This commit is contained in:
boy0001
2015-09-11 20:09:22 +10:00
parent 37a8861fa0
commit c386f33df8
380 changed files with 43490 additions and 33913 deletions

View File

@ -22,8 +22,6 @@ import org.bukkit.plugin.java.JavaPlugin;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.plot.IPlotMain;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.commands.WE_Anywhere;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.ConfigurationNode;
import com.intellectualcrafters.plot.config.Settings;
@ -89,30 +87,34 @@ import com.plotsquared.bukkit.uuid.FileUUIDHandler;
import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.SQLUUIDHandler;
import com.plotsquared.listener.WESubscriber;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public class BukkitMain extends JavaPlugin implements Listener, IPlotMain
{
public static BukkitMain THIS;
public static WorldEditPlugin worldEdit;
private int[] version;
@Override
public int[] getServerVersion() {
if (version == null) {
try {
public int[] getServerVersion()
{
if (version == null)
{
try
{
version = new int[3];
final String[] split = Bukkit.getBukkitVersion().split("-")[0].split("\\.");
version[0] = Integer.parseInt(split[0]);
version[1] = Integer.parseInt(split[1]);
if (split.length == 3) {
if (split.length == 3)
{
version[2] = Integer.parseInt(split[2]);
}
} catch (Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
PS.debug(StringMan.getString(Bukkit.getBukkitVersion()));
PS.debug(StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\.")));
@ -121,93 +123,113 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
}
return version;
}
@Override
public void onEnable() {
public void onEnable()
{
THIS = this;
PS.instance = new PS(this, "Bukkit");
}
@Override
public void onDisable() {
public void onDisable()
{
PS.get().disable();
Bukkit.getScheduler().cancelTasks(this);
THIS = null;
}
@Override
public void log(String message) {
if (message == null) {
return;
}
if (THIS != null && Bukkit.getServer().getConsoleSender() != null) {
try {
public void log(String message)
{
if (message == null) { return; }
if ((THIS != null) && (Bukkit.getServer().getConsoleSender() != null))
{
try
{
message = C.color(message);
if (!Settings.CONSOLE_COLOR) {
if (!Settings.CONSOLE_COLOR)
{
message = ChatColor.stripColor(message);
}
Bukkit.getServer().getConsoleSender().sendMessage(message);
return;
}
catch (Throwable e) {}
catch (final Throwable e)
{}
}
System.out.println(ConsoleColors.fromString(message));
}
@Override
public void disable() {
if (THIS != null) {
public void disable()
{
if (THIS != null)
{
onDisable();
}
}
@Override
public int[] getPluginVersion() {
String[] split = this.getDescription().getVersion().split("\\.");
public int[] getPluginVersion()
{
final String[] split = getDescription().getVersion().split("\\.");
return new int[] { Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]) };
}
@Override
public void registerCommands() {
public void registerCommands()
{
final BukkitCommand bcmd = new BukkitCommand();
final PluginCommand plotCommand = getCommand("plots");
plotCommand.setExecutor(bcmd);
plotCommand.setAliases(Arrays.asList("p", "ps", "plotme", "plot"));
plotCommand.setTabCompleter(bcmd);
}
@Override
public File getDirectory() {
public File getDirectory()
{
return getDataFolder();
}
@Override
public TaskManager getTaskManager() {
public TaskManager getTaskManager()
{
return new BukkitTaskManager();
}
@Override
public void runEntityTask() {
public void runEntityTask()
{
log(C.PREFIX.s() + "KillAllEntities started.");
TaskManager.runTaskRepeat(new Runnable() {
TaskManager.runTaskRepeat(new Runnable()
{
long ticked = 0l;
long error = 0l;
@Override
public void run() {
if (this.ticked > 36_000L) {
this.ticked = 0l;
if (this.error > 0) {
log(C.PREFIX.s() + "KillAllEntities has been running for 6 hours. Errors: " + this.error);
public void run()
{
if (ticked > 36_000L)
{
ticked = 0l;
if (error > 0)
{
log(C.PREFIX.s() + "KillAllEntities has been running for 6 hours. Errors: " + error);
}
this.error = 0l;
error = 0l;
}
World world;
for (final PlotWorld pw : PS.get().getPlotWorldObjects()) {
for (final PlotWorld pw : PS.get().getPlotWorldObjects())
{
world = Bukkit.getWorld(pw.worldname);
try {
for (Entity entity : world.getEntities()) {
switch (entity.getType()) {
try
{
for (final Entity entity : world.getEntities())
{
switch (entity.getType())
{
case EGG:
case ENDER_CRYSTAL:
case COMPLEX_PART:
@ -223,7 +245,8 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case UNKNOWN:
case ITEM_FRAME:
case PAINTING:
case PLAYER: {
case PLAYER:
{
// non moving / unremovable
continue;
}
@ -231,7 +254,8 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case SPLASH_POTION:
case SNOWBALL:
case ENDER_PEARL:
case ARROW: {
case ARROW:
{
// managed elsewhere | projectile
continue;
}
@ -242,24 +266,29 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
case BOAT: {
if (!Settings.KILL_ROAD_VEHICLES) {
case BOAT:
{
if (!Settings.KILL_ROAD_VEHICLES)
{
continue;
}
Location loc = entity.getLocation();
if (MainUtil.isPlotRoad(BukkitUtil.getLocation(loc))) {
final Location loc = entity.getLocation();
if (MainUtil.isPlotRoad(BukkitUtil.getLocation(loc)))
{
entity.remove();
}
break;
}
case SMALL_FIREBALL:
case FIREBALL:
case DROPPED_ITEM: {
case DROPPED_ITEM:
{
// dropped item
continue;
}
case PRIMED_TNT:
case FALLING_BLOCK: {
case FALLING_BLOCK:
{
// managed elsewhere
continue;
}
@ -295,14 +324,18 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case WITHER:
case WOLF:
case ZOMBIE:
default: {
if (!Settings.KILL_ROAD_MOBS) {
default:
{
if (!Settings.KILL_ROAD_MOBS)
{
continue;
}
Location loc = entity.getLocation();
if (MainUtil.isPlotRoad(BukkitUtil.getLocation(loc))) {
Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player)) {
final Location loc = entity.getLocation();
if (MainUtil.isPlotRoad(BukkitUtil.getLocation(loc)))
{
final Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player))
{
entity.remove();
}
}
@ -310,112 +343,143 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
}
}
}
} catch (final Throwable e) {
++this.error;
} finally {
++this.ticked;
}
catch (final Throwable e)
{
++error;
}
finally
{
++ticked;
}
}
}
}, 20);
}
@Override
final public ChunkGenerator getDefaultWorldGenerator(final String world, final String id) {
final public ChunkGenerator getDefaultWorldGenerator(final String world, final String id)
{
WorldEvents.lastWorld = world;
if (!PS.get().setupPlotWorld(world, id)) {
return null;
}
HybridGen result = new HybridGen(world);
TaskManager.runTaskLater(new Runnable() {
if (!PS.get().setupPlotWorld(world, id)) { return null; }
final HybridGen result = new HybridGen(world);
TaskManager.runTaskLater(new Runnable()
{
@Override
public void run() {
if (WorldEvents.lastWorld != null && WorldEvents.lastWorld.equals(world)) {
public void run()
{
if ((WorldEvents.lastWorld != null) && WorldEvents.lastWorld.equals(world))
{
WorldEvents.lastWorld = null;
}
}
}, 20);
return result;
}
@Override
public void registerPlayerEvents() {
public void registerPlayerEvents()
{
getServer().getPluginManager().registerEvents(new PlayerEvents(), this);
if (PS.get().checkVersion(this.getServerVersion(), 1, 8, 0)) {
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0))
{
getServer().getPluginManager().registerEvents(new PlayerEvents_1_8(), this);
}
if (PS.get().checkVersion(this.getServerVersion(), 1, 8, 3)) {
if (PS.get().checkVersion(getServerVersion(), 1, 8, 3))
{
getServer().getPluginManager().registerEvents(new PlayerEvents_1_8_3(), this);
}
}
@Override
public void registerInventoryEvents() {
public void registerInventoryEvents()
{
// Part of PlayerEvents - can be moved if necessary
}
@Override
public void registerPlotPlusEvents() {
public void registerPlotPlusEvents()
{
PlotPlusListener.startRunnable(this);
getServer().getPluginManager().registerEvents(new PlotPlusListener(), this);
}
@Override
public void registerForceFieldEvents() {
public void registerForceFieldEvents()
{
getServer().getPluginManager().registerEvents(new ForceFieldListener(), this);
}
@Override
public boolean initWorldEdit() {
if (getServer().getPluginManager().getPlugin("WorldEdit") != null) {
public boolean initWorldEdit()
{
if (getServer().getPluginManager().getPlugin("WorldEdit") != null)
{
BukkitMain.worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit");
final String version = BukkitMain.worldEdit.getDescription().getVersion();
if ((version != null) && version.startsWith("5.")) {
if ((version != null) && version.startsWith("5."))
{
log("&cThis version of WorldEdit does not support PlotSquared.");
log("&cPlease use WorldEdit 6+ for masking support");
log("&c - http://builds.enginehub.org/job/worldedit");
} else {
}
else
{
getServer().getPluginManager().registerEvents(new WEListener(), this);
return true;
}
}
return false;
}
@Override
public EconHandler getEconomyHandler() {
try {
BukkitEconHandler econ = new BukkitEconHandler();
if (econ.init()) {
return econ;
}
} catch (Throwable e) {
public EconHandler getEconomyHandler()
{
try
{
final BukkitEconHandler econ = new BukkitEconHandler();
if (econ.init()) { return econ; }
}
catch (final Throwable e)
{}
return null;
}
@Override
public BlockManager initBlockManager() {
if (PS.get().checkVersion(this.getServerVersion(), 1, 8, 0)) {
try {
public BlockManager initBlockManager()
{
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0))
{
try
{
BukkitSetBlockManager.setBlockManager = new SetBlockFast_1_8();
} catch (final Throwable e) {
}
catch (final Throwable e)
{
e.printStackTrace();
BukkitSetBlockManager.setBlockManager = new SetBlockSlow();
}
try {
try
{
new SendChunk();
MainUtil.canSendChunk = true;
} catch (final Throwable e) {
}
catch (final Throwable e)
{
e.printStackTrace();
MainUtil.canSendChunk = false;
}
} else {
try {
}
else
{
try
{
BukkitSetBlockManager.setBlockManager = new SetBlockFast();
} catch (final Throwable e) {
}
catch (final Throwable e)
{
MainUtil.canSetFast = false;
BukkitSetBlockManager.setBlockManager = new SetBlockSlow();
}
@ -423,156 +487,206 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
BlockUpdateUtil.setBlockManager = BukkitSetBlockManager.setBlockManager;
return BlockManager.manager = new BukkitUtil();
}
@Override
public boolean initPlotMeConverter() {
TaskManager.runTaskLaterAsync(new Runnable() {
public boolean initPlotMeConverter()
{
TaskManager.runTaskLaterAsync(new Runnable()
{
@Override
public void run() {
if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) return;
if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) return;
if (new LikePlotMeConverter("AthionPlots").run(new ClassicPlotMeConnector())) return;
public void run()
{
if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) {
return;
}
if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) {
return;
}
if (new LikePlotMeConverter("AthionPlots").run(new ClassicPlotMeConnector())) {
return;
}
}
}, 20);
return Bukkit.getPluginManager().getPlugin("PlotMe") != null || Bukkit.getPluginManager().getPlugin("AthionPlots") != null;
return (Bukkit.getPluginManager().getPlugin("PlotMe") != null) || (Bukkit.getPluginManager().getPlugin("AthionPlots") != null);
}
@Override
public BukkitGeneratorWrapper getGenerator(final String world, final String name) {
if (name == null) {
return new BukkitGeneratorWrapper(world, null);
}
public BukkitGeneratorWrapper getGenerator(final String world, final String name)
{
if (name == null) { return new BukkitGeneratorWrapper(world, null); }
final Plugin gen_plugin = Bukkit.getPluginManager().getPlugin(name);
ChunkGenerator gen;
if ((gen_plugin != null) && gen_plugin.isEnabled()) {
if ((gen_plugin != null) && gen_plugin.isEnabled())
{
gen = gen_plugin.getDefaultWorldGenerator(world, "");
} else {
}
else
{
gen = new HybridGen(world);
}
return new BukkitGeneratorWrapper(world, gen);
}
@Override
public HybridUtils initHybridUtils() {
public HybridUtils initHybridUtils()
{
return new BukkitHybridUtils();
}
@Override
public SetupUtils initSetupUtils() {
public SetupUtils initSetupUtils()
{
return new BukkitSetupUtils();
}
@Override
public UUIDHandlerImplementation initUUIDHandler() {
final boolean checkVersion = PS.get().checkVersion(this.getServerVersion(), 1, 7, 6);
public UUIDHandlerImplementation initUUIDHandler()
{
final boolean checkVersion = PS.get().checkVersion(getServerVersion(), 1, 7, 6);
UUIDWrapper wrapper;
if (Settings.OFFLINE_MODE) {
if (Settings.UUID_LOWERCASE) {
if (Settings.OFFLINE_MODE)
{
if (Settings.UUID_LOWERCASE)
{
wrapper = (new LowerOfflineUUIDWrapper());
} else {
wrapper = (new OfflineUUIDWrapper());
}
Settings.OFFLINE_MODE = true;
} else if (checkVersion) {
wrapper = (new DefaultUUIDWrapper());
Settings.OFFLINE_MODE = false;
} else {
if (Settings.UUID_LOWERCASE) {
wrapper = (new LowerOfflineUUIDWrapper());
} else {
else
{
wrapper = (new OfflineUUIDWrapper());
}
Settings.OFFLINE_MODE = true;
}
if (!checkVersion) {
else if (checkVersion)
{
wrapper = (new DefaultUUIDWrapper());
Settings.OFFLINE_MODE = false;
}
else
{
if (Settings.UUID_LOWERCASE)
{
wrapper = (new LowerOfflineUUIDWrapper());
}
else
{
wrapper = (new OfflineUUIDWrapper());
}
Settings.OFFLINE_MODE = true;
}
if (!checkVersion)
{
log(C.PREFIX.s() + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature.");
Settings.TITLES = false;
FlagManager.removeFlag(FlagManager.getFlag("titles"));
} else {
}
else
{
AbstractTitle.TITLE_CLASS = new DefaultTitle();
if (wrapper instanceof DefaultUUIDWrapper) {
if (wrapper instanceof DefaultUUIDWrapper)
{
Settings.TWIN_MODE_UUID = true;
} else if (wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) {
}
else if ((wrapper.getClass() == OfflineUUIDWrapper.class) && !Bukkit.getOnlineMode())
{
Settings.TWIN_MODE_UUID = true;
}
}
if (Settings.OFFLINE_MODE) {
if (Settings.OFFLINE_MODE)
{
log(C.PREFIX.s() + " &6PlotSquared is using Offline Mode UUIDs either because of user preference, or because you are using an old version of Bukkit");
} else {
}
else
{
log(C.PREFIX.s() + " &6PlotSquared is using online UUIDs");
}
return Settings.USE_SQLUUIDHANDLER ? new SQLUUIDHandler(wrapper) : new FileUUIDHandler(wrapper);
}
@Override
public ChunkManager initChunkManager() {
public ChunkManager initChunkManager()
{
return new BukkitChunkManager();
}
@Override
public EventUtil initEventUtil() {
public EventUtil initEventUtil()
{
return new BukkitEventUtil();
}
@Override
public void registerTNTListener() {
public void registerTNTListener()
{
getServer().getPluginManager().registerEvents(new TNTListener(), this);
}
@Override
public void unregister(PlotPlayer player) {
public void unregister(final PlotPlayer player)
{
BukkitUtil.removePlayer(player.getName());
}
@Override
public void registerChunkProcessor() {
public void registerChunkProcessor()
{
getServer().getPluginManager().registerEvents(new ChunkListener(), this);
}
@Override
public void registerWorldEvents() {
public void registerWorldEvents()
{
getServer().getPluginManager().registerEvents(new WorldEvents(), this);
}
@Override
public InventoryUtil initInventoryUtil() {
public InventoryUtil initInventoryUtil()
{
return new BukkitInventoryUtil();
}
@Override
public String getServerName() {
public String getServerName()
{
return Bukkit.getServerName();
}
@Override
public void startMetrics() {
try {
public void startMetrics()
{
try
{
final Metrics metrics = new Metrics(this);
metrics.start();
log(C.PREFIX.s() + "&6Metrics enabled.");
} catch (final Exception e) {
}
catch (final Exception e)
{
log(C.PREFIX.s() + "&cFailed to load up metrics.");
}
}
@Override
public void setGenerator(String worldname) {
public void setGenerator(final String worldname)
{
World world = BukkitUtil.getWorld(worldname);
if (world == null) {
if (world == null)
{
// create world
ConfigurationSection worldConfig = PS.get().config.getConfigurationSection("worlds." + worldname);
final ConfigurationSection worldConfig = PS.get().config.getConfigurationSection("worlds." + worldname);
String manager = worldConfig.getString("generator.plugin");
if (manager == null) {
if (manager == null)
{
manager = "PlotSquared";
}
String generator = worldConfig.getString("generator.init");
if (generator == null) {
if (generator == null)
{
generator = manager;
}
int type = worldConfig.getInt("generator.type");
int terrain = worldConfig.getInt("generator.terrain");
SetupObject setup = new SetupObject();
final int type = worldConfig.getInt("generator.type");
final int terrain = worldConfig.getInt("generator.terrain");
final SetupObject setup = new SetupObject();
setup.plotManager = manager;
setup.setupGenerator = generator;
setup.type = type;
@ -581,75 +695,93 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
setup.world = worldname;
SetupUtils.manager.setupWorld(setup);
}
else {
try {
if (!PS.get().isPlotWorld(worldname)) {
else
{
try
{
if (!PS.get().isPlotWorld(worldname))
{
SetGenCB.setGenerator(BukkitUtil.getWorld(worldname));
}
} catch (Exception e) {
}
catch (final Exception e)
{
log("Failed to reload world: " + world);
Bukkit.getServer().unloadWorld(world, false);
}
}
world = Bukkit.getWorld(worldname);
final ChunkGenerator gen = world.getGenerator();
if (gen instanceof BukkitPlotGenerator) {
PS.get().loadWorld(worldname, new BukkitGeneratorWrapper(worldname, (BukkitPlotGenerator) gen));
if (gen instanceof BukkitPlotGenerator)
{
PS.get().loadWorld(worldname, new BukkitGeneratorWrapper(worldname, gen));
}
else {
if (PS.get().config.contains("worlds." + worldname)) {
else
{
if (PS.get().config.contains("worlds." + worldname))
{
PS.get().loadWorld(worldname, new BukkitGeneratorWrapper(worldname, null));
}
}
}
@Override
public SchematicHandler initSchematicHandler() {
public SchematicHandler initSchematicHandler()
{
return new BukkitSchematicHandler();
}
@Override
public AbstractTitle initTitleManager() {
public AbstractTitle initTitleManager()
{
// Already initialized in UUID handler
return AbstractTitle.TITLE_CLASS;
}
@Override
public PlotPlayer wrapPlayer(Object obj) {
if (obj instanceof Player) {
public PlotPlayer wrapPlayer(final Object obj)
{
if (obj instanceof Player)
{
return BukkitUtil.getPlayer((Player) obj);
}
else if (obj instanceof OfflinePlayer) {
else if (obj instanceof OfflinePlayer)
{
return BukkitUtil.getPlayer((OfflinePlayer) obj);
}
else if (obj instanceof String) {
else if (obj instanceof String)
{
return UUIDHandler.getPlayer((String) obj);
}
else if (obj instanceof UUID) {
return UUIDHandler.getPlayer((UUID) obj);
}
else if (obj instanceof UUID) { return UUIDHandler.getPlayer((UUID) obj); }
return null;
}
@Override
public String getNMSPackage() {
public String getNMSPackage()
{
final Server server = Bukkit.getServer();
final Class<?> bukkitServerClass = server.getClass();
String[] pas = bukkitServerClass.getName().split("\\.");
if (pas.length == 5) {
if (pas.length == 5)
{
final String verB = pas[3];
return verB;
}
try {
try
{
final Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle");
final Object handle = getHandle.invoke(server);
final Class handleServerClass = handle.getClass();
pas = handleServerClass.getName().split("\\.");
if (pas.length == 5) {
if (pas.length == 5)
{
final String verM = pas[3];
return verM;
return verM;
}
} catch (Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
}
PS.debug("Unknown NMS package: " + StringMan.getString(pas));
@ -657,11 +789,14 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
}
@Override
public ChatManager<?> initChatManager() {
if (Settings.FANCY_CHAT) {
public ChatManager<?> initChatManager()
{
if (Settings.FANCY_CHAT)
{
return new BukkitChatManager();
}
else {
else
{
return new BukkitPlainChatManager();
}
}

View File

@ -16,61 +16,62 @@ import org.apache.commons.lang.Validate;
* @param <E> The type of elements in the array.
* @see Arrays
*/
public final class ArrayWrapper<E> {
public final class ArrayWrapper<E>
{
/**
* Creates an array wrapper with some elements.
* @param elements The elements of the array.
*/
public ArrayWrapper(E... elements){
setArray(elements);
}
private E[] _array;
/**
* Retrieves a reference to the wrapped array instance.
* @return The array wrapped by this instance.
*/
public E[] getArray(){
return _array;
}
/**
* Set this wrapper to wrap a new array instance.
* @param array The new wrapped array.
*/
public void setArray(E[] array){
Validate.notNull(array, "The array must not be null.");
_array = array;
}
/**
* Determines if this object has a value equivalent to another object.
* @see Arrays#equals(Object[], Object[])
*/
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object other)
/**
* Creates an array wrapper with some elements.
* @param elements The elements of the array.
*/
public ArrayWrapper(final E... elements)
{
if (!(other instanceof ArrayWrapper))
{
return false;
}
return Arrays.equals(_array, ((ArrayWrapper)other)._array);
setArray(elements);
}
/**
* Gets the hash code represented by this objects value.
* @see Arrays#hashCode(Object[])
* @return This object's hash code.
*/
private E[] _array;
/**
* Retrieves a reference to the wrapped array instance.
* @return The array wrapped by this instance.
*/
public E[] getArray()
{
return _array;
}
/**
* Set this wrapper to wrap a new array instance.
* @param array The new wrapped array.
*/
public void setArray(final E[] array)
{
Validate.notNull(array, "The array must not be null.");
_array = array;
}
/**
* Determines if this object has a value equivalent to another object.
* @see Arrays#equals(Object[], Object[])
*/
@SuppressWarnings("rawtypes")
@Override
public boolean equals(final Object other)
{
if (!(other instanceof ArrayWrapper)) { return false; }
return Arrays.equals(_array, ((ArrayWrapper) other)._array);
}
/**
* Gets the hash code represented by this objects value.
* @see Arrays#hashCode(Object[])
* @return This object's hash code.
*/
@Override
public int hashCode()
{
return Arrays.hashCode(_array);
}
/**
* Converts an iterable element collection to an array of elements.
* The iteration order of the specified object will be used as the array element order.
@ -78,29 +79,34 @@ public final class ArrayWrapper<E> {
* @param c The type of the elements of the array.
* @return An array of elements in the specified iterable.
*/
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Iterable<? extends T> list, Class<T> c) {
@SuppressWarnings("unchecked")
public static <T> T[] toArray(final Iterable<? extends T> list, final Class<T> c)
{
int size = -1;
if(list instanceof Collection<?>){
@SuppressWarnings("rawtypes")
Collection coll = (Collection)list;
size = coll.size();
if (list instanceof Collection<?>)
{
@SuppressWarnings("rawtypes")
final Collection coll = (Collection) list;
size = coll.size();
}
if(size < 0){
size = 0;
// Ugly hack: Count it ourselves
for(@SuppressWarnings("unused") T element : list){
size++;
}
if (size < 0)
{
size = 0;
// Ugly hack: Count it ourselves
for (@SuppressWarnings("unused")
final T element : list)
{
size++;
}
}
T[] result = (T[]) Array.newInstance(c, size);
final T[] result = (T[]) Array.newInstance(c, size);
int i = 0;
for(T element : list){ // Assumes iteration order is consistent
result[i++] = element; // Assign array element at index THEN increment counter
}
for (final T element : list)
{ // Assumes iteration order is consistent
result[i++] = element; // Assign array element at index THEN increment counter
}
return result;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -7,13 +7,14 @@ import com.google.gson.stream.JsonWriter;
/**
* Represents an object that can be serialized to a JSON writer instance.
*/
interface JsonRepresentedObject {
interface JsonRepresentedObject
{
/**
* Writes the JSON representation of this object to the specified writer.
* @param writer The JSON writer which will receive the object.
* @throws IOException If an error occurs writing to the stream.
*/
void writeJson(final JsonWriter writer) throws IOException;
/**
* Writes the JSON representation of this object to the specified writer.
* @param writer The JSON writer which will receive the object.
* @throws IOException If an error occurs writing to the stream.
*/
void writeJson(JsonWriter writer) throws IOException;
}

View File

@ -12,35 +12,43 @@ import com.intellectualcrafters.configuration.serialization.ConfigurationSeriali
* Writes by this object will not write name values nor begin/end objects in the JSON stream.
* All writes merely write the represented string value.
*/
final class JsonString implements JsonRepresentedObject, ConfigurationSerializable {
final class JsonString implements JsonRepresentedObject, ConfigurationSerializable
{
private String _value;
public JsonString(CharSequence value){
_value = value == null ? null : value.toString();
}
private final String _value;
@Override
public void writeJson(JsonWriter writer) throws IOException {
writer.value(getValue());
}
public String getValue(){
return _value;
}
public JsonString(final CharSequence value)
{
_value = value == null ? null : value.toString();
}
public Map<String, Object> serialize() {
HashMap<String, Object> theSingleValue = new HashMap<String, Object>();
theSingleValue.put("stringValue", _value);
return theSingleValue;
}
public static JsonString deserialize(Map<String, Object> map){
return new JsonString(map.get("stringValue").toString());
}
@Override
public String toString(){
return _value;
}
@Override
public void writeJson(final JsonWriter writer) throws IOException
{
writer.value(getValue());
}
public String getValue()
{
return _value;
}
@Override
public Map<String, Object> serialize()
{
final HashMap<String, Object> theSingleValue = new HashMap<String, Object>();
theSingleValue.put("stringValue", _value);
return theSingleValue;
}
public static JsonString deserialize(final Map<String, Object> map)
{
return new JsonString(map.get("stringValue").toString());
}
@Override
public String toString()
{
return _value;
}
}

View File

@ -18,137 +18,167 @@ import com.intellectualcrafters.configuration.serialization.ConfigurationSeriali
/**
* Internal class: Represents a component of a JSON-serializable {@link FancyMessage}.
*/
final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable {
final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable
{
ChatColor color = ChatColor.WHITE;
ArrayList<ChatColor> styles = new ArrayList<ChatColor>();
String clickActionName = null, clickActionData = null,
hoverActionName = null;
JsonRepresentedObject hoverActionData = null;
TextualComponent text = null;
String insertionData = null;
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<JsonRepresentedObject>();
ChatColor color = ChatColor.WHITE;
ArrayList<ChatColor> styles = new ArrayList<ChatColor>();
String clickActionName = null, clickActionData = null,
hoverActionName = null;
JsonRepresentedObject hoverActionData = null;
TextualComponent text = null;
String insertionData = null;
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<JsonRepresentedObject>();
MessagePart(final TextualComponent text){
this.text = text;
}
MessagePart(final TextualComponent text)
{
this.text = text;
}
MessagePart() {
this.text = null;
}
MessagePart()
{
text = null;
}
boolean hasText() {
return text != null;
}
boolean hasText()
{
return text != null;
}
@Override
@SuppressWarnings("unchecked")
public MessagePart clone() throws CloneNotSupportedException{
MessagePart obj = (MessagePart)super.clone();
obj.styles = (ArrayList<ChatColor>)styles.clone();
if(hoverActionData instanceof JsonString){
obj.hoverActionData = new JsonString(((JsonString)hoverActionData).getValue());
}else if(hoverActionData instanceof FancyMessage){
obj.hoverActionData = ((FancyMessage)hoverActionData).clone();
}
obj.translationReplacements = (ArrayList<JsonRepresentedObject>)translationReplacements.clone();
return obj;
@Override
@SuppressWarnings("unchecked")
public MessagePart clone() throws CloneNotSupportedException
{
final MessagePart obj = (MessagePart) super.clone();
obj.styles = (ArrayList<ChatColor>) styles.clone();
if (hoverActionData instanceof JsonString)
{
obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue());
}
else if (hoverActionData instanceof FancyMessage)
{
obj.hoverActionData = ((FancyMessage) hoverActionData).clone();
}
obj.translationReplacements = (ArrayList<JsonRepresentedObject>) translationReplacements.clone();
return obj;
}
}
static final BiMap<ChatColor, String> stylesToNames;
static final BiMap<ChatColor, String> stylesToNames;
static{
ImmutableBiMap.Builder<ChatColor, String> builder = ImmutableBiMap.builder();
for (final ChatColor style : ChatColor.values()){
if(!style.isFormat()){
continue;
}
static
{
final ImmutableBiMap.Builder<ChatColor, String> builder = ImmutableBiMap.builder();
for (final ChatColor style : ChatColor.values())
{
if (!style.isFormat())
{
continue;
}
String styleName;
switch (style) {
case MAGIC:
styleName = "obfuscated"; break;
case UNDERLINE:
styleName = "underlined"; break;
default:
styleName = style.name().toLowerCase(); break;
}
builder.put(style, styleName);
}
stylesToNames = builder.build();
}
String styleName;
switch (style)
{
case MAGIC:
styleName = "obfuscated";
break;
case UNDERLINE:
styleName = "underlined";
break;
default:
styleName = style.name().toLowerCase();
break;
}
public void writeJson(JsonWriter json) {
try {
json.beginObject();
text.writeJson(json);
json.name("color").value(color.name().toLowerCase());
for (final ChatColor style : styles) {
json.name(stylesToNames.get(style)).value(true);
}
if (clickActionName != null && clickActionData != null) {
json.name("clickEvent")
.beginObject()
.name("action").value(clickActionName)
.name("value").value(clickActionData)
.endObject();
}
if (hoverActionName != null && hoverActionData != null) {
json.name("hoverEvent")
.beginObject()
.name("action").value(hoverActionName)
.name("value");
hoverActionData.writeJson(json);
json.endObject();
}
if(insertionData != null){
json.name("insertion").value(insertionData);
}
if(translationReplacements.size() > 0 && text != null && TextualComponent.isTranslatableText(text)){
json.name("with").beginArray();
for(JsonRepresentedObject obj : translationReplacements){
obj.writeJson(json);
}
json.endArray();
}
json.endObject();
} catch(IOException e){
Bukkit.getLogger().log(Level.WARNING, "A problem occured during writing of JSON string", e);
}
}
builder.put(style, styleName);
}
stylesToNames = builder.build();
}
public Map<String, Object> serialize() {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("text", text);
map.put("styles", styles);
map.put("color", color.getChar());
map.put("hoverActionName", hoverActionName);
map.put("hoverActionData", hoverActionData);
map.put("clickActionName", clickActionName);
map.put("clickActionData", clickActionData);
map.put("insertion", insertionData);
map.put("translationReplacements", translationReplacements);
return map;
}
@Override
public void writeJson(final JsonWriter json)
{
try
{
json.beginObject();
text.writeJson(json);
json.name("color").value(color.name().toLowerCase());
for (final ChatColor style : styles)
{
json.name(stylesToNames.get(style)).value(true);
}
if ((clickActionName != null) && (clickActionData != null))
{
json.name("clickEvent")
.beginObject()
.name("action").value(clickActionName)
.name("value").value(clickActionData)
.endObject();
}
if ((hoverActionName != null) && (hoverActionData != null))
{
json.name("hoverEvent")
.beginObject()
.name("action").value(hoverActionName)
.name("value");
hoverActionData.writeJson(json);
json.endObject();
}
if (insertionData != null)
{
json.name("insertion").value(insertionData);
}
if ((translationReplacements.size() > 0) && (text != null) && TextualComponent.isTranslatableText(text))
{
json.name("with").beginArray();
for (final JsonRepresentedObject obj : translationReplacements)
{
obj.writeJson(json);
}
json.endArray();
}
json.endObject();
}
catch (final IOException e)
{
Bukkit.getLogger().log(Level.WARNING, "A problem occured during writing of JSON string", e);
}
}
@SuppressWarnings("unchecked")
public static MessagePart deserialize(Map<String, Object> serialized){
MessagePart part = new MessagePart((TextualComponent)serialized.get("text"));
part.styles = (ArrayList<ChatColor>)serialized.get("styles");
part.color = ChatColor.getByChar(serialized.get("color").toString());
part.hoverActionName = (String)serialized.get("hoverActionName");
part.hoverActionData = (JsonRepresentedObject)serialized.get("hoverActionData");
part.clickActionName = (String)serialized.get("clickActionName");
part.clickActionData = (String)serialized.get("clickActionData");
part.insertionData = (String)serialized.get("insertion");
part.translationReplacements = (ArrayList<JsonRepresentedObject>)serialized.get("translationReplacements");
return part;
}
@Override
public Map<String, Object> serialize()
{
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("text", text);
map.put("styles", styles);
map.put("color", color.getChar());
map.put("hoverActionName", hoverActionName);
map.put("hoverActionData", hoverActionData);
map.put("clickActionName", clickActionName);
map.put("clickActionData", clickActionData);
map.put("insertion", insertionData);
map.put("translationReplacements", translationReplacements);
return map;
}
static{
ConfigurationSerialization.registerClass(MessagePart.class);
}
@SuppressWarnings("unchecked")
public static MessagePart deserialize(final Map<String, Object> serialized)
{
final MessagePart part = new MessagePart((TextualComponent) serialized.get("text"));
part.styles = (ArrayList<ChatColor>) serialized.get("styles");
part.color = ChatColor.getByChar(serialized.get("color").toString());
part.hoverActionName = (String) serialized.get("hoverActionName");
part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData");
part.clickActionName = (String) serialized.get("clickActionName");
part.clickActionData = (String) serialized.get("clickActionData");
part.insertionData = (String) serialized.get("insertion");
part.translationReplacements = (ArrayList<JsonRepresentedObject>) serialized.get("translationReplacements");
return part;
}
static
{
ConfigurationSerialization.registerClass(MessagePart.class);
}
}

View File

@ -12,202 +12,227 @@ import org.bukkit.Bukkit;
* A class containing static utility methods and caches which are intended as reflective conveniences.
* Unless otherwise noted, upon failure methods will return {@code null}.
*/
public final class Reflection {
public final class Reflection
{
private static String _versionString;
private Reflection(){
}
/**
* Gets the version string from the package name of the CraftBukkit server implementation.
* This is needed to bypass the JAR package name changing on each update.
* @return The version string of the OBC and NMS packages, <em>including the trailing dot</em>.
*/
public synchronized static String getVersion() {
if(_versionString == null){
if(Bukkit.getServer() == null){
// The server hasn't started, static initializer call?
return null;
}
String name = Bukkit.getServer().getClass().getPackage().getName();
_versionString = name.substring(name.lastIndexOf('.') + 1) + ".";
}
return _versionString;
}
private static String _versionString;
/**
* Stores loaded classes from the {@code net.minecraft.server} package.
*/
private static final Map<String, Class<?>> _loadedNMSClasses = new HashMap<String, Class<?>>();
/**
* Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages).
*/
private static final Map<String, Class<?>> _loadedOBCClasses = new HashMap<String, Class<?>>();
/**
* Gets a {@link Class} object representing a type contained within the {@code net.minecraft.server} versioned package.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
* @param className The name of the class, excluding the package, within NMS.
* @return The class instance representing the specified NMS class, or {@code null} if it could not be loaded.
*/
public synchronized static Class<?> getNMSClass(String className) {
if(_loadedNMSClasses.containsKey(className)){
return _loadedNMSClasses.get(className);
}
String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
try {
clazz = Class.forName(fullName);
} catch (Exception e) {
e.printStackTrace();
_loadedNMSClasses.put(className, null);
return null;
}
_loadedNMSClasses.put(className, clazz);
return clazz;
}
private Reflection()
{
/**
* Gets a {@link Class} object representing a type contained within the {@code org.bukkit.craftbukkit} versioned package.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
* @param className The name of the class, excluding the package, within OBC. This name may contain a subpackage name, such as {@code inventory.CraftItemStack}.
* @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded.
*/
public synchronized static Class<?> getOBCClass(String className) {
if(_loadedOBCClasses.containsKey(className)){
return _loadedOBCClasses.get(className);
}
String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
Class<?> clazz = null;
try {
clazz = Class.forName(fullName);
} catch (Exception e) {
e.printStackTrace();
_loadedOBCClasses.put(className, null);
return null;
}
_loadedOBCClasses.put(className, clazz);
return clazz;
}
}
/**
* Attempts to get the NMS handle of a CraftBukkit object.
* <p>
* The only match currently attempted by this method is a retrieval by using a parameterless {@code getHandle()} method implemented by the runtime type of the specified object.
* </p>
* @param obj The object for which to retrieve an NMS handle.
* @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}.
*/
public synchronized static Object getHandle(Object obj) {
try {
return getMethod(obj.getClass(), "getHandle").invoke(obj);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Gets the version string from the package name of the CraftBukkit server implementation.
* This is needed to bypass the JAR package name changing on each update.
* @return The version string of the OBC and NMS packages, <em>including the trailing dot</em>.
*/
public synchronized static String getVersion()
{
if (_versionString == null)
{
if (Bukkit.getServer() == null)
{
// The server hasn't started, static initializer call?
return null;
}
final String name = Bukkit.getServer().getClass().getPackage().getName();
_versionString = name.substring(name.lastIndexOf('.') + 1) + ".";
}
private static final Map<Class<?>, Map<String, Field>> _loadedFields = new HashMap<Class<?>, Map<String, Field>>();
/**
* Retrieves a {@link Field} instance declared by the specified class with the specified name.
* Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
* returned will be an instance or static field.
* <p>
* A global caching mechanism within this class is used to store fields. Combined with synchronization, this guarantees that
* no field will be reflectively looked up twice.
* </p>
* <p>
* If a field is deemed suitable for return, {@link Field#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
* This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
* </p>
* @param clazz The class which contains the field to retrieve.
* @param name The declared name of the field in the class.
* @return A field object with the specified name declared by the specified class.
* @see Class#getDeclaredField(String)
*/
public synchronized static Field getField(Class<?> clazz, String name) {
Map<String, Field> loaded;
if(!_loadedFields.containsKey(clazz)){
loaded = new HashMap<String, Field>();
_loadedFields.put(clazz, loaded);
}else{
loaded = _loadedFields.get(clazz);
}
if(loaded.containsKey(name)){
// If the field is loaded (or cached as not existing), return the relevant value, which might be null
return loaded.get(name);
}
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
loaded.put(name, field);
return field;
} catch (Exception e) {
// Error loading
e.printStackTrace();
// Cache field as not existing
loaded.put(name, null);
return null;
}
}
return _versionString;
}
/**
* Contains loaded methods in a cache.
* The map maps [types to maps of [method names to maps of [parameter types to method instances]]].
*/
private static final Map<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>> _loadedMethods = new HashMap<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>>();
/**
* Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types.
* Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
* returned will be an instance or static field.
* <p>
* A global caching mechanism within this class is used to store method. Combined with synchronization, this guarantees that
* no method will be reflectively looked up twice.
* </p>
* <p>
* If a method is deemed suitable for return, {@link Method#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
* This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
* </p>
* <p>
* This method does <em>not</em> search superclasses of the specified type for methods with the specified signature.
* Callers wishing this behavior should use {@link Class#getDeclaredMethod(String, Class...)}.
* @param clazz The class which contains the method to retrieve.
* @param name The declared name of the method in the class.
* @param args The formal argument types of the method.
* @return A method object with the specified name declared by the specified class.
*/
public synchronized static Method getMethod(Class<?> clazz, String name,
Class<?>... args) {
if(!_loadedMethods.containsKey(clazz)){
_loadedMethods.put(clazz, new HashMap<String, Map<ArrayWrapper<Class<?>>, Method>>());
}
Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames = _loadedMethods.get(clazz);
if(!loadedMethodNames.containsKey(name)){
loadedMethodNames.put(name, new HashMap<ArrayWrapper<Class<?>>, Method>());
}
Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name);
ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<Class<?>>(args);
if(loadedSignatures.containsKey(wrappedArg)){
return loadedSignatures.get(wrappedArg);
}
for (Method m : clazz.getMethods())
if (m.getName().equals(name) && Arrays.equals(args, m.getParameterTypes())) {
m.setAccessible(true);
loadedSignatures.put(wrappedArg, m);
return m;
}
loadedSignatures.put(wrappedArg, null);
return null;
}
/**
* Stores loaded classes from the {@code net.minecraft.server} package.
*/
private static final Map<String, Class<?>> _loadedNMSClasses = new HashMap<String, Class<?>>();
/**
* Stores loaded classes from the {@code org.bukkit.craftbukkit} package (and subpackages).
*/
private static final Map<String, Class<?>> _loadedOBCClasses = new HashMap<String, Class<?>>();
/**
* Gets a {@link Class} object representing a type contained within the {@code net.minecraft.server} versioned package.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
* @param className The name of the class, excluding the package, within NMS.
* @return The class instance representing the specified NMS class, or {@code null} if it could not be loaded.
*/
public synchronized static Class<?> getNMSClass(final String className)
{
if (_loadedNMSClasses.containsKey(className)) { return _loadedNMSClasses.get(className); }
final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
try
{
clazz = Class.forName(fullName);
}
catch (final Exception e)
{
e.printStackTrace();
_loadedNMSClasses.put(className, null);
return null;
}
_loadedNMSClasses.put(className, clazz);
return clazz;
}
/**
* Gets a {@link Class} object representing a type contained within the {@code org.bukkit.craftbukkit} versioned package.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
* @param className The name of the class, excluding the package, within OBC. This name may contain a subpackage name, such as {@code inventory.CraftItemStack}.
* @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded.
*/
public synchronized static Class<?> getOBCClass(final String className)
{
if (_loadedOBCClasses.containsKey(className)) { return _loadedOBCClasses.get(className); }
final String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
Class<?> clazz = null;
try
{
clazz = Class.forName(fullName);
}
catch (final Exception e)
{
e.printStackTrace();
_loadedOBCClasses.put(className, null);
return null;
}
_loadedOBCClasses.put(className, clazz);
return clazz;
}
/**
* Attempts to get the NMS handle of a CraftBukkit object.
* <p>
* The only match currently attempted by this method is a retrieval by using a parameterless {@code getHandle()} method implemented by the runtime type of the specified object.
* </p>
* @param obj The object for which to retrieve an NMS handle.
* @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}.
*/
public synchronized static Object getHandle(final Object obj)
{
try
{
return getMethod(obj.getClass(), "getHandle").invoke(obj);
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
private static final Map<Class<?>, Map<String, Field>> _loadedFields = new HashMap<Class<?>, Map<String, Field>>();
/**
* Retrieves a {@link Field} instance declared by the specified class with the specified name.
* Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
* returned will be an instance or static field.
* <p>
* A global caching mechanism within this class is used to store fields. Combined with synchronization, this guarantees that
* no field will be reflectively looked up twice.
* </p>
* <p>
* If a field is deemed suitable for return, {@link Field#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
* This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
* </p>
* @param clazz The class which contains the field to retrieve.
* @param name The declared name of the field in the class.
* @return A field object with the specified name declared by the specified class.
* @see Class#getDeclaredField(String)
*/
public synchronized static Field getField(final Class<?> clazz, final String name)
{
Map<String, Field> loaded;
if (!_loadedFields.containsKey(clazz))
{
loaded = new HashMap<String, Field>();
_loadedFields.put(clazz, loaded);
}
else
{
loaded = _loadedFields.get(clazz);
}
if (loaded.containsKey(name))
{
// If the field is loaded (or cached as not existing), return the relevant value, which might be null
return loaded.get(name);
}
try
{
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
loaded.put(name, field);
return field;
}
catch (final Exception e)
{
// Error loading
e.printStackTrace();
// Cache field as not existing
loaded.put(name, null);
return null;
}
}
/**
* Contains loaded methods in a cache.
* The map maps [types to maps of [method names to maps of [parameter types to method instances]]].
*/
private static final Map<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>> _loadedMethods = new HashMap<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>>();
/**
* Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types.
* Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
* returned will be an instance or static field.
* <p>
* A global caching mechanism within this class is used to store method. Combined with synchronization, this guarantees that
* no method will be reflectively looked up twice.
* </p>
* <p>
* If a method is deemed suitable for return, {@link Method#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
* This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
* </p>
* <p>
* This method does <em>not</em> search superclasses of the specified type for methods with the specified signature.
* Callers wishing this behavior should use {@link Class#getDeclaredMethod(String, Class...)}.
* @param clazz The class which contains the method to retrieve.
* @param name The declared name of the method in the class.
* @param args The formal argument types of the method.
* @return A method object with the specified name declared by the specified class.
*/
public synchronized static Method getMethod(final Class<?> clazz, final String name,
final Class<?>... args)
{
if (!_loadedMethods.containsKey(clazz))
{
_loadedMethods.put(clazz, new HashMap<String, Map<ArrayWrapper<Class<?>>, Method>>());
}
final Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames = _loadedMethods.get(clazz);
if (!loadedMethodNames.containsKey(name))
{
loadedMethodNames.put(name, new HashMap<ArrayWrapper<Class<?>>, Method>());
}
final Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name);
final ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<Class<?>>(args);
if (loadedSignatures.containsKey(wrappedArg)) { return loadedSignatures.get(wrappedArg); }
for (final Method m : clazz.getMethods())
{
if (m.getName().equals(name) && Arrays.equals(args, m.getParameterTypes()))
{
m.setAccessible(true);
loadedSignatures.put(wrappedArg, m);
return m;
}
}
loadedSignatures.put(wrappedArg, null);
return null;
}
}

View File

@ -16,276 +16,326 @@ import com.intellectualcrafters.configuration.serialization.ConfigurationSeriali
* but also to represent localized strings and other text values.
* <p>Different instances of this class can be created with static constructor methods.</p>
*/
public abstract class TextualComponent implements Cloneable {
public abstract class TextualComponent implements Cloneable
{
static{
ConfigurationSerialization.registerClass(TextualComponent.ArbitraryTextTypeComponent.class);
ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class);
}
@Override
public String toString() {
return getReadableString();
}
/**
* @return The JSON key used to represent text components of this type.
*/
public abstract String getKey();
/**
* @return A readable String
*/
public abstract String getReadableString();
/**
* Clones a textual component instance.
* The returned object should not reference this textual component instance, but should maintain the same key and value.
*/
@Override
public abstract TextualComponent clone() throws CloneNotSupportedException;
/**
* Writes the text data represented by this textual component to the specified JSON writer object.
* A new object within the writer is not started.
* @param writer The object to which to write the JSON data.
* @throws IOException If an error occurs while writing to the stream.
*/
public abstract void writeJson(JsonWriter writer) throws IOException;
static TextualComponent deserialize(Map<String, Object> map){
if(map.containsKey("key") && map.size() == 2 && map.containsKey("value")){
// Arbitrary text component
return ArbitraryTextTypeComponent.deserialize(map);
}else if(map.size() >= 2 && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */){
// Complex JSON object
return ComplexTextTypeComponent.deserialize(map);
}
return null;
}
static boolean isTextKey(String key){
return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector");
}
static boolean isTranslatableText(TextualComponent component){
return component instanceof ComplexTextTypeComponent && ((ComplexTextTypeComponent)component).getKey().equals("translate");
}
/**
* Internal class used to represent all types of text components.
* Exception validating done is on keys and values.
*/
private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
static
{
ConfigurationSerialization.registerClass(TextualComponent.ArbitraryTextTypeComponent.class);
ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class);
}
public ArbitraryTextTypeComponent(String key, String value){
setKey(key);
setValue(value);
}
@Override
public String getKey() {
return _key;
}
@Override
public String toString()
{
return getReadableString();
}
public void setKey(String key) {
Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
_key = key;
}
public String getValue() {
return _value;
}
/**
* @return The JSON key used to represent text components of this type.
*/
public abstract String getKey();
public void setValue(String value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
}
/**
* @return A readable String
*/
public abstract String getReadableString();
private String _key;
private String _value;
@Override
public TextualComponent clone() throws CloneNotSupportedException {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ArbitraryTextTypeComponent(getKey(), getValue());
}
/**
* Clones a textual component instance.
* The returned object should not reference this textual component instance, but should maintain the same key and value.
*/
@Override
public abstract TextualComponent clone() throws CloneNotSupportedException;
@Override
public void writeJson(JsonWriter writer) throws IOException {
writer.name(getKey()).value(getValue());
}
/**
* Writes the text data represented by this textual component to the specified JSON writer object.
* A new object within the writer is not started.
* @param writer The object to which to write the JSON data.
* @throws IOException If an error occurs while writing to the stream.
*/
public abstract void writeJson(final JsonWriter writer) throws IOException;
@SuppressWarnings("serial")
public Map<String, Object> serialize() {
return new HashMap<String, Object>(){{
put("key", getKey());
put("value", getValue());
}};
}
public static ArbitraryTextTypeComponent deserialize(Map<String, Object> map){
return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
}
static TextualComponent deserialize(final Map<String, Object> map)
{
if (map.containsKey("key") && (map.size() == 2) && map.containsKey("value"))
{
// Arbitrary text component
return ArbitraryTextTypeComponent.deserialize(map);
}
else if ((map.size() >= 2) && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */)
{
// Complex JSON object
return ComplexTextTypeComponent.deserialize(map);
}
@Override
public String getReadableString() {
return getValue();
}
}
/**
* Internal class used to represent a text component with a nested JSON value.
* Exception validating done is on keys and values.
*/
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable{
return null;
}
public ComplexTextTypeComponent(String key, Map<String, String> values){
setKey(key);
setValue(values);
}
@Override
public String getKey() {
return _key;
}
static boolean isTextKey(final String key)
{
return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector");
}
public void setKey(String key) {
Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
_key = key;
}
public Map<String, String> getValue() {
return _value;
}
static boolean isTranslatableText(final TextualComponent component)
{
return (component instanceof ComplexTextTypeComponent) && ((ComplexTextTypeComponent) component).getKey().equals("translate");
}
public void setValue(Map<String, String> value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
}
/**
* Internal class used to represent all types of text components.
* Exception validating done is on keys and values.
*/
private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable
{
private String _key;
private Map<String, String> _value;
@Override
public TextualComponent clone() throws CloneNotSupportedException {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ComplexTextTypeComponent(getKey(), getValue());
}
public ArbitraryTextTypeComponent(final String key, final String value)
{
setKey(key);
setValue(value);
}
@Override
public void writeJson(JsonWriter writer) throws IOException {
writer.name(getKey());
writer.beginObject();
for(Map.Entry<String, String> jsonPair : _value.entrySet()){
writer.name(jsonPair.getKey()).value(jsonPair.getValue());
}
writer.endObject();
}
@SuppressWarnings("serial")
public Map<String, Object> serialize() {
return new java.util.HashMap<String, Object>(){{
put("key", getKey());
for(Map.Entry<String, String> valEntry : getValue().entrySet()){
put("value." + valEntry.getKey(), valEntry.getValue());
}
}};
}
public static ComplexTextTypeComponent deserialize(Map<String, Object> map){
String key = null;
Map<String, String> value = new HashMap<String, String>();
for(Map.Entry<String, Object> valEntry : map.entrySet()){
if(valEntry.getKey().equals("key")){
key = (String) valEntry.getValue();
}else if(valEntry.getKey().startsWith("value.")){
value.put(((String) valEntry.getKey()).substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
}
}
return new ComplexTextTypeComponent(key, value);
}
@Override
public String getReadableString() {
return getKey();
}
}
/**
* Create a textual component representing a string literal.
* This is the default type of textual component when a single string literal is given to a method.
* @param textValue The text which will be represented.
* @return The text component representing the specified literal text.
*/
public static TextualComponent rawText(String textValue){
return new ArbitraryTextTypeComponent("text", textValue);
}
@Override
public String getKey()
{
return _key;
}
/**
* Create a textual component representing a localized string.
* The client will see this text component as their localized version of the specified string <em>key</em>, which can be overridden by a resource pack.
* <p>
* If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to the client.
* </p>
* @param translateKey The string key which maps to localized text.
* @return The text component representing the specified localized text.
*/
public static TextualComponent localizedText(String translateKey){
return new ArbitraryTextTypeComponent("translate", translateKey);
}
private static void throwUnsupportedSnapshot(){
throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
}
/**
* Create a textual component representing a scoreboard value.
* The client will see their own score for the specified objective as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
* @param scoreboardObjective The name of the objective for which to display the score.
* @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during JSON serialization.
*/
public static TextualComponent objectiveScore(String scoreboardObjective){
return objectiveScore("*", scoreboardObjective);
}
/**
* Create a textual component representing a scoreboard value.
* The client will see the score of the specified player for the specified objective as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
* @param playerName The name of the player whos score will be shown. If this string represents the single-character sequence "*", the viewing player's score will be displayed.
* Standard minecraft selectors (@a, @p, etc) are <em>not</em> supported.
* @param scoreboardObjective The name of the objective for which to display the score.
* @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during JSON serialization.
*/
public static TextualComponent objectiveScore(String playerName, String scoreboardObjective){
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly
return new ComplexTextTypeComponent("score", ImmutableMap.<String, String>builder()
.put("name", playerName)
.put("objective", scoreboardObjective)
.build());
}
/**
* Create a textual component representing a player name, retrievable by using a standard minecraft selector.
* The client will see the players or entities captured by the specified selector as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
* @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in the place of this text component.
* @return The text component representing the name of the entities captured by the selector.
*/
public static TextualComponent selector(String selector){
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly
return new ArbitraryTextTypeComponent("selector", selector);
}
public void setKey(final String key)
{
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
_key = key;
}
public String getValue()
{
return _value;
}
public void setValue(final String value)
{
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
}
private String _key;
private String _value;
@Override
public TextualComponent clone() throws CloneNotSupportedException
{
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ArbitraryTextTypeComponent(getKey(), getValue());
}
@Override
public void writeJson(final JsonWriter writer) throws IOException
{
writer.name(getKey()).value(getValue());
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize()
{
return new HashMap<String, Object>()
{
{
put("key", getKey());
put("value", getValue());
}
};
}
public static ArbitraryTextTypeComponent deserialize(final Map<String, Object> map)
{
return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
}
@Override
public String getReadableString()
{
return getValue();
}
}
/**
* Internal class used to represent a text component with a nested JSON value.
* Exception validating done is on keys and values.
*/
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable
{
public ComplexTextTypeComponent(final String key, final Map<String, String> values)
{
setKey(key);
setValue(values);
}
@Override
public String getKey()
{
return _key;
}
public void setKey(final String key)
{
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
_key = key;
}
public Map<String, String> getValue()
{
return _value;
}
public void setValue(final Map<String, String> value)
{
Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value;
}
private String _key;
private Map<String, String> _value;
@Override
public TextualComponent clone() throws CloneNotSupportedException
{
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ComplexTextTypeComponent(getKey(), getValue());
}
@Override
public void writeJson(final JsonWriter writer) throws IOException
{
writer.name(getKey());
writer.beginObject();
for (final Map.Entry<String, String> jsonPair : _value.entrySet())
{
writer.name(jsonPair.getKey()).value(jsonPair.getValue());
}
writer.endObject();
}
@Override
@SuppressWarnings("serial")
public Map<String, Object> serialize()
{
return new java.util.HashMap<String, Object>()
{
{
put("key", getKey());
for (final Map.Entry<String, String> valEntry : getValue().entrySet())
{
put("value." + valEntry.getKey(), valEntry.getValue());
}
}
};
}
public static ComplexTextTypeComponent deserialize(final Map<String, Object> map)
{
String key = null;
final Map<String, String> value = new HashMap<String, String>();
for (final Map.Entry<String, Object> valEntry : map.entrySet())
{
if (valEntry.getKey().equals("key"))
{
key = (String) valEntry.getValue();
}
else if (valEntry.getKey().startsWith("value."))
{
value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
}
}
return new ComplexTextTypeComponent(key, value);
}
@Override
public String getReadableString()
{
return getKey();
}
}
/**
* Create a textual component representing a string literal.
* This is the default type of textual component when a single string literal is given to a method.
* @param textValue The text which will be represented.
* @return The text component representing the specified literal text.
*/
public static TextualComponent rawText(final String textValue)
{
return new ArbitraryTextTypeComponent("text", textValue);
}
/**
* Create a textual component representing a localized string.
* The client will see this text component as their localized version of the specified string <em>key</em>, which can be overridden by a resource pack.
* <p>
* If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to the client.
* </p>
* @param translateKey The string key which maps to localized text.
* @return The text component representing the specified localized text.
*/
public static TextualComponent localizedText(final String translateKey)
{
return new ArbitraryTextTypeComponent("translate", translateKey);
}
private static void throwUnsupportedSnapshot()
{
throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
}
/**
* Create a textual component representing a scoreboard value.
* The client will see their own score for the specified objective as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
* @param scoreboardObjective The name of the objective for which to display the score.
* @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during JSON serialization.
*/
public static TextualComponent objectiveScore(final String scoreboardObjective)
{
return objectiveScore("*", scoreboardObjective);
}
/**
* Create a textual component representing a scoreboard value.
* The client will see the score of the specified player for the specified objective as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
* @param playerName The name of the player whos score will be shown. If this string represents the single-character sequence "*", the viewing player's score will be displayed.
* Standard minecraft selectors (@a, @p, etc) are <em>not</em> supported.
* @param scoreboardObjective The name of the objective for which to display the score.
* @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during JSON serialization.
*/
public static TextualComponent objectiveScore(final String playerName, final String scoreboardObjective)
{
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly
return new ComplexTextTypeComponent("score", ImmutableMap.<String, String> builder()
.put("name", playerName)
.put("objective", scoreboardObjective)
.build());
}
/**
* Create a textual component representing a player name, retrievable by using a standard minecraft selector.
* The client will see the players or entities captured by the specified selector as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
* @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in the place of this text component.
* @return The text component representing the name of the entities captured by the selector.
*/
public static TextualComponent selector(final String selector)
{
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly
return new ArbitraryTextTypeComponent("selector", selector);
}
}

View File

@ -14,27 +14,30 @@ import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
public abstract class APlotMeConnector {
public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder);
public abstract HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException;
public abstract boolean accepts(String version);
public String getWorld(final String world) {
for (final World newworld : Bukkit.getWorlds()) {
if (newworld.getName().equalsIgnoreCase(world)) {
return newworld.getName();
}
public abstract class APlotMeConnector
{
public abstract Connection getPlotMeConnection(final String plugin, final FileConfiguration plotConfig, final String dataFolder);
public abstract HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException;
public abstract boolean accepts(final String version);
public String getWorld(final String world)
{
for (final World newworld : Bukkit.getWorlds())
{
if (newworld.getName().equalsIgnoreCase(world)) { return newworld.getName(); }
}
return world;
}
public boolean isValidConnection(Connection connection) {
public boolean isValidConnection(final Connection connection)
{
return connection != null;
}
public void copyConfig(FileConfiguration plotConfig, String world, String actualWorldName) {
public void copyConfig(final FileConfiguration plotConfig, final String world, final String actualWorldName)
{
final Integer pathwidth = plotConfig.getInt("worlds." + world + ".PathWidth"); //
PS.get().config.set("worlds." + actualWorldName + ".road.width", pathwidth);
final Integer plotsize = plotConfig.getInt("worlds." + world + ".PlotSize"); //
@ -48,70 +51,84 @@ public abstract class APlotMeConnector {
final String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId");
PS.get().config.set("worlds." + actualWorldName + ".road.block", road);
Integer height = plotConfig.getInt("worlds." + world + ".RoadHeight"); //
if (height == null) {
if (height == null)
{
height = 64;
}
PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
}
public Location getPlotTopLocAbs(int path, int plot, final PlotId plotid) {
public Location getPlotTopLocAbs(final int path, final int plot, final PlotId plotid)
{
final int px = plotid.x;
final int pz = plotid.y;
final int x = (px * (path + plot)) - ((int) Math.floor(path / 2)) - 1;
final int z = (pz * (path + plot)) - ((int) Math.floor(path / 2)) - 1;
return new Location(null, x, 256, z);
}
public Location getPlotBottomLocAbs(int path, int plot, final PlotId plotid) {
public Location getPlotBottomLocAbs(final int path, final int plot, final PlotId plotid)
{
final int px = plotid.x;
final int pz = plotid.y;
final int x = (px * (path + plot)) - plot - ((int) Math.floor(path / 2)) - 1;
final int z = (pz * (path + plot)) - plot - ((int) Math.floor(path / 2)) - 1;
return new Location(null, x, 1, z);
}
public void setMerged(HashMap<String, HashMap<PlotId, boolean[]>> merges, String world, PlotId id, int direction) {
HashMap<PlotId, boolean[]> plots = merges.get(world);
public void setMerged(final HashMap<String, HashMap<PlotId, boolean[]>> merges, final String world, final PlotId id, final int direction)
{
final HashMap<PlotId, boolean[]> plots = merges.get(world);
PlotId id2;
switch (direction) {
case 0: {
switch (direction)
{
case 0:
{
id2 = new PlotId(id.x, id.y);
break;
}
case 1: {
case 1:
{
id2 = new PlotId(id.x, id.y);
break;
}
case 2: {
case 2:
{
id2 = new PlotId(id.x, id.y);
break;
}
case 3: {
case 3:
{
id2 = new PlotId(id.x, id.y);
break;
}
default: {
default:
{
return;
}
}
boolean[] merge1;
boolean[] merge2;
if (plots.containsKey(id)) {
if (plots.containsKey(id))
{
merge1 = plots.get(id);
}
else {
merge1 = new boolean[]{false, false, false, false};
else
{
merge1 = new boolean[] { false, false, false, false };
}
if (plots.containsKey(id2)) {
if (plots.containsKey(id2))
{
merge2 = plots.get(id2);
}
else {
merge2 = new boolean[]{false, false, false, false};
else
{
merge2 = new boolean[] { false, false, false, false };
}
merge1[direction] = true;
merge2[(direction + 2) % 4] = true;
plots.put(id, merge1);
plots.put(id2, merge1);
}
}

View File

@ -1,5 +1,16 @@
package com.plotsquared.bukkit.database.plotme;
import java.io.File;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.UUID;
import com.intellectualcrafters.configuration.file.FileConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
@ -12,41 +23,38 @@ import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.UUIDHandler;
import java.io.File;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.UUID;
public class ClassicPlotMeConnector extends APlotMeConnector {
public class ClassicPlotMeConnector extends APlotMeConnector
{
private String plugin;
@Override
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
public Connection getPlotMeConnection(final String plugin, final FileConfiguration plotConfig, final String dataFolder)
{
this.plugin = plugin.toLowerCase();
try {
if (plotConfig.getBoolean("usemySQL")) {
try
{
if (plotConfig.getBoolean("usemySQL"))
{
final String user = plotConfig.getString("mySQLuname");
final String password = plotConfig.getString("mySQLpass");
final String con = plotConfig.getString("mySQLconn");
return DriverManager.getConnection(con, user, password);
// return new MySQL(plotsquared, hostname, port, database, username, password)
} else {
// return new MySQL(plotsquared, hostname, port, database, username, password)
}
else
{
return new SQLite(dataFolder + File.separator + "plots.db").openConnection();
}
}
catch (SQLException | ClassNotFoundException e) {}
catch (SQLException | ClassNotFoundException e)
{}
return null;
}
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException {
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException
{
ResultSet r;
PreparedStatement stmt;
final HashMap<String, Integer> plotWidth = new HashMap<>();
@ -56,211 +64,269 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "Plots`");
r = stmt.executeQuery();
String column = null;
boolean checkUUID = DBFunc.hasColumn(r, "ownerid");
boolean checkUUID2 = DBFunc.hasColumn(r, "ownerId");
if (checkUUID) {
final boolean checkUUID = DBFunc.hasColumn(r, "ownerid");
final boolean checkUUID2 = DBFunc.hasColumn(r, "ownerId");
if (checkUUID)
{
column = "ownerid";
}
else if (checkUUID2) {
else if (checkUUID2)
{
column = "ownerId";
}
boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (r.next()) {
final boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (r.next())
{
final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ"));
final String name = r.getString("owner");
final String world = LikePlotMeConverter.getWorld(r.getString("world"));
if (!plots.containsKey(world)) {
if (!plots.containsKey(world))
{
plots.put(world, new HashMap<PlotId, Plot>());
if (merge) {
int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
int path = PS.get().config.getInt("worlds." + world + ".road.width");
if (merge)
{
final int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
final int path = PS.get().config.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot);
roadWidth.put(world, path);
merges.put(world, new HashMap<PlotId,boolean[]>());
merges.put(world, new HashMap<PlotId, boolean[]>());
}
}
if (merge) {
int tx = r.getInt("topX");
int tz = r.getInt("topZ");
int bx = r.getInt("bottomX") - 1;
int bz = r.getInt("bottomZ") - 1;
int path = roadWidth.get(world);
int plot = plotWidth.get(world);
Location top = getPlotTopLocAbs(path, plot, id);
Location bot = getPlotBottomLocAbs(path, plot, id);
if (tx > top.getX()) {
if (merge)
{
final int tx = r.getInt("topX");
final int tz = r.getInt("topZ");
final int bx = r.getInt("bottomX") - 1;
final int bz = r.getInt("bottomZ") - 1;
final int path = roadWidth.get(world);
final int plot = plotWidth.get(world);
final Location top = getPlotTopLocAbs(path, plot, id);
final Location bot = getPlotBottomLocAbs(path, plot, id);
if (tx > top.getX())
{
setMerged(merges, world, id, 1);
}
if (tz > top.getZ()) {
if (tz > top.getZ())
{
setMerged(merges, world, id, 2);
}
if (bx < bot.getX()) {
if (bx < bot.getX())
{
setMerged(merges, world, id, 3);
}
if (bz > bot.getZ()) {
if (bz > bot.getZ())
{
setMerged(merges, world, id, 0);
}
}
UUID owner = UUIDHandler.getUUID(name, null);
if (owner == null) {
if (name.equals("*")) {
if (owner == null)
{
if (name.equals("*"))
{
owner = DBFunc.everyone;
}
else {
if (checkUUID || checkUUID2){
try {
byte[] bytes = r.getBytes(column);
if (bytes != null) {
try {
ByteBuffer bb = ByteBuffer.wrap(bytes);
long high = bb.getLong();
long low = bb.getLong();
else
{
if (checkUUID || checkUUID2)
{
try
{
final byte[] bytes = r.getBytes(column);
if (bytes != null)
{
try
{
final ByteBuffer bb = ByteBuffer.wrap(bytes);
final long high = bb.getLong();
final long low = bb.getLong();
owner = new UUID(high, low);
}
catch (Exception e) {
catch (final Exception e)
{
e.printStackTrace();
owner = UUID.nameUUIDFromBytes(bytes);
}
if (owner != null) {
if (owner != null)
{
UUIDHandler.add(new StringWrapper(name), owner);
}
}
}
catch (Exception e) {
catch (final Exception e)
{
e.printStackTrace();
}
}
if (owner == null) {
if (owner == null)
{
MainUtil.sendConsoleMessage("&cCould not identify owner for plot: " + id + " -> '" + name + "'");
continue;
}
}
}
else {
else
{
UUIDHandler.add(new StringWrapper(name), owner);
}
final Plot plot = new Plot(world, id, owner);
plots.get(world).put(id, plot);
}
for (Entry<String, HashMap<PlotId, boolean[]>> entry : merges.entrySet()) {
String world = entry.getKey();
for (Entry<PlotId, boolean[]> entry2 : entry.getValue().entrySet()) {
HashMap<PlotId, Plot> newplots = plots.get(world);
Plot plot = newplots.get(entry2.getKey());
if (plot != null) {
for (final Entry<String, HashMap<PlotId, boolean[]>> entry : merges.entrySet())
{
final String world = entry.getKey();
for (final Entry<PlotId, boolean[]> entry2 : entry.getValue().entrySet())
{
final HashMap<PlotId, Plot> newplots = plots.get(world);
final Plot plot = newplots.get(entry2.getKey());
if (plot != null)
{
plot.getSettings().setMerged(entry2.getValue());
}
}
}
r.close();
stmt.close();
try {
try
{
MainUtil.sendConsoleMessage(" - " + plugin + "Denied");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "Denied`");
r = stmt.executeQuery();
while (r.next()) {
while (r.next())
{
final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ"));
final String name = r.getString("player");
final String world = LikePlotMeConverter.getWorld(r.getString("world"));
UUID denied = UUIDHandler.getUUID(name, null);
if (denied == null) {
if (name.equals("*")) {
if (denied == null)
{
if (name.equals("*"))
{
denied = DBFunc.everyone;
} else {
if (DBFunc.hasColumn(r, "playerid")) {
try {
byte[] bytes = r.getBytes("playerid");
if (bytes != null) {
try {
ByteBuffer bb = ByteBuffer.wrap(bytes);
long high = bb.getLong();
long low = bb.getLong();
}
else
{
if (DBFunc.hasColumn(r, "playerid"))
{
try
{
final byte[] bytes = r.getBytes("playerid");
if (bytes != null)
{
try
{
final ByteBuffer bb = ByteBuffer.wrap(bytes);
final long high = bb.getLong();
final long low = bb.getLong();
denied = new UUID(high, low);
} catch (Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
denied = UUID.nameUUIDFromBytes(bytes);
}
if (denied != null) {
if (denied != null)
{
UUIDHandler.add(new StringWrapper(name), denied);
}
}
} catch (Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
}
}
}
if (denied == null){
if (denied == null)
{
MainUtil.sendConsoleMessage("&6Could not identify denied for plot: " + id);
continue;
}
}
if (plots.get(world).containsKey(id)) {
if (plots.get(world).containsKey(id))
{
plots.get(world).get(id).getDenied().add(denied);
}
}
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "Allowed`");
r = stmt.executeQuery();
while (r.next()) {
while (r.next())
{
final PlotId id = new PlotId(r.getInt("idX"), r.getInt("idZ"));
final String name = r.getString("player");
final String world = LikePlotMeConverter.getWorld(r.getString("world"));
UUID helper = UUIDHandler.getUUID(name, null);
if (helper == null) {
if (name.equals("*")) {
if (helper == null)
{
if (name.equals("*"))
{
helper = DBFunc.everyone;
} else {
if (DBFunc.hasColumn(r, "playerid")) {
try {
byte[] bytes = r.getBytes("playerid");
if (bytes != null) {
try {
ByteBuffer bb = ByteBuffer.wrap(bytes);
long high = bb.getLong();
long low = bb.getLong();
}
else
{
if (DBFunc.hasColumn(r, "playerid"))
{
try
{
final byte[] bytes = r.getBytes("playerid");
if (bytes != null)
{
try
{
final ByteBuffer bb = ByteBuffer.wrap(bytes);
final long high = bb.getLong();
final long low = bb.getLong();
helper = new UUID(high, low);
} catch (Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
helper = UUID.nameUUIDFromBytes(bytes);
}
if (helper != null) {
if (helper != null)
{
UUIDHandler.add(new StringWrapper(name), helper);
}
}
} catch (Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
}
}
}
if (helper == null){
if (helper == null)
{
MainUtil.sendConsoleMessage("&6Could not identify helper for plot: " + id);
continue;
}
}
if (plots.get(world).containsKey(id)) {
if (plots.get(world).containsKey(id))
{
plots.get(world).get(id).getTrusted().add(helper);
}
}
r.close();
stmt.close();
}
catch (Exception e) {}
catch (final Exception e)
{}
return plots;
}
@Override
public boolean accepts(String version) {
if (version == null) {
return true;
}
public boolean accepts(final String version)
{
if (version == null) { return true; }
return PS.get().canUpdate(version, "0.17.0");
}
}

View File

@ -1,349 +1,410 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.database.plotme;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import com.intellectualcrafters.configuration.file.FileConfiguration;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.generator.HybridGen;
/**
* Created 2014-08-17 for PlotSquared
*
* @author Citymonstret
* @author Empire92
*/
public class LikePlotMeConverter {
private String plugin;
/**
* Constructor
*
* @param plugin Plugin Used to run the converter
*/
public LikePlotMeConverter(String plugin) {
this.plugin = plugin;
}
public static String getWorld(final String world) {
for (final World newworld : Bukkit.getWorlds()) {
if (newworld.getName().equalsIgnoreCase(world)) {
return newworld.getName();
}
}
return world;
}
private void sendMessage(final String message) {
PS.debug("&3PlotMe&8->&3PlotSquared&8: &7" + message);
}
public String getPlotMePath() {
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator;
}
public String getAthionPlotsPath() {
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator;
}
public FileConfiguration getPlotMeConfig(String dataFolder) {
final File plotMeFile = new File(dataFolder + "config.yml");
if (!plotMeFile.exists()) {
return null;
}
return YamlConfiguration.loadConfiguration(plotMeFile);
}
public Set<String> getPlotMeWorlds(FileConfiguration plotConfig) {
return plotConfig.getConfigurationSection("worlds").getKeys(false);
}
public void updateWorldYml(String plugin, String location) {
try {
Path path = Paths.get(location);
File file = new File(location);
if (!file.exists()) {
return;
}
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("PlotMe-DefaultGenerator", "PlotSquared");
content = content.replaceAll(plugin, "PlotSquared");
Files.write(path, content.getBytes(charset));
} catch (Exception e) {
}
}
public boolean run(final APlotMeConnector connector) {
try {
String dataFolder = getPlotMePath();
FileConfiguration plotConfig = getPlotMeConfig(dataFolder);
if (plotConfig == null) {
return false;
}
String version = plotConfig.getString("Version");
if (version == null) version = plotConfig.getString("version");
if (!connector.accepts(version)) {
return false;
}
PS.debug("&3Using connector: " + connector.getClass().getCanonicalName());
Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder);
if (!connector.isValidConnection(connection)) {
sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue");
return false;
}
sendMessage(plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' in the 'settings.yml'");
sendMessage("Connecting to " + plugin + " DB");
int plotCount = 0;
final ArrayList<Plot> createdPlots = new ArrayList<>();
sendMessage("Collecting plot data");
String dbPrefix = plugin.toLowerCase();
sendMessage(" - " + dbPrefix + "Plots");
final Set<String> worlds = getPlotMeWorlds(plotConfig);
if (Settings.CONVERT_PLOTME) {
sendMessage("Updating bukkit.yml");
updateWorldYml(plugin, "bukkit.yml");
updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml");
for (final String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) {
sendMessage("Copying config for: " + world);
try {
String actualWorldName = getWorld(world);
connector.copyConfig(plotConfig, world, actualWorldName);
PS.get().config.save(PS.get().configFile);
} catch (final Exception e) {
e.printStackTrace();
sendMessage("&c-- &lFailed to save configuration for world '" + world + "'\nThis will need to be done using the setup command, or manually");
}
}
}
HashMap<String, HashMap<PlotId, Plot>> plots = connector.getPlotMePlots(connection);
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
plotCount += entry.getValue().size();
}
if (!Settings.CONVERT_PLOTME) {
return false;
}
sendMessage(" - " + dbPrefix + "Allowed");
sendMessage("Collected " + plotCount + " plots from PlotMe");
final File PLOTME_DG_FILE = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
if (PLOTME_DG_FILE.exists()) {
final YamlConfiguration PLOTME_DG_YML = YamlConfiguration.loadConfiguration(PLOTME_DG_FILE);
try {
for (final String world : plots.keySet()) {
String actualWorldName = getWorld(world);
final String plotMeWorldName = world.toLowerCase();
Integer pathwidth = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PathWidth"); //
if (pathwidth == null) {
pathwidth = 7;
}
PS.get().config.set("worlds." + world + ".road.width", pathwidth);
Integer pathheight = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if (pathheight == null || pathheight == 0) {
pathheight = 64;
}
PS.get().config.set("worlds." + world + ".road.height", pathheight);
PS.get().config.set("worlds." + world + ".wall.height", pathheight);
PS.get().config.set("worlds." + world + ".plot.height", pathheight);
Integer plotsize = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PlotSize"); //
if (plotsize == null || plotsize == 0) {
plotsize = 32;
}
PS.get().config.set("worlds." + world + ".plot.size", plotsize);
String wallblock = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".WallBlock"); //
if (wallblock == null) {
wallblock = "44";
}
PS.get().config.set("worlds." + world + ".wall.block", wallblock);
String floor = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".PlotFloorBlock"); //
if (floor == null) {
floor = "2";
}
PS.get().config.set("worlds." + world + ".plot.floor", Arrays.asList(floor));
String filling = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".FillBlock"); //
if (filling == null) {
filling = "3";
}
PS.get().config.set("worlds." + world + ".plot.filling", Arrays.asList(filling));
String road = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".RoadMainBlock");
if (road == null) {
road = "5";
}
PS.get().config.set("worlds." + world + ".road.block", road);
Integer height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if ((height == null) || (height == 0)) {
height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".GroundHeight"); //
if ((height == null) || (height == 0)) {
height = 64;
}
}
PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
PS.get().config.set("worlds." + actualWorldName + ".plot.height", height);
PS.get().config.set("worlds." + actualWorldName + ".wall.height", height);
PS.get().config.save(PS.get().configFile);
}
} catch (final Exception e) {
}
}
for (final String world : plots.keySet()) {
int duplicate = 0;
for (final Plot plot : plots.get(world).values()) {
if (PS.get().getPlot(world, plot.id) == null) {
createdPlots.add(plot);
} else {
duplicate++;
}
}
if (duplicate > 0) {
PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?");
}
}
sendMessage("Creating plot DB");
Thread.sleep(1000);
final AtomicBoolean done = new AtomicBoolean(false);
DBFunc.createPlotsAndData(createdPlots, new Runnable() {
@Override
public void run() {
if (done.get()) {
sendMessage("&aDatabase conversion is now complete!");
PS.debug("&c - Stop the server");
PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PS.debug("&c - Start the server");
PS.get().setAllPlotsRaw(DBFunc.getPlots());
}
else {
sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
}
});
sendMessage("Saving configuration...");
try {
PS.get().config.save(PS.get().configFile);
} catch (final IOException e) {
sendMessage(" - &cFailed to save configuration.");
}
TaskManager.runTask(new Runnable() {
@Override
public void run() {
try {
boolean MV = false;
boolean MW = false;
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
MV = true;
} else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
MW = true;
}
for (final String worldname : worlds) {
final World world = Bukkit.getWorld(getWorld(worldname));
if (world == null) {
sendMessage("&cInvalid world in PlotMe configuration: " + worldname);
}
final String actualWorldName = world.getName();
sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
PS.get().removePlotWorld(actualWorldName);
if (MV) {
// unload world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
}
// load world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv import " + actualWorldName + " normal -g PlotSquared");
} else if (MW) {
// unload world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
}
// load world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + actualWorldName + " plugin:PlotSquared");
} else {
// Load using Bukkit API
// - User must set generator manually
Bukkit.getServer().unloadWorld(world, true);
final World myworld = WorldCreator.name(actualWorldName).generator(new HybridGen(actualWorldName)).createWorld();
myworld.save();
}
}
} catch (final Exception e) {
e.printStackTrace();
}
if (done.get()) {
sendMessage("&aDatabase conversion is now complete!");
PS.debug("&c - Stop the server");
PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PS.debug("&c - Start the server");
}
else {
sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
}
});
} catch (final Exception e) {
e.printStackTrace();
PS.debug("&/end/");
}
return true;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.database.plotme;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import com.intellectualcrafters.configuration.file.FileConfiguration;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.generator.HybridGen;
/**
* Created 2014-08-17 for PlotSquared
*
*/
public class LikePlotMeConverter
{
private final String plugin;
/**
* Constructor
*
* @param plugin Plugin Used to run the converter
*/
public LikePlotMeConverter(final String plugin)
{
this.plugin = plugin;
}
public static String getWorld(final String world)
{
for (final World newworld : Bukkit.getWorlds())
{
if (newworld.getName().equalsIgnoreCase(world)) { return newworld.getName(); }
}
return world;
}
private void sendMessage(final String message)
{
PS.debug("&3PlotMe&8->&3PlotSquared&8: &7" + message);
}
public String getPlotMePath()
{
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator;
}
public String getAthionPlotsPath()
{
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator;
}
public FileConfiguration getPlotMeConfig(final String dataFolder)
{
final File plotMeFile = new File(dataFolder + "config.yml");
if (!plotMeFile.exists()) { return null; }
return YamlConfiguration.loadConfiguration(plotMeFile);
}
public Set<String> getPlotMeWorlds(final FileConfiguration plotConfig)
{
return plotConfig.getConfigurationSection("worlds").getKeys(false);
}
public void updateWorldYml(final String plugin, final String location)
{
try
{
final Path path = Paths.get(location);
final File file = new File(location);
if (!file.exists()) { return; }
final Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("PlotMe-DefaultGenerator", "PlotSquared");
content = content.replaceAll(plugin, "PlotSquared");
Files.write(path, content.getBytes(charset));
}
catch (final Exception e)
{}
}
public boolean run(final APlotMeConnector connector)
{
try
{
final String dataFolder = getPlotMePath();
final FileConfiguration plotConfig = getPlotMeConfig(dataFolder);
if (plotConfig == null) { return false; }
String version = plotConfig.getString("Version");
if (version == null)
{
version = plotConfig.getString("version");
}
if (!connector.accepts(version)) { return false; }
PS.debug("&3Using connector: " + connector.getClass().getCanonicalName());
final Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder);
if (!connector.isValidConnection(connection))
{
sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue");
return false;
}
sendMessage(plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' in the 'settings.yml'");
sendMessage("Connecting to " + plugin + " DB");
int plotCount = 0;
final ArrayList<Plot> createdPlots = new ArrayList<>();
sendMessage("Collecting plot data");
final String dbPrefix = plugin.toLowerCase();
sendMessage(" - " + dbPrefix + "Plots");
final Set<String> worlds = getPlotMeWorlds(plotConfig);
if (Settings.CONVERT_PLOTME)
{
sendMessage("Updating bukkit.yml");
updateWorldYml(plugin, "bukkit.yml");
updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml");
for (final String world : plotConfig.getConfigurationSection("worlds").getKeys(false))
{
sendMessage("Copying config for: " + world);
try
{
final String actualWorldName = getWorld(world);
connector.copyConfig(plotConfig, world, actualWorldName);
PS.get().config.save(PS.get().configFile);
}
catch (final Exception e)
{
e.printStackTrace();
sendMessage("&c-- &lFailed to save configuration for world '" + world + "'\nThis will need to be done using the setup command, or manually");
}
}
}
final HashMap<String, HashMap<PlotId, Plot>> plots = connector.getPlotMePlots(connection);
for (final Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet())
{
plotCount += entry.getValue().size();
}
if (!Settings.CONVERT_PLOTME) { return false; }
sendMessage(" - " + dbPrefix + "Allowed");
sendMessage("Collected " + plotCount + " plots from PlotMe");
final File PLOTME_DG_FILE = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
if (PLOTME_DG_FILE.exists())
{
final YamlConfiguration PLOTME_DG_YML = YamlConfiguration.loadConfiguration(PLOTME_DG_FILE);
try
{
for (final String world : plots.keySet())
{
final String actualWorldName = getWorld(world);
final String plotMeWorldName = world.toLowerCase();
Integer pathwidth = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PathWidth"); //
if (pathwidth == null)
{
pathwidth = 7;
}
PS.get().config.set("worlds." + world + ".road.width", pathwidth);
Integer pathheight = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if ((pathheight == null) || (pathheight == 0))
{
pathheight = 64;
}
PS.get().config.set("worlds." + world + ".road.height", pathheight);
PS.get().config.set("worlds." + world + ".wall.height", pathheight);
PS.get().config.set("worlds." + world + ".plot.height", pathheight);
Integer plotsize = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PlotSize"); //
if ((plotsize == null) || (plotsize == 0))
{
plotsize = 32;
}
PS.get().config.set("worlds." + world + ".plot.size", plotsize);
String wallblock = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".WallBlock"); //
if (wallblock == null)
{
wallblock = "44";
}
PS.get().config.set("worlds." + world + ".wall.block", wallblock);
String floor = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".PlotFloorBlock"); //
if (floor == null)
{
floor = "2";
}
PS.get().config.set("worlds." + world + ".plot.floor", Arrays.asList(floor));
String filling = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".FillBlock"); //
if (filling == null)
{
filling = "3";
}
PS.get().config.set("worlds." + world + ".plot.filling", Arrays.asList(filling));
String road = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".RoadMainBlock");
if (road == null)
{
road = "5";
}
PS.get().config.set("worlds." + world + ".road.block", road);
Integer height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if ((height == null) || (height == 0))
{
height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".GroundHeight"); //
if ((height == null) || (height == 0))
{
height = 64;
}
}
PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
PS.get().config.set("worlds." + actualWorldName + ".plot.height", height);
PS.get().config.set("worlds." + actualWorldName + ".wall.height", height);
PS.get().config.save(PS.get().configFile);
}
}
catch (final Exception e)
{}
}
for (final String world : plots.keySet())
{
int duplicate = 0;
for (final Plot plot : plots.get(world).values())
{
if (PS.get().getPlot(world, plot.id) == null)
{
createdPlots.add(plot);
}
else
{
duplicate++;
}
}
if (duplicate > 0)
{
PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?");
}
}
sendMessage("Creating plot DB");
Thread.sleep(1000);
final AtomicBoolean done = new AtomicBoolean(false);
DBFunc.createPlotsAndData(createdPlots, new Runnable()
{
@Override
public void run()
{
if (done.get())
{
sendMessage("&aDatabase conversion is now complete!");
PS.debug("&c - Stop the server");
PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PS.debug("&c - Start the server");
PS.get().setAllPlotsRaw(DBFunc.getPlots());
}
else
{
sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
}
});
sendMessage("Saving configuration...");
try
{
PS.get().config.save(PS.get().configFile);
}
catch (final IOException e)
{
sendMessage(" - &cFailed to save configuration.");
}
TaskManager.runTask(new Runnable()
{
@Override
public void run()
{
try
{
boolean MV = false;
boolean MW = false;
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled())
{
MV = true;
}
else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled())
{
MW = true;
}
for (final String worldname : worlds)
{
final World world = Bukkit.getWorld(getWorld(worldname));
if (world == null)
{
sendMessage("&cInvalid world in PlotMe configuration: " + worldname);
}
final String actualWorldName = world.getName();
sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
PS.get().removePlotWorld(actualWorldName);
if (MV)
{
// unload world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
try
{
Thread.sleep(1000);
}
catch (final InterruptedException ex)
{
Thread.currentThread().interrupt();
}
// load world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv import " + actualWorldName + " normal -g PlotSquared");
}
else if (MW)
{
// unload world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName);
try
{
Thread.sleep(1000);
}
catch (final InterruptedException ex)
{
Thread.currentThread().interrupt();
}
// load world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + actualWorldName + " plugin:PlotSquared");
}
else
{
// Load using Bukkit API
// - User must set generator manually
Bukkit.getServer().unloadWorld(world, true);
final World myworld = WorldCreator.name(actualWorldName).generator(new HybridGen(actualWorldName)).createWorld();
myworld.save();
}
}
}
catch (final Exception e)
{
e.printStackTrace();
}
if (done.get())
{
sendMessage("&aDatabase conversion is now complete!");
PS.debug("&c - Stop the server");
PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PS.debug("&c - Start the server");
}
else
{
sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
}
});
}
catch (final Exception e)
{
e.printStackTrace();
PS.debug("&/end/");
}
return true;

View File

@ -22,177 +22,211 @@ import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.UUIDHandler;
public class PlotMeConnector_017 extends APlotMeConnector {
public class PlotMeConnector_017 extends APlotMeConnector
{
private String plugin;
@Override
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
public Connection getPlotMeConnection(final String plugin, final FileConfiguration plotConfig, final String dataFolder)
{
this.plugin = plugin.toLowerCase();
try {
if (plotConfig.getBoolean("usemySQL")) {
String user = plotConfig.getString("mySQLuname");
String password = plotConfig.getString("mySQLpass");
String con = plotConfig.getString("mySQLconn");
try
{
if (plotConfig.getBoolean("usemySQL"))
{
final String user = plotConfig.getString("mySQLuname");
final String password = plotConfig.getString("mySQLpass");
final String con = plotConfig.getString("mySQLconn");
return DriverManager.getConnection(con, user, password);
} else {
File file = new File(dataFolder + File.separator + "plotmecore.db");
if (file.exists()) {
return new SQLite(dataFolder + File.separator + "plotmecore.db").openConnection();
}
}
else
{
final File file = new File(dataFolder + File.separator + "plotmecore.db");
if (file.exists()) { return new SQLite(dataFolder + File.separator + "plotmecore.db").openConnection(); }
return new SQLite(dataFolder + File.separator + "plots.db").openConnection();
}
}
catch (SQLException | ClassNotFoundException e) {}
catch (SQLException | ClassNotFoundException e)
{}
return null;
}
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException {
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException
{
ResultSet r;
PreparedStatement stmt;
HashMap<String, Integer> plotWidth = new HashMap<>();
HashMap<String, Integer> roadWidth = new HashMap<>();
final HashMap<String, Integer> plotWidth = new HashMap<>();
final HashMap<String, Integer> roadWidth = new HashMap<>();
final HashMap<Integer, Plot> plots = new HashMap<>();
HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>();
final HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>();
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_plots`");
r = stmt.executeQuery();
boolean checkUUID = DBFunc.hasColumn(r, "ownerID");
boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (r.next()) {
int key = r.getInt("plot_id");
PlotId id = new PlotId(r.getInt("plotX"), r.getInt("plotZ"));
String name = r.getString("owner");
String world = LikePlotMeConverter.getWorld(r.getString("world"));
if (!plots.containsKey(world)) {
if (merge) {
int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
int path = PS.get().config.getInt("worlds." + world + ".road.width");
final boolean checkUUID = DBFunc.hasColumn(r, "ownerID");
final boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (r.next())
{
final int key = r.getInt("plot_id");
final PlotId id = new PlotId(r.getInt("plotX"), r.getInt("plotZ"));
final String name = r.getString("owner");
final String world = LikePlotMeConverter.getWorld(r.getString("world"));
if (!plots.containsKey(world))
{
if (merge)
{
final int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
final int path = PS.get().config.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot);
roadWidth.put(world, path);
merges.put(world, new HashMap<PlotId,boolean[]>());
merges.put(world, new HashMap<PlotId, boolean[]>());
}
}
if (merge) {
int tx = r.getInt("topX");
int tz = r.getInt("topZ");
int bx = r.getInt("bottomX") - 1;
int bz = r.getInt("bottomZ") - 1;
int path = roadWidth.get(world);
int plot = plotWidth.get(world);
Location top = getPlotTopLocAbs(path, plot, id);
Location bot = getPlotBottomLocAbs(path, plot, id);
if (tx > top.getX()) {
if (merge)
{
final int tx = r.getInt("topX");
final int tz = r.getInt("topZ");
final int bx = r.getInt("bottomX") - 1;
final int bz = r.getInt("bottomZ") - 1;
final int path = roadWidth.get(world);
final int plot = plotWidth.get(world);
final Location top = getPlotTopLocAbs(path, plot, id);
final Location bot = getPlotBottomLocAbs(path, plot, id);
if (tx > top.getX())
{
setMerged(merges, world, id, 1);
}
if (tz > top.getZ()) {
if (tz > top.getZ())
{
setMerged(merges, world, id, 2);
}
if (bx < bot.getX()) {
if (bx < bot.getX())
{
setMerged(merges, world, id, 3);
}
if (bz > bot.getZ()) {
if (bz > bot.getZ())
{
setMerged(merges, world, id, 0);
}
}
UUID owner = UUIDHandler.getUUID(name, null);
if (owner == null) {
if (name.equals("*")) {
if (owner == null)
{
if (name.equals("*"))
{
owner = DBFunc.everyone;
}
else {
if (checkUUID){
try {
byte[] bytes = r.getBytes("ownerid");
if (bytes != null) {
else
{
if (checkUUID)
{
try
{
final byte[] bytes = r.getBytes("ownerid");
if (bytes != null)
{
owner = UUID.nameUUIDFromBytes(bytes);
if (owner != null) {
if (owner != null)
{
UUIDHandler.add(new StringWrapper(name), owner);
}
}
}
catch (Exception e) {
catch (final Exception e)
{
e.printStackTrace();
}
}
if (owner == null) {
if (owner == null)
{
MainUtil.sendConsoleMessage("&cCould not identify owner for plot: " + id + " -> '" + name + "'");
continue;
}
}
}
else {
else
{
UUIDHandler.add(new StringWrapper(name), owner);
}
Plot plot = new Plot(world, id, owner);
final Plot plot = new Plot(world, id, owner);
plots.put(key, plot);
}
for (Entry<Integer, Plot> entry : plots.entrySet()) {
Plot plot = entry.getValue();
HashMap<PlotId, boolean[]> mergeMap = merges.get(plot.world);
if (mergeMap != null) {
if (mergeMap.containsKey(plot.id)) {
for (final Entry<Integer, Plot> entry : plots.entrySet())
{
final Plot plot = entry.getValue();
final HashMap<PlotId, boolean[]> mergeMap = merges.get(plot.world);
if (mergeMap != null)
{
if (mergeMap.containsKey(plot.id))
{
plot.getSettings().setMerged(mergeMap.get(plot.id));
}
}
}
r.close();
stmt.close();
try {
try
{
MainUtil.sendConsoleMessage(" - " + plugin + "core_denied");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_denied`");
r = stmt.executeQuery();
while (r.next()) {
int key = r.getInt("plot_id");
Plot plot = plots.get(key);
if (plot == null) {
while (r.next())
{
final int key = r.getInt("plot_id");
final Plot plot = plots.get(key);
if (plot == null)
{
MainUtil.sendConsoleMessage("&6Denied (" + key + ") references deleted plot; ignoring entry.");
continue;
}
UUID denied = UUID.fromString(r.getString("player"));
final UUID denied = UUID.fromString(r.getString("player"));
plot.getDenied().add(denied);
}
MainUtil.sendConsoleMessage(" - " + plugin + "core_allowed");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_allowed`");
r = stmt.executeQuery();
while (r.next()) {
int key = r.getInt("plot_id");
Plot plot = plots.get(key);
if (plot == null) {
while (r.next())
{
final int key = r.getInt("plot_id");
final Plot plot = plots.get(key);
if (plot == null)
{
MainUtil.sendConsoleMessage("&6Allowed (" + key + ") references deleted plot; ignoring entry.");
continue;
}
UUID allowed = UUID.fromString(r.getString("player"));
final UUID allowed = UUID.fromString(r.getString("player"));
plot.getTrusted().add(allowed);
}
r.close();
stmt.close();
}
catch (Exception e) {
catch (final Exception e)
{
e.printStackTrace();
}
HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>();
for (Entry<Integer, Plot> entry : plots.entrySet()) {
Plot plot = entry.getValue();
final HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>();
for (final Entry<Integer, Plot> entry : plots.entrySet())
{
final Plot plot = entry.getValue();
HashMap<PlotId, Plot> map = processed.get(plot.world);
if (map == null) {
if (map == null)
{
map = new HashMap<>();
processed.put(plot.world, map);
}
map.put(plot.id, plot);
}
return processed ;
return processed;
}
@Override
public boolean accepts(String version) {
if (version == null) {
return false;
}
public boolean accepts(final String version)
{
if (version == null) { return false; }
return !PS.get().canUpdate(version, "0.17");
}
}

View File

@ -1,89 +1,95 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.PlotCluster;
/**
* Called when a flag is removed from a plot
*
* @author Citymonstret
* @author Empire92
*/
public class ClusterFlagRemoveEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final PlotCluster cluster;
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot
*
* @param flag Flag that was removed
* @param plot Plot from which the flag was removed
*/
public ClusterFlagRemoveEvent(final Flag flag, final PlotCluster cluster) {
this.cluster = cluster;
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the cluster involved
*
* @return PlotCluster
*/
public PlotCluster getCluster() {
return this.cluster;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(final boolean b) {
this.cancelled = b;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.PlotCluster;
/**
* Called when a flag is removed from a plot
*
*/
public class ClusterFlagRemoveEvent extends Event implements Cancellable
{
private static HandlerList handlers = new HandlerList();
private final PlotCluster cluster;
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot
*
* @param flag Flag that was removed
* @param plot Plot from which the flag was removed
*/
public ClusterFlagRemoveEvent(final Flag flag, final PlotCluster cluster)
{
this.cluster = cluster;
this.flag = flag;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* Get the cluster involved
*
* @return PlotCluster
*/
public PlotCluster getCluster()
{
return cluster;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag()
{
return flag;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}
@Override
public boolean isCancelled()
{
return cancelled;
}
@Override
public void setCancelled(final boolean b)
{
cancelled = b;

View File

@ -1,86 +1,92 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.object.Plot;
/**
* @author Citymonstret
* @author Empire92
*/
public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final Plot plot;
private final boolean auto;
private boolean cancelled;
/**
* PlayerClaimPlotEvent: Called when a plot is claimed
*
* @param player Player that claimed the plot
* @param plot Plot that was claimed
*/
public PlayerClaimPlotEvent(final Player player, final Plot plot, final boolean auto) {
super(player);
this.plot = plot;
this.auto = auto;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
/**
* @return true if it was an automated claim, else false
*/
public boolean wasAuto() {
return this.auto;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(final boolean b) {
this.cancelled = b;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.object.Plot;
/**
*/
public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable
{
private static HandlerList handlers = new HandlerList();
private final Plot plot;
private final boolean auto;
private boolean cancelled;
/**
* PlayerClaimPlotEvent: Called when a plot is claimed
*
* @param player Player that claimed the plot
* @param plot Plot that was claimed
*/
public PlayerClaimPlotEvent(final Player player, final Plot plot, final boolean auto)
{
super(player);
this.plot = plot;
this.auto = auto;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot()
{
return plot;
}
/**
* @return true if it was an automated claim, else false
*/
public boolean wasAuto()
{
return auto;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}
@Override
public boolean isCancelled()
{
return cancelled;
}
@Override
public void setCancelled(final boolean b)
{
cancelled = b;

View File

@ -1,65 +1,68 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.object.Plot;
/**
* @author Citymonstret
* @author Empire92
*/
public class PlayerEnterPlotEvent extends PlayerEvent {
private static HandlerList handlers = new HandlerList();
private final Plot plot;
/**
* PlayerEnterPlotEvent: Called when a player leaves a plot
*
* @param player Player that entered the plot
* @param plot Plot that was entered
*/
public PlayerEnterPlotEvent(final Player player, final Plot plot) {
super(player);
this.plot = plot;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.object.Plot;
/**
*/
public class PlayerEnterPlotEvent extends PlayerEvent
{
private static HandlerList handlers = new HandlerList();
private final Plot plot;
/**
* PlayerEnterPlotEvent: Called when a player leaves a plot
*
* @param player Player that entered the plot
* @param plot Plot that was entered
*/
public PlayerEnterPlotEvent(final Player player, final Plot plot)
{
super(player);
this.plot = plot;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot()
{
return plot;
}
@Override
public HandlerList getHandlers()
{
return handlers;

View File

@ -1,66 +1,69 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.object.Plot;
/**
* @author Citymonstret
* @author Empire92
*/
public class PlayerLeavePlotEvent extends PlayerEvent {
private static HandlerList handlers = new HandlerList();
private final Plot plot;
/**
* PlayerLeavePlotEvent: Called when a player leaves a plot
*
* @param player Player that left the plot
* @param plot Plot that was left
*/
public PlayerLeavePlotEvent(final Player player, final Plot plot) {
super(player);
this.plot = plot;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.object.Plot;
/**
*/
public class PlayerLeavePlotEvent extends PlayerEvent
{
private static HandlerList handlers = new HandlerList();
private final Plot plot;
/**
* PlayerLeavePlotEvent: Called when a player leaves a plot
*
* @param player Player that left the plot
* @param plot Plot that was left
*/
public PlayerLeavePlotEvent(final Player player, final Plot plot)
{
super(player);
this.plot = plot;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot()
{
return plot;
}
@Override
public HandlerList getHandlers()
{
return handlers;

View File

@ -1,91 +1,96 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.Plot;
/**
* @author Citymonstret
* @author Empire92
*/
public class PlayerPlotDeniedEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a plot
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was denied/un-denied
* @param added true of add to deny list, false if removed
*/
public PlayerPlotDeniedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* If a user was added
*
* @return boolean
*/
public boolean wasAdded() {
return this.added;
}
/**
* The player added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return this.player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return this.initiator;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.Plot;
/**
*/
public class PlayerPlotDeniedEvent extends PlotEvent
{
private static HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a plot
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was denied/un-denied
* @param added true of add to deny list, false if removed
*/
public PlayerPlotDeniedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added)
{
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* If a user was added
*
* @return boolean
*/
public boolean wasAdded()
{
return added;
}
/**
* The player added/removed
*
* @return UUID
*/
public UUID getPlayer()
{
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator()
{
return initiator;
}
@Override
public HandlerList getHandlers()
{
return handlers;

View File

@ -1,91 +1,96 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.Plot;
/**
* @author Empire92
* @author Citymonstret
*/
public class PlayerPlotHelperEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotHelperEvent: Called when a plot helper is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the helper list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotHelperEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* If a player was added
*
* @return boolean
*/
public boolean wasAdded() {
return this.added;
}
/**
* The UUID added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return this.player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return this.initiator;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.Plot;
/**
*/
public class PlayerPlotHelperEvent extends PlotEvent
{
private static HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotHelperEvent: Called when a plot helper is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the helper list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotHelperEvent(final Player initiator, final Plot plot, final UUID player, final boolean added)
{
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* If a player was added
*
* @return boolean
*/
public boolean wasAdded()
{
return added;
}
/**
* The UUID added/removed
*
* @return UUID
*/
public UUID getPlayer()
{
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator()
{
return initiator;
}
@Override
public HandlerList getHandlers()
{
return handlers;

View File

@ -1,91 +1,96 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.Plot;
/**
* @author Citymonstret
* @author Empire92
*/
public class PlayerPlotTrustedEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the trusted list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotTrustedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* If a player was added
*
* @return boolean
*/
public boolean wasAdded() {
return this.added;
}
/**
* The UUID added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return this.player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return this.initiator;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.Plot;
/**
*/
public class PlayerPlotTrustedEvent extends PlotEvent
{
private static HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the trusted list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotTrustedEvent(final Player initiator, final Plot plot, final UUID player, final boolean added)
{
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* If a player was added
*
* @return boolean
*/
public boolean wasAdded()
{
return added;
}
/**
* The UUID added/removed
*
* @return UUID
*/
public UUID getPlayer()
{
return player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator()
{
return initiator;
}
@Override
public HandlerList getHandlers()
{
return handlers;

View File

@ -1,92 +1,98 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
/**
* Called when a player teleports to a plot
*
* @author Citymonstret
* @author Empire92
*/
public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Location from;
private final Plot plot;
private boolean cancelled;
/**
* PlayerTeleportToPlotEvent: Called when a player teleports to a plot
*
* @param player That was teleported
* @param from Start location
* @param plot Plot to which the player was teleported
*/
public PlayerTeleportToPlotEvent(final Player player, final Location from, final Plot plot) {
super(player);
this.from = from;
this.plot = plot;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
/**
* Get the from location
*
* @return Location
*/
public Location getFrom() {
return this.from;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(final boolean cancelled) {
this.cancelled = cancelled;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
/**
* Called when a player teleports to a plot
*
*/
public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable
{
private static final HandlerList handlers = new HandlerList();
private final Location from;
private final Plot plot;
private boolean cancelled;
/**
* PlayerTeleportToPlotEvent: Called when a player teleports to a plot
*
* @param player That was teleported
* @param from Start location
* @param plot Plot to which the player was teleported
*/
public PlayerTeleportToPlotEvent(final Player player, final Location from, final Plot plot)
{
super(player);
this.from = from;
this.plot = plot;
}
public static HandlerList getHandlerList()
{
return handlers;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}
/**
* Get the from location
*
* @return Location
*/
public Location getFrom()
{
return from;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot()
{
return plot;
}
@Override
public boolean isCancelled()
{
return cancelled;
}
@Override
public void setCancelled(final boolean cancelled)
{
this.cancelled = cancelled;

View File

@ -1,88 +1,94 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.PlotId;
/**
* Called when a plot is cleared
*
* @author Citymonstret
* @author Empire92
*/
public class PlotClearEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final PlotId id;
private final String world;
private boolean cancelled;
/**
* PlotClearEvent: Called when a plot is cleared
*
* @param world The world in which the plot was cleared
* @param id The plot that was cleared
*/
public PlotClearEvent(final String world, final PlotId id) {
this.id = id;
this.world = world;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the PlotId
*
* @return PlotId
*/
public PlotId getPlotId() {
return this.id;
}
/**
* Get the world name
*
* @return String
*/
public String getWorld() {
return this.world;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(final boolean b) {
this.cancelled = b;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.PlotId;
/**
* Called when a plot is cleared
*
*/
public class PlotClearEvent extends Event implements Cancellable
{
private static HandlerList handlers = new HandlerList();
private final PlotId id;
private final String world;
private boolean cancelled;
/**
* PlotClearEvent: Called when a plot is cleared
*
* @param world The world in which the plot was cleared
* @param id The plot that was cleared
*/
public PlotClearEvent(final String world, final PlotId id)
{
this.id = id;
this.world = world;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* Get the PlotId
*
* @return PlotId
*/
public PlotId getPlotId()
{
return id;
}
/**
* Get the world name
*
* @return String
*/
public String getWorld()
{
return world;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}
@Override
public boolean isCancelled()
{
return cancelled;
}
@Override
public void setCancelled(final boolean b)
{
cancelled = b;

View File

@ -1,76 +1,80 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.PlotId;
/**
* Called when a plot is deleted
*
* @author Citymonstret
* @author Empire92
*/
public class PlotDeleteEvent extends Event {
private static HandlerList handlers = new HandlerList();
private final PlotId id;
private final String world;
/**
* PlotDeleteEvent: Called when a plot is deleted
*
* @param world The world in which the plot was deleted
* @param id The ID of the plot that was deleted
*/
public PlotDeleteEvent(final String world, final PlotId id) {
this.id = id;
this.world = world;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the PlotId
*
* @return PlotId
*/
public PlotId getPlotId() {
return this.id;
}
/**
* Get the world name
*
* @return String
*/
public String getWorld() {
return this.world;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.PlotId;
/**
* Called when a plot is deleted
*
*/
public class PlotDeleteEvent extends Event
{
private static HandlerList handlers = new HandlerList();
private final PlotId id;
private final String world;
/**
* PlotDeleteEvent: Called when a plot is deleted
*
* @param world The world in which the plot was deleted
* @param id The ID of the plot that was deleted
*/
public PlotDeleteEvent(final String world, final PlotId id)
{
this.id = id;
this.world = world;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* Get the PlotId
*
* @return PlotId
*/
public PlotId getPlotId()
{
return id;
}
/**
* Get the world name
*
* @return String
*/
public String getWorld()
{
return world;
}
@Override
public HandlerList getHandlers()
{
return handlers;

View File

@ -4,16 +4,19 @@ import org.bukkit.event.Event;
import com.intellectualcrafters.plot.object.Plot;
public abstract class PlotEvent extends Event {
public abstract class PlotEvent extends Event
{
private final Plot plot;
public PlotEvent(final Plot plot) {
public PlotEvent(final Plot plot)
{
this.plot = plot;
}
public final Plot getPlot() {
return this.plot;
public final Plot getPlot()
{
return plot;
}
}

View File

@ -1,79 +1,84 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Plot;
/**
* Called when a Flag is added to a plot
*
* @author Citymonstret
* @author Empire92
*/
public class PlotFlagAddEvent extends PlotEvent implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagAddEvent: Called when a Flag is added to a plot
*
* @param flag Flag that was added
* @param plot Plot to which the flag was added
*/
public PlotFlagAddEvent(final Flag flag, final Plot plot) {
super(plot);
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public final boolean isCancelled() {
return this.cancelled;
}
@Override
public final void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Plot;
/**
* Called when a Flag is added to a plot
*
*/
public class PlotFlagAddEvent extends PlotEvent implements Cancellable
{
private static HandlerList handlers = new HandlerList();
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagAddEvent: Called when a Flag is added to a plot
*
* @param flag Flag that was added
* @param plot Plot to which the flag was added
*/
public PlotFlagAddEvent(final Flag flag, final Plot plot)
{
super(plot);
this.flag = flag;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag()
{
return flag;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}
@Override
public final boolean isCancelled()
{
return cancelled;
}
@Override
public final void setCancelled(final boolean cancelled)
{
this.cancelled = cancelled;

View File

@ -1,80 +1,84 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Plot;
/**
* Called when a flag is removed from a plot
*
* @author Citymonstret
* @author Empire92
*/
public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot
*
* @param flag Flag that was removed
* @param plot Plot from which the flag was removed
*/
public PlotFlagRemoveEvent(final Flag flag, final Plot plot) {
super(plot);
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public final boolean isCancelled() {
return this.cancelled;
}
@Override
public final void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Plot;
/**
* Called when a flag is removed from a plot
*
*/
public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable
{
private static HandlerList handlers = new HandlerList();
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot
*
* @param flag Flag that was removed
* @param plot Plot from which the flag was removed
*/
public PlotFlagRemoveEvent(final Flag flag, final Plot plot)
{
super(plot);
this.flag = flag;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag()
{
return flag;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}
@Override
public final boolean isCancelled()
{
return cancelled;
}
@Override
public final void setCancelled(final boolean cancelled)
{
this.cancelled = cancelled;

View File

@ -1,94 +1,102 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import java.util.ArrayList;
import org.bukkit.World;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
/**
* @author Empire92
*/
public class PlotMergeEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final ArrayList<PlotId> plots;
private boolean cancelled;
private Plot plot;
private World world;
/**
* PlotMergeEvent: Called when plots are merged
*
* @param world World in which the event occurred
* @param plot Plot that was merged
* @param plots A list of plots involved in the event
*/
public PlotMergeEvent(final World world, final Plot plot, final ArrayList<PlotId> plots) {
this.plots = plots;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the plots being added;
*
* @return Plot
*/
public ArrayList<PlotId> getPlots() {
return this.plots;
}
/**
* Get the main plot
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
public World getWorld() {
return this.world;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(final boolean b) {
this.cancelled = b;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import java.util.ArrayList;
import org.bukkit.World;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
/**
*/
public class PlotMergeEvent extends Event implements Cancellable
{
private static HandlerList handlers = new HandlerList();
private final ArrayList<PlotId> plots;
private boolean cancelled;
private Plot plot;
private World world;
/**
* PlotMergeEvent: Called when plots are merged
*
* @param world World in which the event occurred
* @param plot Plot that was merged
* @param plots A list of plots involved in the event
*/
public PlotMergeEvent(final World world, final Plot plot, final ArrayList<PlotId> plots)
{
this.plots = plots;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* Get the plots being added;
*
* @return Plot
*/
public ArrayList<PlotId> getPlots()
{
return plots;
}
/**
* Get the main plot
*
* @return Plot
*/
public Plot getPlot()
{
return plot;
}
public World getWorld()
{
return world;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}
@Override
public boolean isCancelled()
{
return cancelled;
}
@Override
public void setCancelled(final boolean b)
{
cancelled = b;
}

View File

@ -1,47 +1,53 @@
package com.plotsquared.bukkit.events;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.Rating;
/**
* Created 2015-07-13 for PlotSquaredGit
*
* @author Citymonstret
*/
public class PlotRateEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList();
private final PlotPlayer rater;
private Rating rating;
public PlotRateEvent(final PlotPlayer rater, final Rating rating, final Plot plot) {
super(plot);
this.rater = rater;
this.rating = rating;
}
public static HandlerList getHandlerList() {
return handlers;
}
public PlotPlayer getRater() {
return this.rater;
}
public void setRating(Rating rating) {
this.rating = rating;
}
public Rating getRating() {
return this.rating;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}
package com.plotsquared.bukkit.events;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.Rating;
/**
* Created 2015-07-13 for PlotSquaredGit
*
*/
public class PlotRateEvent extends PlotEvent
{
private static HandlerList handlers = new HandlerList();
private final PlotPlayer rater;
private Rating rating;
public PlotRateEvent(final PlotPlayer rater, final Rating rating, final Plot plot)
{
super(plot);
this.rater = rater;
this.rating = rating;
}
public static HandlerList getHandlerList()
{
return handlers;
}
public PlotPlayer getRater()
{
return rater;
}
public void setRating(final Rating rating)
{
this.rating = rating;
}
public Rating getRating()
{
return rating;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}

View File

@ -1,83 +1,90 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import java.util.ArrayList;
import org.bukkit.World;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.PlotId;
/**
* @author Empire92
*/
public class PlotUnlinkEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList();
private final ArrayList<PlotId> plots;
private final World world;
private boolean cancelled;
/**
* Called when a mega-plot is unlinked.
*
* @param world World in which the event occurred
* @param plots Plots that are involved in the event
*/
public PlotUnlinkEvent(final World world, final ArrayList<PlotId> plots) {
this.plots = plots;
this.world = world;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the plots involved
*
* @return PlotId
*/
public ArrayList<PlotId> getPlots() {
return this.plots;
}
public World getWorld() {
return this.world;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(final boolean b) {
this.cancelled = b;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import java.util.ArrayList;
import org.bukkit.World;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.PlotId;
/**
*/
public class PlotUnlinkEvent extends Event implements Cancellable
{
private static HandlerList handlers = new HandlerList();
private final ArrayList<PlotId> plots;
private final World world;
private boolean cancelled;
/**
* Called when a mega-plot is unlinked.
*
* @param world World in which the event occurred
* @param plots Plots that are involved in the event
*/
public PlotUnlinkEvent(final World world, final ArrayList<PlotId> plots)
{
this.plots = plots;
this.world = world;
}
public static HandlerList getHandlerList()
{
return handlers;
}
/**
* Get the plots involved
*
* @return PlotId
*/
public ArrayList<PlotId> getPlots()
{
return plots;
}
public World getWorld()
{
return world;
}
@Override
public HandlerList getHandlers()
{
return handlers;
}
@Override
public boolean isCancelled()
{
return cancelled;
}
@Override
public void setCancelled(final boolean b)
{
cancelled = b;
}

View File

@ -25,7 +25,8 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.BukkitChunkManager;
import com.plotsquared.bukkit.util.BukkitSetBlockManager;
public class AugmentedPopulator extends BlockPopulator {
public class AugmentedPopulator extends BlockPopulator
{
public final PlotWorld plotworld;
public final PlotManager manager;
public final BukkitPlotGenerator generator;
@ -39,64 +40,80 @@ public class AugmentedPopulator extends BlockPopulator {
private final int tx;
private final int tz;
public AugmentedPopulator(final String world, final BukkitPlotGenerator generator, final PlotCluster cluster, final boolean p, final boolean b) {
public AugmentedPopulator(final String world, final BukkitPlotGenerator generator, final PlotCluster cluster, final boolean p, final boolean b)
{
MainUtil.initCache();
PS.log("== NEW AUGMENTED POPULATOR FOR: " + world);
this.cluster = cluster;
this.generator = generator;
this.plotworld = PS.get().getPlotWorld(world);
this.manager = generator.getPlotManager();
plotworld = PS.get().getPlotWorld(world);
manager = generator.getPlotManager();
this.p = p;
this.b = b;
this.o = (this.plotworld.TERRAIN == 1) || (this.plotworld.TERRAIN == 2);
o = (plotworld.TERRAIN == 1) || (plotworld.TERRAIN == 2);
final World bukkitWorld = Bukkit.getWorld(world);
if (cluster != null) {
final Location bl = this.manager.getPlotBottomLocAbs(this.plotworld, cluster.getP1());
final Location tl = this.manager.getPlotTopLocAbs(this.plotworld, cluster.getP2()).add(1, 0, 1);
this.bx = bl.getX();
this.bz = bl.getZ();
this.tx = tl.getX();
this.tz = tl.getZ();
} else {
this.bx = Integer.MIN_VALUE;
this.bz = Integer.MIN_VALUE;
this.tx = Integer.MAX_VALUE;
this.tz = Integer.MAX_VALUE;
if (cluster != null)
{
final Location bl = manager.getPlotBottomLocAbs(plotworld, cluster.getP1());
final Location tl = manager.getPlotTopLocAbs(plotworld, cluster.getP2()).add(1, 0, 1);
bx = bl.getX();
bz = bl.getZ();
tx = tl.getX();
tz = tl.getZ();
}
else
{
bx = Integer.MIN_VALUE;
bz = Integer.MIN_VALUE;
tx = Integer.MAX_VALUE;
tz = Integer.MAX_VALUE;
}
// Add the populator
if (this.o) {
if (o)
{
bukkitWorld.getPopulators().add(0, this);
} else {
}
else
{
bukkitWorld.getPopulators().add(this);
}
}
public static void removePopulator(final String worldname, final PlotCluster cluster) {
public static void removePopulator(final String worldname, final PlotCluster cluster)
{
final World world = Bukkit.getWorld(worldname);
for (final Iterator<BlockPopulator> iterator = world.getPopulators().iterator(); iterator.hasNext();) {
for (final Iterator<BlockPopulator> iterator = world.getPopulators().iterator(); iterator.hasNext();)
{
final BlockPopulator populator = iterator.next();
if (populator instanceof AugmentedPopulator) {
if (((AugmentedPopulator) populator).cluster.equals(cluster)) {
if (populator instanceof AugmentedPopulator)
{
if (((AugmentedPopulator) populator).cluster.equals(cluster))
{
iterator.remove();
}
}
}
}
public BlockWrapper get(final int x, final int z, final int i, final int j, final short[][] r, final boolean c) {
public BlockWrapper get(final int x, final int z, final int i, final int j, final short[][] r, final boolean c)
{
final int y = (i << 4) + (j >> 8);
final int a = (j - ((y & 0xF) << 8));
final int z1 = (a >> 4);
final int x1 = a - (z1 << 4);
if (r[i] == null) {
return (c && (((z + z1) < this.bz) || ((z + z1) > this.tz) || ((x + x1) < this.bx) || ((x + x1) > this.tx))) ? null : new BlockWrapper(x1, y, z1, (short) 0, (byte) 0);
} else {
return (c && (((z + z1) < this.bz) || ((z + z1) > this.tz) || ((x + x1) < this.bx) || ((x + x1) > this.tx))) ? null : new BlockWrapper(x1, y, z1, r[i][j], (byte) 0);
if (r[i] == null)
{
return (c && (((z + z1) < bz) || ((z + z1) > tz) || ((x + x1) < bx) || ((x + x1) > tx))) ? null : new BlockWrapper(x1, y, z1, (short) 0, (byte) 0);
}
else
{
return (c && (((z + z1) < bz) || ((z + z1) > tz) || ((x + x1) < bx) || ((x + x1) > tx))) ? null : new BlockWrapper(x1, y, z1, r[i][j], (byte) 0);
}
}
@Override
public void populate(final World world, final Random rand, final Chunk chunk) {
public void populate(final World world, final Random rand, final Chunk chunk)
{
final int cx = chunk.getX();
final int cz = chunk.getZ();
final int bx = cx << 4;
@ -109,25 +126,30 @@ public class AugmentedPopulator extends BlockPopulator {
final boolean inZ2 = ((tz >= this.bz) && (tz <= this.tz));
final boolean inX = inX1 || inX2;
final boolean inZ = inZ1 || inZ2;
if (!inX || !inZ) {
return;
}
if (this.plotworld.TERRAIN == 3) {
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
if (ChunkManager.FORCE_PASTE) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
if (!inX || !inZ) { return; }
if (plotworld.TERRAIN == 3)
{
final int X = chunk.getX() << 4;
final int Z = chunk.getZ() << 4;
if (ChunkManager.FORCE_PASTE)
{
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
{
final PlotLoc loc = new PlotLoc((short) (X + x), (short) (Z + z));
final HashMap<Short, Short> blocks = ChunkManager.GENERATE_BLOCKS.get(loc);
HashMap<Short, Byte> datas = ChunkManager.GENERATE_DATA.get(loc);
for (final Entry<Short, Short> entry : blocks.entrySet()) {
int y = entry.getKey();
final HashMap<Short, Byte> datas = ChunkManager.GENERATE_DATA.get(loc);
for (final Entry<Short, Short> entry : blocks.entrySet())
{
final int y = entry.getKey();
byte data;
if (datas != null) {
if (datas != null)
{
data = datas.get(y);
}
else {
else
{
data = 0;
}
BukkitSetBlockManager.setBlockManager.set(world, x, y, z, blocks.get(y), data);
@ -136,24 +158,31 @@ public class AugmentedPopulator extends BlockPopulator {
}
return;
}
if (ChunkManager.CURRENT_PLOT_CLEAR != null) {
if (ChunkManager.CURRENT_PLOT_CLEAR != null)
{
PlotLoc loc;
for (Entry<PlotLoc, HashMap<Short, Byte>> entry : ChunkManager.GENERATE_DATA.entrySet()) {
HashMap<Short, Byte> datas = ChunkManager.GENERATE_DATA.get(entry.getKey());
for (Entry<Short, Byte> entry2 : entry.getValue().entrySet()) {
Short y = entry2.getKey();
for (final Entry<PlotLoc, HashMap<Short, Byte>> entry : ChunkManager.GENERATE_DATA.entrySet())
{
final HashMap<Short, Byte> datas = ChunkManager.GENERATE_DATA.get(entry.getKey());
for (final Entry<Short, Byte> entry2 : entry.getValue().entrySet())
{
final Short y = entry2.getKey();
byte data;
if (datas != null) {
if (datas != null)
{
data = datas.get(y);
}
else {
else
{
data = 0;
}
loc = entry.getKey();
int xx = loc.x - X;
int zz = loc.z - Z;
if (xx >= 0 && xx < 16) {
if (zz >= 0 && zz < 16) {
final int xx = loc.x - X;
final int zz = loc.z - Z;
if ((xx >= 0) && (xx < 16))
{
if ((zz >= 0) && (zz < 16))
{
BukkitSetBlockManager.setBlockManager.set(world, xx, y, zz, entry2.getValue(), data);
}
}
@ -164,25 +193,31 @@ public class AugmentedPopulator extends BlockPopulator {
}
final boolean check;
check = !inX1 || !inX2 || !inZ1 || !inZ2;
if (this.plotworld.TERRAIN > 1) {
final PlotId plot1 = this.manager.getPlotIdAbs(this.plotworld, bx, 0, bz);
final PlotId plot2 = this.manager.getPlotIdAbs(this.plotworld, tx, 0, tz);
if ((plot1 != null) && (plot2 != null) && plot1.equals(plot2)) {
return;
}
if (plotworld.TERRAIN > 1)
{
final PlotId plot1 = manager.getPlotIdAbs(plotworld, bx, 0, bz);
final PlotId plot2 = manager.getPlotIdAbs(plotworld, tx, 0, tz);
if ((plot1 != null) && (plot2 != null) && plot1.equals(plot2)) { return; }
}
if (this.o) {
if (o)
{
populateBlocks(world, rand, cx, cz, bx, bz, check);
} else {
TaskManager.runTaskLater(new Runnable() {
}
else
{
TaskManager.runTaskLater(new Runnable()
{
@Override
public void run() {
public void run()
{
populateBiome(world, bx, bz);
}
}, 20 + rand.nextInt(10));
TaskManager.runTaskLater(new Runnable() {
TaskManager.runTaskLater(new Runnable()
{
@Override
public void run() {
public void run()
{
chunk.load(true);
populateBlocks(world, rand, cx, cz, bx, bz, check);
}
@ -190,61 +225,86 @@ public class AugmentedPopulator extends BlockPopulator {
}
}
private void populateBiome(final World world, final int x, final int z) {
final Biome biome = Biome.valueOf(this.plotworld.PLOT_BIOME);
if (this.b) {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
private void populateBiome(final World world, final int x, final int z)
{
final Biome biome = Biome.valueOf(plotworld.PLOT_BIOME);
if (b)
{
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 16; j++)
{
world.setBiome(x + i, z + j, biome);
}
}
}
}
private void populateBlocks(final World world, final Random rand, final int X, final int Z, final int x, final int z, final boolean check) {
final short[][] result = this.generator.generateExtBlockSections(world, rand, X, Z, null);
for (int i = 0; i < result.length; i++) {
if (result[i] != null) {
for (int j = 0; j < 4096; j++) {
int x1 = MainUtil.x_loc[i][j];
int y = MainUtil.y_loc[i][j];
int z1 = MainUtil.z_loc[i][j];
short id = result[i][j];
private void populateBlocks(final World world, final Random rand, final int X, final int Z, final int x, final int z, final boolean check)
{
final short[][] result = generator.generateExtBlockSections(world, rand, X, Z, null);
for (int i = 0; i < result.length; i++)
{
if (result[i] != null)
{
for (int j = 0; j < 4096; j++)
{
final int x1 = MainUtil.x_loc[i][j];
final int y = MainUtil.y_loc[i][j];
final int z1 = MainUtil.z_loc[i][j];
final short id = result[i][j];
final int xx = x + x1;
final int zz = z + z1;
if (check && (((zz) < this.bz) || ((zz) > this.tz) || ((xx) < this.bx) || ((xx) > this.tx))) {
if (check && (((zz) < bz) || ((zz) > tz) || ((xx) < bx) || ((xx) > tx)))
{
continue;
}
if (this.p) {
if (ChunkManager.CURRENT_PLOT_CLEAR != null) {
if (BukkitChunkManager.isIn(ChunkManager.CURRENT_PLOT_CLEAR, xx, zz)) {
if (p)
{
if (ChunkManager.CURRENT_PLOT_CLEAR != null)
{
if (BukkitChunkManager.isIn(ChunkManager.CURRENT_PLOT_CLEAR, xx, zz))
{
continue;
}
} else if (this.manager.getPlotIdAbs(this.plotworld, xx, 0, zz) != null) {
}
else if (manager.getPlotIdAbs(plotworld, xx, 0, zz) != null)
{
continue;
}
}
BukkitSetBlockManager.setBlockManager.set(world, xx, y, zz, id, (byte) 0);
}
}
else {
short y_min = MainUtil.y_loc[i][0];
if (y_min < 128) {
for (int x1 = x; x1 < x + 16; x1++) {
for (int z1 = z; z1 < z + 16; z1++) {
if (check && (((z1) < this.bz) || ((z1) > this.tz) || ((x1) < this.bx) || ((x1) > this.tx))) {
else
{
final short y_min = MainUtil.y_loc[i][0];
if (y_min < 128)
{
for (int x1 = x; x1 < (x + 16); x1++)
{
for (int z1 = z; z1 < (z + 16); z1++)
{
if (check && (((z1) < bz) || ((z1) > tz) || ((x1) < bx) || ((x1) > tx)))
{
continue;
}
if (this.p) {
if (ChunkManager.CURRENT_PLOT_CLEAR != null) {
if (BukkitChunkManager.isIn(ChunkManager.CURRENT_PLOT_CLEAR, x1, z1)) {
if (p)
{
if (ChunkManager.CURRENT_PLOT_CLEAR != null)
{
if (BukkitChunkManager.isIn(ChunkManager.CURRENT_PLOT_CLEAR, x1, z1))
{
continue;
}
} else if (this.manager.getPlotIdAbs(this.plotworld, x1, 0, z1) != null) {
}
else if (manager.getPlotIdAbs(plotworld, x1, 0, z1) != null)
{
continue;
}
}
for (int y = y_min; y < y_min + 16; y++) {
for (int y = y_min; y < (y_min + 16); y++)
{
BukkitSetBlockManager.setBlockManager.set(world, x1, y, z1, 0, (byte) 0);
}
}
@ -252,9 +312,10 @@ public class AugmentedPopulator extends BlockPopulator {
}
}
}
for (final BlockPopulator populator : this.generator.getPopulators(world.getName())) {
Chunk chunk = world.getChunkAt(X, Z);
populator.populate(world, this.r, chunk);
for (final BlockPopulator populator : generator.getPopulators(world.getName()))
{
final Chunk chunk = world.getChunkAt(X, Z);
populator.populate(world, r, chunk);
}
}
}

View File

@ -9,81 +9,94 @@ import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.SetupObject;
public class BukkitGeneratorWrapper extends PlotGenerator<ChunkGenerator> {
public class BukkitGeneratorWrapper extends PlotGenerator<ChunkGenerator>
{
public final boolean full;
public BukkitGeneratorWrapper(String world, ChunkGenerator generator) {
public BukkitGeneratorWrapper(final String world, final ChunkGenerator generator)
{
super(world, generator);
full = (generator instanceof BukkitPlotGenerator);
}
@Override
public void initialize(PlotWorld plotworld) {
if (generator instanceof BukkitPlotGenerator) {
public void initialize(final PlotWorld plotworld)
{
if (generator instanceof BukkitPlotGenerator)
{
((BukkitPlotGenerator) generator).init(plotworld);
}
}
@Override
public void augment(PlotCluster cluster, PlotWorld plotworld) {
if (generator instanceof BukkitPlotGenerator) {
BukkitPlotGenerator plotgen = (BukkitPlotGenerator) generator;
if (cluster != null) {
public void augment(final PlotCluster cluster, final PlotWorld plotworld)
{
if (generator instanceof BukkitPlotGenerator)
{
final BukkitPlotGenerator plotgen = (BukkitPlotGenerator) generator;
if (cluster != null)
{
new AugmentedPopulator(world, plotgen, cluster, plotworld.TERRAIN == 2, plotworld.TERRAIN != 2);
}
else {
else
{
new AugmentedPopulator(world, plotgen, null, plotworld.TERRAIN == 2, plotworld.TERRAIN != 2);
}
}
}
@Override
public void setGenerator(String gen_string) {
if (gen_string == null) {
public void setGenerator(final String gen_string)
{
if (gen_string == null)
{
generator = new HybridGen(world);
} else {
PlotGenerator<ChunkGenerator> gen_wrapper = (PlotGenerator<ChunkGenerator>) PS.get().IMP.getGenerator(world, gen_string);
if (gen_wrapper != null) {
}
else
{
final PlotGenerator<ChunkGenerator> gen_wrapper = (PlotGenerator<ChunkGenerator>) PS.get().IMP.getGenerator(world, gen_string);
if (gen_wrapper != null)
{
generator = gen_wrapper.generator;
}
}
}
@Override
public PlotWorld getNewPlotWorld(String world) {
if (!(generator instanceof BukkitPlotGenerator)) {
return null;
}
public PlotWorld getNewPlotWorld(final String world)
{
if (!(generator instanceof BukkitPlotGenerator)) { return null; }
return ((BukkitPlotGenerator) generator).getNewPlotWorld(world);
}
@Override
public PlotManager getPlotManager() {
if (!(generator instanceof BukkitPlotGenerator)) {
return null;
}
public PlotManager getPlotManager()
{
if (!(generator instanceof BukkitPlotGenerator)) { return null; }
return ((BukkitPlotGenerator) generator).getPlotManager();
}
@Override
public boolean isFull() {
public boolean isFull()
{
return full;
}
@Override
public String getName() {
if (generator == null) {
return "Null";
}
public String getName()
{
if (generator == null) { return "Null"; }
return generator.getClass().getName();
}
@Override
public void processSetup(SetupObject object) {
if (generator instanceof BukkitPlotGenerator) {
public void processSetup(final SetupObject object)
{
if (generator instanceof BukkitPlotGenerator)
{
((BukkitPlotGenerator) generator).processSetup(object);
}
}
}

View File

@ -41,7 +41,8 @@ import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.plotsquared.bukkit.listeners.WorldEvents;
public abstract class BukkitPlotGenerator extends ChunkGenerator {
public abstract class BukkitPlotGenerator extends ChunkGenerator
{
public static short[][][] CACHE_I = null;
public static short[][][] CACHE_J = null;
@ -49,22 +50,28 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator {
public int Z;
private boolean loaded = false;
private short[][] result;
private PseudoRandom random = new PseudoRandom();
public BukkitPlotGenerator(String world) {
private final PseudoRandom random = new PseudoRandom();
public BukkitPlotGenerator(final String world)
{
WorldEvents.lastWorld = world;
initCache();
}
public void initCache() {
if (CACHE_I == null) {
public void initCache()
{
if (CACHE_I == null)
{
CACHE_I = new short[256][16][16];
CACHE_J = new short[256][16][16];
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
for (int y = 0; y < 256; y++) {
short i = (short) (y >> 4);
short j = (short) (((y & 0xF) << 8) | (z << 4) | x);
for (int x = 0; x < 16; x++)
{
for (int z = 0; z < 16; z++)
{
for (int y = 0; y < 256; y++)
{
final short i = (short) (y >> 4);
final short j = (short) (((y & 0xF) << 8) | (z << 4) | x);
CACHE_I[y][x][z] = i;
CACHE_J[y][x][z] = j;
}
@ -75,14 +82,19 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator {
@SuppressWarnings("unchecked")
@Override
public List<BlockPopulator> getDefaultPopulators(World world) {
try {
if (!loaded) {
String name = WorldEvents.getName(world);
public List<BlockPopulator> getDefaultPopulators(final World world)
{
try
{
if (!loaded)
{
final String name = WorldEvents.getName(world);
PS.get().loadWorld(name, new BukkitGeneratorWrapper(name, this));
PlotWorld plotworld = PS.get().getPlotWorld(WorldEvents.getName(world));
if (!plotworld.MOB_SPAWNING) {
if (!plotworld.SPAWN_EGGS) {
final PlotWorld plotworld = PS.get().getPlotWorld(WorldEvents.getName(world));
if (!plotworld.MOB_SPAWNING)
{
if (!plotworld.SPAWN_EGGS)
{
world.setSpawnFlags(false, false);
}
world.setAmbientSpawnLimit(0);
@ -90,7 +102,8 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator {
world.setMonsterSpawnLimit(0);
world.setWaterAnimalSpawnLimit(0);
}
else {
else
{
world.setSpawnFlags(true, true);
world.setAmbientSpawnLimit(-1);
world.setAnimalSpawnLimit(-1);
@ -98,28 +111,33 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator {
world.setWaterAnimalSpawnLimit(-1);
}
loaded = true;
return (List<BlockPopulator>)(List<?>) getPopulators(WorldEvents.getName(world));
return (List<BlockPopulator>) (List<?>) getPopulators(WorldEvents.getName(world));
}
}
catch (Exception e) {
catch (final Exception e)
{
e.printStackTrace();
}
return new ArrayList<BlockPopulator>();
}
/**
* Set the result;
* @param result
*/
public void setResult(short[][] result) {
public void setResult(final short[][] result)
{
this.result = result;
}
@Override
public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, BiomeGrid biomes) {
try {
if (!loaded) {
String name = WorldEvents.getName(world);
public short[][] generateExtBlockSections(final World world, final Random r, final int cx, final int cz, final BiomeGrid biomes)
{
try
{
if (!loaded)
{
final String name = WorldEvents.getName(world);
PS.get().loadWorld(name, new BukkitGeneratorWrapper(name, this));
loaded = true;
}
@ -127,37 +145,47 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator {
int h = 1;
h = (prime * h) + cx;
h = (prime * h) + cz;
this.random.state = h;
this.result = new short[16][];
this.X = cx << 4;
this.Z = cz << 4;
if (ChunkManager.FORCE_PASTE) {
PlotWorld plotworld = PS.get().getPlotWorld(world.getName());
Biome biome = Biome.valueOf(plotworld.PLOT_BIOME);
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
if (biomes != null) {
random.state = h;
result = new short[16][];
X = cx << 4;
Z = cz << 4;
if (ChunkManager.FORCE_PASTE)
{
final PlotWorld plotworld = PS.get().getPlotWorld(world.getName());
final Biome biome = Biome.valueOf(plotworld.PLOT_BIOME);
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
{
if (biomes != null)
{
biomes.setBiome(x, z, biome);
}
final PlotLoc loc = new PlotLoc((X + x), (Z + z));
final HashMap<Short, Short> blocks = ChunkManager.GENERATE_BLOCKS.get(loc);
for (final Entry<Short, Short> entry : blocks.entrySet()) {
for (final Entry<Short, Short> entry : blocks.entrySet())
{
setBlock(x, entry.getKey(), z, entry.getValue());
}
}
}
return this.result;
return result;
}
generateChunk(world, ChunkManager.CURRENT_PLOT_CLEAR, random, cx, cz, biomes);
if (ChunkManager.CURRENT_PLOT_CLEAR != null) {
if (ChunkManager.CURRENT_PLOT_CLEAR != null)
{
PlotLoc loc;
for (Entry<PlotLoc, HashMap<Short, Short>> entry : ChunkManager.GENERATE_BLOCKS.entrySet()) {
for (Entry<Short, Short> entry2 : entry.getValue().entrySet()) {
for (final Entry<PlotLoc, HashMap<Short, Short>> entry : ChunkManager.GENERATE_BLOCKS.entrySet())
{
for (final Entry<Short, Short> entry2 : entry.getValue().entrySet())
{
loc = entry.getKey();
int xx = loc.x - X;
int zz = loc.z - Z;
if (xx >= 0 && xx < 16) {
if (zz >= 0 && zz < 16) {
final int xx = loc.x - X;
final int zz = loc.z - Z;
if ((xx >= 0) && (xx < 16))
{
if ((zz >= 0) && (zz < 16))
{
setBlock(xx, entry2.getKey(), zz, entry2.getValue());
}
}
@ -165,30 +193,36 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator {
}
}
}
catch (Exception e) {
catch (final Exception e)
{
e.printStackTrace();
}
return result;
}
public void setBlock(final int x, final int y, final int z, final short blkid) {
if (result[CACHE_I[y][x][z]] == null) {
public void setBlock(final int x, final int y, final int z, final short blkid)
{
if (result[CACHE_I[y][x][z]] == null)
{
result[CACHE_I[y][x][z]] = new short[4096];
}
result[CACHE_I[y][x][z]][CACHE_J[y][x][z]] = blkid;
}
public void setBlock(final int x, final int y, final int z, final short[] blkid) {
if (blkid.length == 1) {
public void setBlock(final int x, final int y, final int z, final short[] blkid)
{
if (blkid.length == 1)
{
setBlock(x, y, z, blkid[0]);
}
short id = blkid[random.random(blkid.length)];
if (result[CACHE_I[y][x][z]] == null) {
final short id = blkid[random.random(blkid.length)];
if (result[CACHE_I[y][x][z]] == null)
{
result[CACHE_I[y][x][z]] = new short[4096];
}
result[CACHE_I[y][x][z]][CACHE_J[y][x][z]] = id;
}
/**
* check if a region contains a location. (x, z) must be between [0,15], [0,15]
* @param plot
@ -196,22 +230,24 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator {
* @param z
* @return
*/
public boolean contains(final RegionWrapper plot, final int x, final int z) {
int xx = X + x;
int zz = Z + z;
public boolean contains(final RegionWrapper plot, final int x, final int z)
{
final int xx = X + x;
final int zz = Z + z;
return ((xx >= plot.minX) && (xx <= plot.maxX) && (zz >= plot.minZ) && (zz <= plot.maxZ));
}
/**
* Allow spawning everywhere
*/
@Override
public boolean canSpawn(final World world, final int x, final int z) {
public boolean canSpawn(final World world, final int x, final int z)
{
return true;
}
/**
* <b>random</b> is an optimized random number generator.<br>
* <b>random</b> is an optimized random number generator.<br>
* - Change the state to have the same chunk random each time it generates<br>
* <b>requiredRegion</b> If a plot is being regenerated, you are only required to generate content in this area<br>
* - use the contains(RegionWrapper, x, z) method to check if the region contains a location<br>
@ -219,7 +255,7 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator {
* - will be null if no restrictions are set<br>
* <b>result</b> is the standard 2D block data array used for generation<br>
* <b>biomes</b> is the standard BiomeGrid used for generation
*
*
* @param world
* @param random
* @param cx
@ -229,19 +265,19 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator {
* @param result
* @return
*/
public abstract void generateChunk(final World world, RegionWrapper requiredRegion, final PseudoRandom random, final int cx, final int cz, final BiomeGrid biomes);
public abstract List<BukkitPlotPopulator> getPopulators(String world);
public abstract void generateChunk(final World world, final RegionWrapper requiredRegion, final PseudoRandom random, final int cx, final int cz, final BiomeGrid biomes);
public abstract List<BukkitPlotPopulator> getPopulators(final String world);
/**
* This is called when the generator is initialized.
* This is called when the generator is initialized.
* You don't need to do anything with it necessarily.
* @param plotworld
*/
public abstract void init(PlotWorld plotworld);
public abstract void init(final PlotWorld plotworld);
/**
* Return a new instance of the PlotWorld for a world
* Return a new instance of the PlotWorld for a world
* @param world
* @return
*/
@ -252,13 +288,13 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator {
* @return
*/
public abstract PlotManager getPlotManager();
/**
* If you need to do anything fancy for /plot setup<br>
* - Otherwise it will just use the PlotWorld configuration<br>
* Feel free to extend BukkitSetupUtils and customize world creation
* @param object
*/
public void processSetup(SetupObject object) {
}
public void processSetup(final SetupObject object)
{}
}

View File

@ -15,28 +15,33 @@ import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.SetBlockQueue;
public abstract class BukkitPlotPopulator extends BlockPopulator {
private PseudoRandom random = new PseudoRandom();
public abstract class BukkitPlotPopulator extends BlockPopulator
{
private final PseudoRandom random = new PseudoRandom();
public int X;
public int Z;
public String worldname;
private World world;
@Override
public void populate(World world, Random rand, Chunk chunk) {
public void populate(final World world, final Random rand, final Chunk chunk)
{
this.world = world;
this.worldname = world.getName();
this.X = chunk.getX() << 4;
this.Z = chunk.getZ() << 4;
if (ChunkManager.FORCE_PASTE) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
worldname = world.getName();
X = chunk.getX() << 4;
Z = chunk.getZ() << 4;
if (ChunkManager.FORCE_PASTE)
{
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
{
final PlotLoc loc = new PlotLoc((short) (X + x), (short) (Z + z));
final HashMap<Short, Byte> blocks = ChunkManager.GENERATE_DATA.get(loc);
for (final Entry<Short, Byte> entry : blocks.entrySet()) {
for (final Entry<Short, Byte> entry : blocks.entrySet())
{
setBlock(x, entry.getKey(), z, entry.getValue());
}
}
@ -44,25 +49,30 @@ public abstract class BukkitPlotPopulator extends BlockPopulator {
return;
}
populate(world, ChunkManager.CURRENT_PLOT_CLEAR, random, X, Z);
if (ChunkManager.CURRENT_PLOT_CLEAR != null) {
if (ChunkManager.CURRENT_PLOT_CLEAR != null)
{
PlotLoc loc;
for (Entry<PlotLoc, HashMap<Short, Byte>> entry : ChunkManager.GENERATE_DATA.entrySet()) {
for (Entry<Short, Byte> entry2 : entry.getValue().entrySet()) {
for (final Entry<PlotLoc, HashMap<Short, Byte>> entry : ChunkManager.GENERATE_DATA.entrySet())
{
for (final Entry<Short, Byte> entry2 : entry.getValue().entrySet())
{
loc = entry.getKey();
int xx = loc.x - X;
int zz = loc.z - Z;
if (xx >= 0 && xx < 16) {
if (zz >= 0 && zz < 16) {
setBlock(xx, entry2.getKey(), zz, entry2.getValue());
}
final int xx = loc.x - X;
final int zz = loc.z - Z;
if ((xx >= 0) && (xx < 16))
{
if ((zz >= 0) && (zz < 16))
{
setBlock(xx, entry2.getKey(), zz, entry2.getValue());
}
}
}
}
}
}
public abstract void populate(World world, RegionWrapper requiredRegion, PseudoRandom random, int cx, int cz);
public abstract void populate(final World world, final RegionWrapper requiredRegion, final PseudoRandom random, final int cx, final int cz);
/**
* Set the id and data at a location. (x, y, z) must be between [0,15], [0,255], [0,15]
* @param x
@ -71,15 +81,18 @@ public abstract class BukkitPlotPopulator extends BlockPopulator {
* @param id
* @param data
*/
public void setBlock(int x, int y, int z, short id, byte data) {
if (data == 0) {
public void setBlock(final int x, final int y, final int z, final short id, final byte data)
{
if (data == 0)
{
SetBlockQueue.setBlock(worldname, x, y, z, id);
}
else {
else
{
SetBlockQueue.setBlock(worldname, x, y, z, new PlotBlock(id, data));
}
}
/**
* Set the data at a location. (x, y, z) must be between [0,15], [0,255], [0,15]
* @param x
@ -87,12 +100,14 @@ public abstract class BukkitPlotPopulator extends BlockPopulator {
* @param z
* @param data
*/
public void setBlock(int x, int y, int z, byte data) {
if (data != 0) {
public void setBlock(final int x, final int y, final int z, final byte data)
{
if (data != 0)
{
world.getBlockAt(X + x, y, Z + z).setData(data);
}
}
/**
* Like setblock, but lacks the data != 0 check
* @param x
@ -100,10 +115,11 @@ public abstract class BukkitPlotPopulator extends BlockPopulator {
* @param z
* @param data
*/
public void setBlockAbs(int x, int y, int z, byte data) {
public void setBlockAbs(final int x, final int y, final int z, final byte data)
{
world.getBlockAt(X + x, y, Z + z).setData(data);
}
/**
* check if a region contains a location. (x, z) must be between [0,15], [0,15]
* @param plot
@ -111,10 +127,11 @@ public abstract class BukkitPlotPopulator extends BlockPopulator {
* @param z
* @return
*/
public boolean contains(final RegionWrapper plot, final int x, final int z) {
int xx = X + x;
int zz = Z + z;
public boolean contains(final RegionWrapper plot, final int x, final int z)
{
final int xx = X + x;
final int zz = Z + z;
return ((xx >= plot.minX) && (xx <= plot.maxX) && (zz >= plot.minZ) && (zz <= plot.maxZ));
}
}

View File

@ -1,294 +1,358 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.generator;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.block.Biome;
import com.intellectualcrafters.plot.generator.HybridPlotManager;
import com.intellectualcrafters.plot.generator.HybridPlotWorld;
import com.intellectualcrafters.plot.object.PlotLoc;
import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.object.RegionWrapper;
/**
* The default generator is very messy, as we have decided to try externalize all calculations from within the loop. -
* You will see a lot of slower implementations have a single for loop. - This is perfectly fine to do, it will just
* mean world generation may take somewhat longer
*
* @author Citymonstret
* @author Empire92
*/
public class HybridGen extends BukkitPlotGenerator {
public HybridGen(String world) {
super(world);
}
/**
* Set to static to re-use the same managet for all Default World Generators
*/
private static PlotManager manager = null;
/**
* plotworld object
*/
public HybridPlotWorld plotworld = null;
/**
* Some generator specific variables (implementation dependent)
*/
int plotsize;
int pathsize;
short wall;
short wallfilling;
short roadblock;
int size;
Biome biome;
int roadheight;
int wallheight;
int plotheight;
short[] plotfloors;
short[] filling;
short pathWidthLower;
short pathWidthUpper;
boolean doState = false;
int maxY = 0;
short[][] cached;
/**
* Initialize variables, and create plotworld object used in calculations
*/
public void init(PlotWorld plotworld) {
if (plotworld != null) {
this.plotworld = (HybridPlotWorld) plotworld;
}
this.plotsize = this.plotworld.PLOT_WIDTH;
this.pathsize = this.plotworld.ROAD_WIDTH;
this.roadblock = this.plotworld.ROAD_BLOCK.id;
this.wallfilling = this.plotworld.WALL_FILLING.id;
this.size = this.pathsize + this.plotsize;
this.wall = this.plotworld.WALL_BLOCK.id;
this.plotfloors = new short[this.plotworld.TOP_BLOCK.length];
for (int i = 0; i < this.plotworld.TOP_BLOCK.length; i++) {
this.plotfloors[i] = this.plotworld.TOP_BLOCK[i].id;
}
this.filling = new short[this.plotworld.MAIN_BLOCK.length];
for (int i = 0; i < this.plotworld.MAIN_BLOCK.length; i++) {
this.filling[i] = this.plotworld.MAIN_BLOCK[i].id;
}
if ((this.filling.length > 1) || (this.plotfloors.length > 1)) {
this.doState = true;
}
this.wallheight = this.plotworld.WALL_HEIGHT;
this.roadheight = this.plotworld.ROAD_HEIGHT;
this.plotheight = this.plotworld.PLOT_HEIGHT;
if (this.pathsize == 0) {
this.pathWidthLower = (short) -1;
this.pathWidthUpper = (short) (this.plotsize + 1);
}
else {
if ((this.pathsize % 2) == 0) {
this.pathWidthLower = (short) (Math.floor(this.pathsize / 2) - 1);
} else {
this.pathWidthLower = (short) (Math.floor(this.pathsize / 2));
}
this.pathWidthUpper = (short) (this.pathWidthLower + this.plotsize + 1);
}
this.biome = Biome.valueOf(this.plotworld.PLOT_BIOME);
try {
this.maxY = Bukkit.getWorld(plotworld.worldname).getMaxHeight();
} catch (final NullPointerException e) {}
if (this.maxY == 0) {
this.maxY = 256;
}
// create cached chunk (for optimized chunk generation)
if (!this.plotworld.PLOT_SCHEMATIC) {
this.cached = new short[(plotheight + 16) / 16][];
for (int i = 0; i < cached.length; i++) {
cached[i] = new short[4096];
}
PseudoRandom random = new PseudoRandom();
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
cached[CACHE_I[plotheight][x][z]][CACHE_J[plotheight][x][z]] = plotfloors[random.random(plotfloors.length)];
if (this.plotworld.PLOT_BEDROCK) {
cached[CACHE_I[0][x][z]][CACHE_J[0][x][z]] = 7;
}
for (int y = 1; y < plotheight; y++) {
cached[CACHE_I[y][x][z]][CACHE_J[y][x][z]] = filling[random.random(filling.length)];
}
}
}
}
}
/**
* Return the plot manager for this type of generator, or create one For square plots you may as well use the
* default plot manager which comes with PlotSquared
*/
public PlotManager getPlotManager() {
if (HybridGen.manager == null) {
HybridGen.manager = new HybridPlotManager();
}
return HybridGen.manager;
}
/**
* Get a new plotworld class For square plots you can use the DefaultPlotWorld class which comes with PlotSquared
*/
public PlotWorld getNewPlotWorld(final String world) {
if (this.plotworld == null) {
this.plotworld = new HybridPlotWorld(world);
}
return this.plotworld;
}
/**
* Return the block populator
*/
public List<BukkitPlotPopulator> getPopulators(final String world) {
// You can have as many populators as you would like, e.g. tree
// populator, ore populator
return Arrays.asList((BukkitPlotPopulator) new HybridPop(this.plotworld));
}
/**
* This part is a fucking mess. - Refer to a proper tutorial if you would like to learn how to make a world
* generator
*/
public void generateChunk(final World world, RegionWrapper region, final PseudoRandom random, final int cx, final int cz, final BiomeGrid biomes) {
int sx = (short) ((this.X - this.plotworld.ROAD_OFFSET_X) % this.size);
int sz = (short) ((this.Z - this.plotworld.ROAD_OFFSET_Z) % this.size);
if (sx < 0) {
sx += this.size;
}
if (sz < 0) {
sz += this.size;
}
if (biomes != null) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
biomes.setBiome(x, z, this.biome);
}
}
}
if (cached != null) {
if (sx > pathWidthLower && sz > pathWidthLower && sx + 15 < pathWidthUpper&& sz + 15 < pathWidthUpper) {
setResult(cached);
return;
}
}
if (this.plotworld.PLOT_BEDROCK) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
setBlock(x, 0, z, (short) 7);
}
}
}
if (region != null) {
for (short x = 0; x < 16; x++) {
final int absX = ((sx + x) % this.size);
for (short z = 0; z < 16; z++) {
if (contains(region, x, z)) {
for (short y = 1; y < this.plotheight; y++) {
setBlock(x, y, z, this.filling);
}
setBlock(x, this.plotheight, z, this.plotfloors);
final int absZ = ((sz + z) % this.size);
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);
if (blocks != null) {
for (final Entry<Short, Short> entry : blocks.entrySet()) {
setBlock(x, this.plotheight + entry.getKey(), z, entry.getValue());
}
}
}
}
}
return;
}
for (short x = 0; x < 16; x++) {
final int absX = ((sx + x) % this.size);
final boolean gx = absX > this.pathWidthLower;
final boolean lx = absX < this.pathWidthUpper;
for (short z = 0; z < 16; z++) {
final int absZ = ((sz + z) % this.size);
final boolean gz = absZ > this.pathWidthLower;
final boolean lz = absZ < this.pathWidthUpper;
// inside plot
if (gx && gz && lx && lz) {
for (short y = 1; y < this.plotheight; y++) {
setBlock(x, y, z, this.filling);
}
setBlock(x, this.plotheight, z, this.plotfloors);
if (this.plotworld.PLOT_SCHEMATIC) {
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = this.plotworld.G_SCH.get(loc);
if (blocks != null) {
for (final Entry<Short, Short> entry : blocks.entrySet()) {
setBlock(x, this.plotheight + entry.getKey(), z, entry.getValue());
}
}
}
} else if (pathsize != 0) {
// wall
if (((absX >= this.pathWidthLower) && (absX <= this.pathWidthUpper) && (absZ >= this.pathWidthLower) && (absZ <= this.pathWidthUpper))) {
for (short y = 1; y <= this.wallheight; y++) {
setBlock(x, y, z, this.wallfilling);
}
if (!this.plotworld.ROAD_SCHEMATIC_ENABLED) {
setBlock(x, this.wallheight + 1, z, this.wall);
}
}
// road
else {
for (short y = 1; y <= this.roadheight; y++) {
setBlock(x, y, z, this.roadblock);
}
}
if (this.plotworld.ROAD_SCHEMATIC_ENABLED) {
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = this.plotworld.G_SCH.get(loc);
if (blocks != null) {
for (final Entry<Short, Short> entry : blocks.entrySet()) {
setBlock(x, this.roadheight + entry.getKey(), z, entry.getValue());
}
}
}
}
}
}
return;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.generator;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.block.Biome;
import com.intellectualcrafters.plot.generator.HybridPlotManager;
import com.intellectualcrafters.plot.generator.HybridPlotWorld;
import com.intellectualcrafters.plot.object.PlotLoc;
import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.object.RegionWrapper;
/**
* The default generator is very messy, as we have decided to try externalize all calculations from within the loop. -
* You will see a lot of slower implementations have a single for loop. - This is perfectly fine to do, it will just
* mean world generation may take somewhat longer
*
*/
public class HybridGen extends BukkitPlotGenerator
{
public HybridGen(final String world)
{
super(world);
}
/**
* Set to static to re-use the same managet for all Default World Generators
*/
private static PlotManager manager = null;
/**
* plotworld object
*/
public HybridPlotWorld plotworld = null;
/**
* Some generator specific variables (implementation dependent)
*/
int plotsize;
int pathsize;
short wall;
short wallfilling;
short roadblock;
int size;
Biome biome;
int roadheight;
int wallheight;
int plotheight;
short[] plotfloors;
short[] filling;
short pathWidthLower;
short pathWidthUpper;
boolean doState = false;
int maxY = 0;
short[][] cached;
/**
* Initialize variables, and create plotworld object used in calculations
*/
@Override
public void init(final PlotWorld plotworld)
{
if (plotworld != null)
{
this.plotworld = (HybridPlotWorld) plotworld;
}
plotsize = this.plotworld.PLOT_WIDTH;
pathsize = this.plotworld.ROAD_WIDTH;
roadblock = this.plotworld.ROAD_BLOCK.id;
wallfilling = this.plotworld.WALL_FILLING.id;
size = pathsize + plotsize;
wall = this.plotworld.WALL_BLOCK.id;
plotfloors = new short[this.plotworld.TOP_BLOCK.length];
for (int i = 0; i < this.plotworld.TOP_BLOCK.length; i++)
{
plotfloors[i] = this.plotworld.TOP_BLOCK[i].id;
}
filling = new short[this.plotworld.MAIN_BLOCK.length];
for (int i = 0; i < this.plotworld.MAIN_BLOCK.length; i++)
{
filling[i] = this.plotworld.MAIN_BLOCK[i].id;
}
if ((filling.length > 1) || (plotfloors.length > 1))
{
doState = true;
}
wallheight = this.plotworld.WALL_HEIGHT;
roadheight = this.plotworld.ROAD_HEIGHT;
plotheight = this.plotworld.PLOT_HEIGHT;
if (pathsize == 0)
{
pathWidthLower = (short) -1;
pathWidthUpper = (short) (plotsize + 1);
}
else
{
if ((pathsize % 2) == 0)
{
pathWidthLower = (short) (Math.floor(pathsize / 2) - 1);
}
else
{
pathWidthLower = (short) (Math.floor(pathsize / 2));
}
pathWidthUpper = (short) (pathWidthLower + plotsize + 1);
}
biome = Biome.valueOf(this.plotworld.PLOT_BIOME);
try
{
maxY = Bukkit.getWorld(plotworld.worldname).getMaxHeight();
}
catch (final NullPointerException e)
{}
if (maxY == 0)
{
maxY = 256;
}
// create cached chunk (for optimized chunk generation)
if (!this.plotworld.PLOT_SCHEMATIC)
{
cached = new short[(plotheight + 16) / 16][];
for (int i = 0; i < cached.length; i++)
{
cached[i] = new short[4096];
}
final PseudoRandom random = new PseudoRandom();
for (int x = 0; x < 16; x++)
{
for (int z = 0; z < 16; z++)
{
cached[CACHE_I[plotheight][x][z]][CACHE_J[plotheight][x][z]] = plotfloors[random.random(plotfloors.length)];
if (this.plotworld.PLOT_BEDROCK)
{
cached[CACHE_I[0][x][z]][CACHE_J[0][x][z]] = 7;
}
for (int y = 1; y < plotheight; y++)
{
cached[CACHE_I[y][x][z]][CACHE_J[y][x][z]] = filling[random.random(filling.length)];
}
}
}
}
}
/**
* Return the plot manager for this type of generator, or create one For square plots you may as well use the
* default plot manager which comes with PlotSquared
*/
@Override
public PlotManager getPlotManager()
{
if (HybridGen.manager == null)
{
HybridGen.manager = new HybridPlotManager();
}
return HybridGen.manager;
}
/**
* Get a new plotworld class For square plots you can use the DefaultPlotWorld class which comes with PlotSquared
*/
@Override
public PlotWorld getNewPlotWorld(final String world)
{
if (plotworld == null)
{
plotworld = new HybridPlotWorld(world);
}
return plotworld;
}
/**
* Return the block populator
*/
@Override
public List<BukkitPlotPopulator> getPopulators(final String world)
{
// You can have as many populators as you would like, e.g. tree
// populator, ore populator
return Arrays.asList((BukkitPlotPopulator) new HybridPop(plotworld));
}
/**
* This part is a fucking mess. - Refer to a proper tutorial if you would like to learn how to make a world
* generator
*/
@Override
public void generateChunk(final World world, final RegionWrapper region, final PseudoRandom random, final int cx, final int cz, final BiomeGrid biomes)
{
int sx = (short) ((X - plotworld.ROAD_OFFSET_X) % size);
int sz = (short) ((Z - plotworld.ROAD_OFFSET_Z) % size);
if (sx < 0)
{
sx += size;
}
if (sz < 0)
{
sz += size;
}
if (biomes != null)
{
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
{
biomes.setBiome(x, z, biome);
}
}
}
if (cached != null)
{
if ((sx > pathWidthLower) && (sz > pathWidthLower) && ((sx + 15) < pathWidthUpper) && ((sz + 15) < pathWidthUpper))
{
setResult(cached);
return;
}
}
if (plotworld.PLOT_BEDROCK)
{
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
{
setBlock(x, 0, z, (short) 7);
}
}
}
if (region != null)
{
for (short x = 0; x < 16; x++)
{
final int absX = ((sx + x) % size);
for (short z = 0; z < 16; z++)
{
if (contains(region, x, z))
{
for (short y = 1; y < plotheight; y++)
{
setBlock(x, y, z, filling);
}
setBlock(x, plotheight, z, plotfloors);
final int absZ = ((sz + z) % size);
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);
if (blocks != null)
{
for (final Entry<Short, Short> entry : blocks.entrySet())
{
setBlock(x, plotheight + entry.getKey(), z, entry.getValue());
}
}
}
}
}
return;
}
for (short x = 0; x < 16; x++)
{
final int absX = ((sx + x) % size);
final boolean gx = absX > pathWidthLower;
final boolean lx = absX < pathWidthUpper;
for (short z = 0; z < 16; z++)
{
final int absZ = ((sz + z) % size);
final boolean gz = absZ > pathWidthLower;
final boolean lz = absZ < pathWidthUpper;
// inside plot
if (gx && gz && lx && lz)
{
for (short y = 1; y < plotheight; y++)
{
setBlock(x, y, z, filling);
}
setBlock(x, plotheight, z, plotfloors);
if (plotworld.PLOT_SCHEMATIC)
{
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);
if (blocks != null)
{
for (final Entry<Short, Short> entry : blocks.entrySet())
{
setBlock(x, plotheight + entry.getKey(), z, entry.getValue());
}
}
}
}
else if (pathsize != 0)
{
// wall
if (((absX >= pathWidthLower) && (absX <= pathWidthUpper) && (absZ >= pathWidthLower) && (absZ <= pathWidthUpper)))
{
for (short y = 1; y <= wallheight; y++)
{
setBlock(x, y, z, wallfilling);
}
if (!plotworld.ROAD_SCHEMATIC_ENABLED)
{
setBlock(x, wallheight + 1, z, wall);
}
}
// road
else
{
for (short y = 1; y <= roadheight; y++)
{
setBlock(x, y, z, roadblock);
}
}
if (plotworld.ROAD_SCHEMATIC_ENABLED)
{
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);
if (blocks != null)
{
for (final Entry<Short, Short> entry : blocks.entrySet())
{
setBlock(x, roadheight + entry.getKey(), z, entry.getValue());
}
}
}
}
}
}
return;

View File

@ -1,233 +1,284 @@
package com.plotsquared.bukkit.generator;
import java.util.HashMap;
import java.util.HashSet;
import org.bukkit.World;
import org.bukkit.block.Biome;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.generator.HybridPlotWorld;
import com.intellectualcrafters.plot.object.PlotLoc;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.BlockManager;
/**
* @author Citymonstret
*/
public class HybridPop extends BukkitPlotPopulator {
/*
* Sorry, this isn't well documented at the moment.
* We advise you to take a look at a world generation tutorial for
* information about how a BlockPopulator works.
*/
final short plotsize;
final short pathsize;
final byte wall;
final byte wallfilling;
final byte roadblock;
final int size;
final int roadheight;
final int wallheight;
final int plotheight;
final byte[] plotfloors;
final byte[] filling;
final short pathWidthLower;
final short pathWidthUpper;
private final HybridPlotWorld plotworld;
Biome biome;
private long state;
private boolean doFilling = false;
private boolean doFloor = false;
private boolean doState = false;
public HybridPop(final PlotWorld pw) {
this.plotworld = (HybridPlotWorld) pw;
// save configuration
this.plotsize = (short) this.plotworld.PLOT_WIDTH;
this.pathsize = (short) this.plotworld.ROAD_WIDTH;
this.roadblock = this.plotworld.ROAD_BLOCK.data;
this.wallfilling = this.plotworld.WALL_FILLING.data;
this.size = this.pathsize + this.plotsize;
this.wall = this.plotworld.WALL_BLOCK.data;
int count1 = 0;
int count2 = 0;
this.plotfloors = new byte[this.plotworld.TOP_BLOCK.length];
for (int i = 0; i < this.plotworld.TOP_BLOCK.length; i++) {
count1++;
this.plotfloors[i] = this.plotworld.TOP_BLOCK[i].data;
if (this.plotworld.TOP_BLOCK[i].data != 0) {
this.doFloor = true;
}
}
this.filling = new byte[this.plotworld.MAIN_BLOCK.length];
for (int i = 0; i < this.plotworld.MAIN_BLOCK.length; i++) {
count2++;
this.filling[i] = this.plotworld.MAIN_BLOCK[i].data;
if (this.plotworld.MAIN_BLOCK[i].data != 0) {
this.doFilling = true;
}
}
if (((count1 > 0) && this.doFloor) || ((count2 > 0) && this.doFilling)) {
this.doState = true;
}
this.wallheight = this.plotworld.WALL_HEIGHT;
this.roadheight = this.plotworld.ROAD_HEIGHT;
this.plotheight = this.plotworld.PLOT_HEIGHT;
if (this.pathsize == 0) {
this.pathWidthLower = (short) -1;
this.pathWidthUpper = (short) (this.plotsize + 1);
}
else {
if ((this.pathsize % 2) == 0) {
this.pathWidthLower = (short) (Math.floor(this.pathsize / 2) - 1);
} else {
this.pathWidthLower = (short) (Math.floor(this.pathsize / 2));
}
this.pathWidthUpper = (short) (this.pathWidthLower + this.plotsize + 1);
}
}
public final long nextLong() {
final long a = this.state;
this.state = xorShift64(a);
return a;
}
public final long xorShift64(long a) {
a ^= (a << 21);
a ^= (a >>> 35);
a ^= (a << 4);
return a;
}
public final int random(final int n) {
final long result = ((nextLong() >>> 32) * n) >> 32;
return (int) result;
}
@Override
public void populate(World world, RegionWrapper requiredRegion, PseudoRandom random, int cx, int cz) {
PS.get().getPlotManager(world.getName());
int sx = (short) ((this.X - this.plotworld.ROAD_OFFSET_X) % this.size);
int sz = (short) ((this.Z - this.plotworld.ROAD_OFFSET_Z) % this.size);
if (sx < 0) {
sx += this.size;
}
if (sz < 0) {
sz += this.size;
}
if (requiredRegion != null) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
if (contains(requiredRegion, x, z)) {
if (this.doFilling) {
for (short y = 1; y < this.plotheight; y++) {
setBlock(x, y, z, this.filling);
}
}
if (this.doFloor) {
setBlock(x, (short) this.plotheight, z, this.plotfloors);
}
if (this.plotworld.PLOT_SCHEMATIC) {
final int absX = ((sx + x) % this.size);
final int absZ = ((sz + z) % this.size);
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Byte> blocks = this.plotworld.G_SCH_DATA.get(loc);
if (blocks != null) {
for (final short y : blocks.keySet()) {
setBlockAbs(x, (short) (this.plotheight + y), z, blocks.get(y));
}
}
if (this.plotworld.G_SCH_STATE != null) {
HashSet<PlotItem> states = this.plotworld.G_SCH_STATE.get(loc);
if (states != null) {
for (PlotItem items : states) {
BlockManager.manager.addItems(this.plotworld.worldname, items);
}
}
}
}
}
}
}
return;
}
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
final int absX = ((sx + x) % this.size);
final int absZ = ((sz + z) % this.size);
final boolean gx = absX > this.pathWidthLower;
final boolean gz = absZ > this.pathWidthLower;
final boolean lx = absX < this.pathWidthUpper;
final boolean lz = absZ < this.pathWidthUpper;
// inside plot
if (gx && gz && lx && lz) {
for (short y = 1; y < this.plotheight; y++) {
setBlock(x, y, z, this.filling);
}
setBlock(x, (short) this.plotheight, z, this.plotfloors);
if (this.plotworld.PLOT_SCHEMATIC) {
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Byte> blocks = this.plotworld.G_SCH_DATA.get(loc);
if (blocks != null) {
for (final short y : blocks.keySet()) {
setBlockAbs(x, (short) (this.plotheight + y), z, blocks.get(y));
}
}
if (this.plotworld.G_SCH_STATE != null) {
HashSet<PlotItem> states = this.plotworld.G_SCH_STATE.get(loc);
if (states != null) {
for (PlotItem items : states) {
items.x = this.X + x;
items.z = this.Z + z;
BlockManager.manager.addItems(this.plotworld.worldname, items);
}
}
}
}
} else if (pathsize != 0) {
// wall
if (((absX >= this.pathWidthLower) && (absX <= this.pathWidthUpper) && (absZ >= this.pathWidthLower) && (absZ <= this.pathWidthUpper))) {
for (short y = 1; y <= this.wallheight; y++) {
setBlock(x, y, z, this.wallfilling);
}
if (!this.plotworld.ROAD_SCHEMATIC_ENABLED) {
setBlock(x, this.wallheight + 1, z, this.wall);
}
}
// road
else {
for (short y = 1; y <= this.roadheight; y++) {
setBlock(x, y, z, this.roadblock);
}
}
if (this.plotworld.ROAD_SCHEMATIC_ENABLED) {
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Byte> blocks = this.plotworld.G_SCH_DATA.get(loc);
if (blocks != null) {
for (final short y : blocks.keySet()) {
setBlockAbs(x, (short) (this.roadheight + y), z, blocks.get(y));
}
}
}
}
}
}
}
private void setBlock(final short x, final short y, final short z, final byte[] blkids) {
if (blkids.length == 1) {
setBlock(x, y, z, blkids[0]);
} else {
final int i = random(blkids.length);
setBlock(x, y, z, blkids[i]);
}
}
}
package com.plotsquared.bukkit.generator;
import java.util.HashMap;
import java.util.HashSet;
import org.bukkit.World;
import org.bukkit.block.Biome;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.generator.HybridPlotWorld;
import com.intellectualcrafters.plot.object.PlotLoc;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.BlockManager;
/**
*/
public class HybridPop extends BukkitPlotPopulator
{
/*
* Sorry, this isn't well documented at the moment.
* We advise you to take a look at a world generation tutorial for
* information about how a BlockPopulator works.
*/
final short plotsize;
final short pathsize;
final byte wall;
final byte wallfilling;
final byte roadblock;
final int size;
final int roadheight;
final int wallheight;
final int plotheight;
final byte[] plotfloors;
final byte[] filling;
final short pathWidthLower;
final short pathWidthUpper;
private final HybridPlotWorld plotworld;
Biome biome;
private long state;
private boolean doFilling = false;
private boolean doFloor = false;
public HybridPop(final PlotWorld pw)
{
plotworld = (HybridPlotWorld) pw;
// save configuration
plotsize = (short) plotworld.PLOT_WIDTH;
pathsize = (short) plotworld.ROAD_WIDTH;
roadblock = plotworld.ROAD_BLOCK.data;
wallfilling = plotworld.WALL_FILLING.data;
size = pathsize + plotsize;
wall = plotworld.WALL_BLOCK.data;
int count1 = 0;
int count2 = 0;
plotfloors = new byte[plotworld.TOP_BLOCK.length];
for (int i = 0; i < plotworld.TOP_BLOCK.length; i++)
{
count1++;
plotfloors[i] = plotworld.TOP_BLOCK[i].data;
if (plotworld.TOP_BLOCK[i].data != 0)
{
doFloor = true;
}
}
filling = new byte[plotworld.MAIN_BLOCK.length];
for (int i = 0; i < plotworld.MAIN_BLOCK.length; i++)
{
count2++;
filling[i] = plotworld.MAIN_BLOCK[i].data;
if (plotworld.MAIN_BLOCK[i].data != 0)
{
doFilling = true;
}
}
if (((count1 > 0) && doFloor) || ((count2 > 0) && doFilling))
{}
wallheight = plotworld.WALL_HEIGHT;
roadheight = plotworld.ROAD_HEIGHT;
plotheight = plotworld.PLOT_HEIGHT;
if (pathsize == 0)
{
pathWidthLower = (short) -1;
pathWidthUpper = (short) (plotsize + 1);
}
else
{
if ((pathsize % 2) == 0)
{
pathWidthLower = (short) (Math.floor(pathsize / 2) - 1);
}
else
{
pathWidthLower = (short) (Math.floor(pathsize / 2));
}
pathWidthUpper = (short) (pathWidthLower + plotsize + 1);
}
}
public final long nextLong()
{
final long a = state;
state = xorShift64(a);
return a;
}
public final long xorShift64(long a)
{
a ^= (a << 21);
a ^= (a >>> 35);
a ^= (a << 4);
return a;
}
public final int random(final int n)
{
final long result = ((nextLong() >>> 32) * n) >> 32;
return (int) result;
}
@Override
public void populate(final World world, final RegionWrapper requiredRegion, final PseudoRandom random, final int cx, final int cz)
{
PS.get().getPlotManager(world.getName());
int sx = (short) ((X - plotworld.ROAD_OFFSET_X) % size);
int sz = (short) ((Z - plotworld.ROAD_OFFSET_Z) % size);
if (sx < 0)
{
sx += size;
}
if (sz < 0)
{
sz += size;
}
if (requiredRegion != null)
{
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
{
if (contains(requiredRegion, x, z))
{
if (doFilling)
{
for (short y = 1; y < plotheight; y++)
{
setBlock(x, y, z, filling);
}
}
if (doFloor)
{
setBlock(x, (short) plotheight, z, plotfloors);
}
if (plotworld.PLOT_SCHEMATIC)
{
final int absX = ((sx + x) % size);
final int absZ = ((sz + z) % size);
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Byte> blocks = plotworld.G_SCH_DATA.get(loc);
if (blocks != null)
{
for (final short y : blocks.keySet())
{
setBlockAbs(x, (short) (plotheight + y), z, blocks.get(y));
}
}
if (plotworld.G_SCH_STATE != null)
{
final HashSet<PlotItem> states = plotworld.G_SCH_STATE.get(loc);
if (states != null)
{
for (final PlotItem items : states)
{
BlockManager.manager.addItems(plotworld.worldname, items);
}
}
}
}
}
}
}
return;
}
for (short x = 0; x < 16; x++)
{
for (short z = 0; z < 16; z++)
{
final int absX = ((sx + x) % size);
final int absZ = ((sz + z) % size);
final boolean gx = absX > pathWidthLower;
final boolean gz = absZ > pathWidthLower;
final boolean lx = absX < pathWidthUpper;
final boolean lz = absZ < pathWidthUpper;
// inside plot
if (gx && gz && lx && lz)
{
for (short y = 1; y < plotheight; y++)
{
setBlock(x, y, z, filling);
}
setBlock(x, (short) plotheight, z, plotfloors);
if (plotworld.PLOT_SCHEMATIC)
{
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Byte> blocks = plotworld.G_SCH_DATA.get(loc);
if (blocks != null)
{
for (final short y : blocks.keySet())
{
setBlockAbs(x, (short) (plotheight + y), z, blocks.get(y));
}
}
if (plotworld.G_SCH_STATE != null)
{
final HashSet<PlotItem> states = plotworld.G_SCH_STATE.get(loc);
if (states != null)
{
for (final PlotItem items : states)
{
items.x = X + x;
items.z = Z + z;
BlockManager.manager.addItems(plotworld.worldname, items);
}
}
}
}
}
else if (pathsize != 0)
{
// wall
if (((absX >= pathWidthLower) && (absX <= pathWidthUpper) && (absZ >= pathWidthLower) && (absZ <= pathWidthUpper)))
{
for (short y = 1; y <= wallheight; y++)
{
setBlock(x, y, z, wallfilling);
}
if (!plotworld.ROAD_SCHEMATIC_ENABLED)
{
setBlock(x, wallheight + 1, z, wall);
}
}
// road
else
{
for (short y = 1; y <= roadheight; y++)
{
setBlock(x, y, z, roadblock);
}
}
if (plotworld.ROAD_SCHEMATIC_ENABLED)
{
final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Byte> blocks = plotworld.G_SCH_DATA.get(loc);
if (blocks != null)
{
for (final short y : blocks.keySet())
{
setBlockAbs(x, (short) (roadheight + y), z, blocks.get(y));
}
}
}
}
}
}
}
private void setBlock(final short x, final short y, final short z, final byte[] blkids)
{
if (blkids.length == 1)
{
setBlock(x, y, z, blkids[0]);
}
else
{
final int i = random(blkids.length);
setBlock(x, y, z, blkids[i]);
}
}

View File

@ -36,231 +36,270 @@ import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
public class ChunkListener implements Listener {
public class ChunkListener implements Listener
{
private Chunk lastChunk = null;
final RefClass classChunk = getRefClass("{nms}.Chunk");
final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
final RefMethod methodGetHandleChunk;
final RefField mustSave = classChunk.getField("mustSave");
public ChunkListener() {
public ChunkListener()
{
RefMethod method;
try {
try
{
method = classCraftChunk.getMethod("getHandle");
}
catch (Exception e) {
catch (final Exception e)
{
method = null;
e.printStackTrace();
}
methodGetHandleChunk = method;
if (!Settings.CHUNK_PROCESSOR_GC) {
return;
}
TaskManager.runTaskRepeat(new Runnable() {
if (!Settings.CHUNK_PROCESSOR_GC) { return; }
TaskManager.runTaskRepeat(new Runnable()
{
@Override
public void run() {
int distance = Bukkit.getViewDistance() + 1;
HashMap<String, HashMap<ChunkLoc, Integer>> players = new HashMap<>();
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
PlotPlayer pp = entry.getValue();
Location loc = pp.getLocation();
String world = loc.getWorld();
if (!PS.get().isPlotWorld(world)) {
public void run()
{
final int distance = Bukkit.getViewDistance() + 1;
final HashMap<String, HashMap<ChunkLoc, Integer>> players = new HashMap<>();
for (final Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet())
{
final PlotPlayer pp = entry.getValue();
final Location loc = pp.getLocation();
final String world = loc.getWorld();
if (!PS.get().isPlotWorld(world))
{
continue;
}
HashMap<ChunkLoc, Integer> map = players.get(world);
if (map == null) {
if (map == null)
{
map = new HashMap<>();
players.put(world, map);
}
ChunkLoc origin = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4);
final ChunkLoc origin = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4);
Integer val = map.get(origin);
int check;
if (val != null) {
if (val == distance) {
if (val != null)
{
if (val == distance)
{
continue;
}
check = distance - val;
}
else {
else
{
check = distance;
map.put(origin, distance);
}
for (int x = -distance; x <= distance; x++) {
if (x >= check || -x >= check) {
for (int x = -distance; x <= distance; x++)
{
if ((x >= check) || (-x >= check))
{
continue;
}
for (int z = -distance; z <= distance; z++) {
if (z >= check || -z >= check) {
for (int z = -distance; z <= distance; z++)
{
if ((z >= check) || (-z >= check))
{
continue;
}
int weight = distance - Math.max(Math.abs(x), Math.abs(z));
ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z);
final int weight = distance - Math.max(Math.abs(x), Math.abs(z));
final ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z);
val = map.get(chunk);
if (val == null || val < weight) {
if ((val == null) || (val < weight))
{
map.put(chunk, weight);
}
}
}
}
for (World world : Bukkit.getWorlds()) {
String name = world.getName();
boolean autosave = world.isAutoSave();
if (!PS.get().isPlotWorld(name)) {
for (final World world : Bukkit.getWorlds())
{
final String name = world.getName();
final boolean autosave = world.isAutoSave();
if (!PS.get().isPlotWorld(name))
{
continue;
}
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autosave) {
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autosave)
{
world.setAutoSave(false);
}
HashMap<ChunkLoc, Integer> map = players.get(name);
if (map == null || map.size() == 0) {
final HashMap<ChunkLoc, Integer> map = players.get(name);
if ((map == null) || (map.size() == 0))
{
continue;
}
for (Chunk chunk : world.getLoadedChunks()) {
int x = chunk.getX();
int z = chunk.getZ();
if (!map.containsKey(new ChunkLoc(x, z))) {
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE || !unloadChunk(name, chunk)) {
for (final Chunk chunk : world.getLoadedChunks())
{
final int x = chunk.getX();
final int z = chunk.getZ();
if (!map.containsKey(new ChunkLoc(x, z)))
{
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE || !unloadChunk(name, chunk))
{
chunk.unload(true, false);
}
}
}
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autosave) {
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autosave)
{
world.setAutoSave(true);
}
}
}
}, 300);
}
public boolean unloadChunk(String world, Chunk chunk) {
int X = chunk.getX();
int Z = chunk.getZ();
int x = X << 4;
int z = Z << 4;
int x2 = x + 15;
int z2 = z + 15;
public boolean unloadChunk(final String world, final Chunk chunk)
{
final int X = chunk.getX();
final int Z = chunk.getZ();
final int x = X << 4;
final int z = Z << 4;
final int x2 = x + 15;
final int z2 = z + 15;
Plot plot;
plot = MainUtil.getPlot(new Location(world, x, 1, z));
if (plot != null && plot.owner != null) return false;
if ((plot != null) && (plot.owner != null)) { return false; }
plot = MainUtil.getPlot(new Location(world, x2, 1, z2));
if (plot != null && plot.owner != null) return false;
if ((plot != null) && (plot.owner != null)) { return false; }
plot = MainUtil.getPlot(new Location(world, x2, 1, z));
if (plot != null && plot.owner != null) return false;
if ((plot != null) && (plot.owner != null)) { return false; }
plot = MainUtil.getPlot(new Location(world, x, 1, z2));
if (plot != null && plot.owner != null) return false;
if ((plot != null) && (plot.owner != null)) { return false; }
plot = MainUtil.getPlot(new Location(world, x + 7, 1, z + 7));
if (plot != null && plot.owner != null) return false;
Object c = methodGetHandleChunk.of(chunk).call();
if ((plot != null) && (plot.owner != null)) { return false; }
final Object c = methodGetHandleChunk.of(chunk).call();
mustSave.of(c).set(false);
chunk.unload(false, false);
return true;
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
if (Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE) {
Chunk chunk = event.getChunk();
String world = chunk.getWorld().getName();
if (PS.get().isPlotWorld(world)) {
if (unloadChunk(world, chunk)) {
return;
}
public void onChunkUnload(final ChunkUnloadEvent event)
{
if (Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE)
{
final Chunk chunk = event.getChunk();
final String world = chunk.getWorld().getName();
if (PS.get().isPlotWorld(world))
{
if (unloadChunk(world, chunk)) { return; }
}
}
if (processChunk(event.getChunk(), true)) {
if (processChunk(event.getChunk(), true))
{
event.setCancelled(true);
}
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
public void onChunkLoad(final ChunkLoadEvent event)
{
processChunk(event.getChunk(), false);
}
@EventHandler(priority=EventPriority.LOWEST)
public void onItemSpawn(ItemSpawnEvent event) {
Item entity = event.getEntity();
Chunk chunk = entity.getLocation().getChunk();
if (chunk == lastChunk) {
@EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawn(final ItemSpawnEvent event)
{
final Item entity = event.getEntity();
final Chunk chunk = entity.getLocation().getChunk();
if (chunk == lastChunk)
{
event.getEntity().remove();
event.setCancelled(true);
return;
}
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) {
return;
}
Entity[] entities = chunk.getEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) { return; }
final Entity[] entities = chunk.getEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES)
{
event.getEntity().remove();
event.setCancelled(true);
lastChunk = chunk;
}
else {
lastChunk = null;
}
}
@EventHandler(priority=EventPriority.HIGHEST, ignoreCancelled=true)
public void onBlockPhysics(BlockPhysicsEvent event) {
if (Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS) {
event.setCancelled(true);
}
}
@EventHandler(priority=EventPriority.LOWEST)
public void onEntitySpawn(CreatureSpawnEvent event) {
LivingEntity entity = event.getEntity();
Chunk chunk = entity.getLocation().getChunk();
if (chunk == lastChunk) {
event.getEntity().remove();
event.setCancelled(true);
return;
}
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) {
return;
}
Entity[] entities = chunk.getEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
event.getEntity().remove();
event.setCancelled(true);
lastChunk = chunk;
}
else {
else
{
lastChunk = null;
}
}
public void cleanChunk(final Chunk chunk) {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPhysics(final BlockPhysicsEvent event)
{
if (Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS)
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntitySpawn(final CreatureSpawnEvent event)
{
final LivingEntity entity = event.getEntity();
final Chunk chunk = entity.getLocation().getChunk();
if (chunk == lastChunk)
{
event.getEntity().remove();
event.setCancelled(true);
return;
}
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) { return; }
final Entity[] entities = chunk.getEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES)
{
event.getEntity().remove();
event.setCancelled(true);
lastChunk = chunk;
}
else
{
lastChunk = null;
}
}
public void cleanChunk(final Chunk chunk)
{
TaskManager.index.incrementAndGet();
final Integer currentIndex = TaskManager.index.get();
final Integer task = TaskManager.runTaskRepeat(new Runnable() {
final Integer task = TaskManager.runTaskRepeat(new Runnable()
{
@Override
public void run() {
if (!chunk.isLoaded()) {
public void run()
{
if (!chunk.isLoaded())
{
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PS.debug("[PlotSquared] &aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
BlockState[] tiles = chunk.getTileEntities();
if (tiles.length == 0) {
final BlockState[] tiles = chunk.getTileEntities();
if (tiles.length == 0)
{
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PS.debug("[PlotSquared] &aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
long start = System.currentTimeMillis();
final long start = System.currentTimeMillis();
int i = 0;
while (System.currentTimeMillis() - start < 250) {
if (i >= tiles.length) {
while ((System.currentTimeMillis() - start) < 250)
{
if (i >= tiles.length)
{
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PS.debug("[PlotSquared] &aSuccessfully processed and unloaded chunk!");
@ -274,28 +313,33 @@ public class ChunkListener implements Listener {
}, 5);
TaskManager.tasks.put(currentIndex, task);
}
public boolean processChunk(Chunk chunk, boolean unload) {
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) {
return false;
}
Entity[] entities = chunk.getEntities();
BlockState[] tiles = chunk.getTileEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
for (Entity ent : entities) {
if (!(ent instanceof Player)) {
public boolean processChunk(final Chunk chunk, final boolean unload)
{
if (!PS.get().isPlotWorld(chunk.getWorld().getName())) { return false; }
final Entity[] entities = chunk.getEntities();
final BlockState[] tiles = chunk.getTileEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES)
{
for (final Entity ent : entities)
{
if (!(ent instanceof Player))
{
ent.remove();
}
}
PS.debug("[PlotSquared] &a detected unsafe chunk and processed: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
}
if (tiles.length > Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES) {
if (unload) {
if (tiles.length > Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES)
{
if (unload)
{
PS.debug("[PlotSquared] &c detected unsafe chunk: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
cleanChunk(chunk);
return true;
}
for (BlockState tile : tiles) {
for (final BlockState tile : tiles)
{
tile.getBlock().setType(Material.AIR, false);
}
}

View File

@ -1,125 +1,143 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.listeners;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.util.Vector;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.events.PlayerEnterPlotEvent;
import com.plotsquared.bukkit.util.BukkitPlayerFunctions;
import com.plotsquared.bukkit.util.BukkitUtil;
/**
* @author Citymonstret
*/
public class ForceFieldListener implements Listener {
private Set<Player> getNearbyPlayers(final Player player, final Plot plot) {
final Set<Player> players = new HashSet<>();
Player oPlayer;
for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d)) {
if (!(entity instanceof Player) || ((oPlayer = (Player) entity) == null) || !BukkitPlayerFunctions.isInPlot(oPlayer) || !BukkitPlayerFunctions.getCurrentPlot(oPlayer).equals(plot)) {
continue;
}
final UUID uuid = UUIDHandler.getUUID(BukkitUtil.getPlayer(oPlayer));
if (!plot.isAdded(uuid)) {
players.add(oPlayer);
}
}
return players;
}
private Player hasNearbyPermitted(final Player player, final Plot plot) {
Player oPlayer;
for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d)) {
if (!(entity instanceof Player) || ((oPlayer = (Player) entity) == null) || !BukkitPlayerFunctions.isInPlot(oPlayer) || !BukkitPlayerFunctions.getCurrentPlot(oPlayer).equals(plot)) {
continue;
}
final UUID uuid = UUIDHandler.getUUID(BukkitUtil.getPlayer(oPlayer));
if (plot.isAdded(uuid)) {
return oPlayer;
}
}
return null;
}
public Vector calculateVelocity(final Player p, final Player e) {
final org.bukkit.Location playerLocation = p.getLocation();
final org.bukkit.Location oPlayerLocation = e.getLocation();
final double playerX = playerLocation.getX(), playerY = playerLocation.getY(), playerZ = playerLocation.getZ(), oPlayerX = oPlayerLocation.getX(), oPlayerY = oPlayerLocation.getY(), oPlayerZ = oPlayerLocation.getZ();
double x = 0d, y = 0d, z = 0d;
if (playerX < oPlayerX) {
x = 1.0d;
} else if (playerX > oPlayerX) {
x = -1.0d;
}
if (playerY < oPlayerY) {
y = 0.5d;
} else if (playerY > oPlayerY) {
y = -0.5d;
}
if (playerZ < oPlayerZ) {
z = 1.0d;
} else if (playerZ > oPlayerZ) {
z = -1.0d;
}
return new Vector(x, y, z);
}
@EventHandler
public void onPlotEntry(final PlayerEnterPlotEvent event) {
final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player);
final Location loc = pp.getLocation();
final Plot plot = event.getPlot();
if (plot == null) {
return;
}
if ((FlagManager.getPlotFlag(plot, "forcefield") != null) && FlagManager.getPlotFlag(plot, "forcefield").getValue().equals("true")) {
if (!FlagManager.isBooleanFlag(plot, "forcefield", false)) {
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid)) {
final Set<Player> players = getNearbyPlayers(player, plot);
for (final Player oPlayer : players) {
oPlayer.setVelocity(calculateVelocity(player, oPlayer));
}
} else {
final Player oPlayer = hasNearbyPermitted(player, plot);
if (oPlayer == null) {
return;
}
player.setVelocity(calculateVelocity(oPlayer, player));
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.listeners;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.util.Vector;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.events.PlayerEnterPlotEvent;
import com.plotsquared.bukkit.util.BukkitPlayerFunctions;
import com.plotsquared.bukkit.util.BukkitUtil;
/**
*/
public class ForceFieldListener implements Listener
{
private Set<Player> getNearbyPlayers(final Player player, final Plot plot)
{
final Set<Player> players = new HashSet<>();
Player oPlayer;
for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d))
{
if (!(entity instanceof Player) || ((oPlayer = (Player) entity) == null) || !BukkitPlayerFunctions.isInPlot(oPlayer) || !BukkitPlayerFunctions.getCurrentPlot(oPlayer).equals(plot))
{
continue;
}
final UUID uuid = UUIDHandler.getUUID(BukkitUtil.getPlayer(oPlayer));
if (!plot.isAdded(uuid))
{
players.add(oPlayer);
}
}
return players;
}
private Player hasNearbyPermitted(final Player player, final Plot plot)
{
Player oPlayer;
for (final Entity entity : player.getNearbyEntities(5d, 5d, 5d))
{
if (!(entity instanceof Player) || ((oPlayer = (Player) entity) == null) || !BukkitPlayerFunctions.isInPlot(oPlayer) || !BukkitPlayerFunctions.getCurrentPlot(oPlayer).equals(plot))
{
continue;
}
final UUID uuid = UUIDHandler.getUUID(BukkitUtil.getPlayer(oPlayer));
if (plot.isAdded(uuid)) { return oPlayer; }
}
return null;
}
public Vector calculateVelocity(final Player p, final Player e)
{
final org.bukkit.Location playerLocation = p.getLocation();
final org.bukkit.Location oPlayerLocation = e.getLocation();
final double playerX = playerLocation.getX(), playerY = playerLocation.getY(), playerZ = playerLocation.getZ(), oPlayerX = oPlayerLocation.getX(), oPlayerY = oPlayerLocation.getY(), oPlayerZ = oPlayerLocation
.getZ();
double x = 0d, y = 0d, z = 0d;
if (playerX < oPlayerX)
{
x = 1.0d;
}
else if (playerX > oPlayerX)
{
x = -1.0d;
}
if (playerY < oPlayerY)
{
y = 0.5d;
}
else if (playerY > oPlayerY)
{
y = -0.5d;
}
if (playerZ < oPlayerZ)
{
z = 1.0d;
}
else if (playerZ > oPlayerZ)
{
z = -1.0d;
}
return new Vector(x, y, z);
}
@EventHandler
public void onPlotEntry(final PlayerEnterPlotEvent event)
{
final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player);
pp.getLocation();
final Plot plot = event.getPlot();
if (plot == null) { return; }
if ((FlagManager.getPlotFlag(plot, "forcefield") != null) && FlagManager.getPlotFlag(plot, "forcefield").getValue().equals("true"))
{
if (!FlagManager.isBooleanFlag(plot, "forcefield", false))
{
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid))
{
final Set<Player> players = getNearbyPlayers(player, plot);
for (final Player oPlayer : players)
{
oPlayer.setVelocity(calculateVelocity(player, oPlayer));
}
}
else
{
final Player oPlayer = hasNearbyPermitted(player, plot);
if (oPlayer == null) { return; }
player.setVelocity(calculateVelocity(oPlayer, player));
}
}
}
}

View File

@ -1,16 +1,17 @@
package com.plotsquared.bukkit.listeners;
public enum PlayerBlockEventType {
public enum PlayerBlockEventType
{
// Non interactive
EAT,
READ,
// Right click with monster egg
SPAWN_MOB,
// Dragon egg
TELEPORT_OBJECT,
// armor stands
PLACE_MISC,
// blocks
@ -27,7 +28,7 @@ public enum PlayerBlockEventType {
// paintings / item frames
BREAK_HANGING,
BREAK_VEHICLE,
// armor stands
INTERACT_MISC,
// blocks
@ -36,7 +37,7 @@ public enum PlayerBlockEventType {
INTERACT_VEHICLE,
// item frame / painting
INTERACT_HANGING,
// Pressure plate, tripwire etc
TRIGGER_PHYSICAL,
}

View File

@ -30,85 +30,87 @@ import com.intellectualcrafters.plot.util.Permissions;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlotListener;
public class PlayerEvents_1_8 extends PlotListener implements Listener {
public class PlayerEvents_1_8 extends PlotListener implements Listener
{
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
if (!event.isLeftClick() || event.getAction() != InventoryAction.PLACE_ALL || event.isShiftClick()) {
return;
}
HumanEntity entity = event.getWhoClicked();
if (!(entity instanceof Player) || !PS.get().isPlotWorld(entity.getWorld().getName())) {
return;
}
Player player = (Player) entity;
PlayerInventory inv = player.getInventory();
int slot = inv.getHeldItemSlot();
if (slot != event.getSlot() || slot > 8 || !event.getEventName().equals("InventoryCreativeEvent")) {
return;
}
ItemStack current = inv.getItemInHand();
ItemStack newItem = event.getCursor();
ItemMeta newMeta = newItem.getItemMeta();
ItemMeta oldMeta = newItem.getItemMeta();
public void onInventoryClick(final InventoryClickEvent event)
{
if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event.isShiftClick()) { return; }
final HumanEntity entity = event.getWhoClicked();
if (!(entity instanceof Player) || !PS.get().isPlotWorld(entity.getWorld().getName())) { return; }
final Player player = (Player) entity;
final PlayerInventory inv = player.getInventory();
final int slot = inv.getHeldItemSlot();
if ((slot != event.getSlot()) || (slot > 8) || !event.getEventName().equals("InventoryCreativeEvent")) { return; }
final ItemStack current = inv.getItemInHand();
final ItemStack newItem = event.getCursor();
final ItemMeta newMeta = newItem.getItemMeta();
final ItemMeta oldMeta = newItem.getItemMeta();
String newLore = "";
if (newMeta != null) {
List<String> lore = newMeta.getLore();
if (lore != null) {
if (newMeta != null)
{
final List<String> lore = newMeta.getLore();
if (lore != null)
{
newLore = lore.toString();
}
}
String oldLore = "";
if (oldMeta != null) {
List<String> lore = oldMeta.getLore();
if (lore != null) {
if (oldMeta != null)
{
final List<String> lore = oldMeta.getLore();
if (lore != null)
{
oldLore = lore.toString();
}
}
if (!newLore.equals("[(+NBT)]") || (current.equals(newItem) && newLore.equals(oldLore))) {
return;
}
HashSet<Byte> blocks = null;
Block block = player.getTargetBlock(blocks, 7);
BlockState state = block.getState();
if (state == null) {
return;
}
if (state.getType() != newItem.getType()) {
return;
}
if (!newLore.equals("[(+NBT)]") || (current.equals(newItem) && newLore.equals(oldLore))) { return; }
final HashSet<Byte> blocks = null;
final Block block = player.getTargetBlock(blocks, 7);
final BlockState state = block.getState();
if (state == null) { return; }
if (state.getType() != newItem.getType()) { return; }
final Location l = BukkitUtil.getLocation(state.getLocation());
Plot plot = MainUtil.getPlot(l);
PlotPlayer pp = BukkitUtil.getPlayer(player);
final Plot plot = MainUtil.getPlot(l);
final PlotPlayer pp = BukkitUtil.getPlayer(player);
boolean cancelled = false;
if (plot == null) {
if (!MainUtil.isPlotArea(l)) {
return;
}
if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) {
if (plot == null)
{
if (!MainUtil.isPlotArea(l)) { return; }
if (!Permissions.hasPermission(pp, "plots.admin.interact.road"))
{
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.road");
cancelled = true;
}
}
else {
if (!plot.hasOwner()) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) {
else
{
if (!plot.hasOwner())
{
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned"))
{
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned");
cancelled = true;
}
}
else {
else
{
final UUID uuid = pp.getUUID();
if (!plot.isAdded(uuid)) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) {
if (!plot.isAdded(uuid))
{
if (!Permissions.hasPermission(pp, "plots.admin.interact.other"))
{
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other");
cancelled = true;
}
}
}
}
if (cancelled) {
if (current.getTypeId() == newItem.getTypeId() && current.getDurability() == newItem.getDurability()) {
if (cancelled)
{
if ((current.getTypeId() == newItem.getTypeId()) && (current.getDurability() == newItem.getDurability()))
{
event.setCursor(new ItemStack(newItem.getTypeId(), newItem.getAmount(), newItem.getDurability()));
event.setCancelled(true);
return;
@ -116,40 +118,43 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener {
event.setCursor(new ItemStack(newItem.getTypeId(), newItem.getAmount(), newItem.getDurability()));
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInteract(final PlayerInteractAtEntityEvent e) {
Entity entity = e.getRightClicked();
if (!(entity instanceof ArmorStand)) {
return;
}
public void onInteract(final PlayerInteractAtEntityEvent e)
{
final Entity entity = e.getRightClicked();
if (!(entity instanceof ArmorStand)) { return; }
final Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation());
String world = l.getWorld();
if (!PS.get().isPlotWorld(world)) {
return;
}
Plot plot = MainUtil.getPlot(l);
PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer());
if (plot == null) {
if (!MainUtil.isPlotArea(l)) {
return;
}
if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) {
final String world = l.getWorld();
if (!PS.get().isPlotWorld(world)) { return; }
final Plot plot = MainUtil.getPlot(l);
final PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer());
if (plot == null)
{
if (!MainUtil.isPlotArea(l)) { return; }
if (!Permissions.hasPermission(pp, "plots.admin.interact.road"))
{
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.road");
e.setCancelled(true);
}
}
else {
if (!plot.hasOwner()) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) {
else
{
if (!plot.hasOwner())
{
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned"))
{
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned");
e.setCancelled(true);
}
}
else {
else
{
final UUID uuid = pp.getUUID();
if (!plot.isAdded(uuid)) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) {
if (!plot.isAdded(uuid))
{
if (!Permissions.hasPermission(pp, "plots.admin.interact.other"))
{
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other");
e.setCancelled(true);
}

View File

@ -15,35 +15,44 @@ import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.bukkit.util.BukkitUtil;
public class PlayerEvents_1_8_3 implements Listener {
public class PlayerEvents_1_8_3 implements Listener
{
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBigBoom(final BlockExplodeEvent event) {
Block block = event.getBlock();
Location loc = BukkitUtil.getLocation(block.getLocation());
public void onBigBoom(final BlockExplodeEvent event)
{
final Block block = event.getBlock();
final Location loc = BukkitUtil.getLocation(block.getLocation());
final String world = loc.getWorld();
if (!PS.get().isPlotWorld(world)) {
return;
}
if (!PS.get().isPlotWorld(world)) { return; }
final Plot plot = MainUtil.getPlot(loc);
if ((plot != null) && plot.hasOwner()) {
if (FlagManager.isPlotFlagTrue(plot, "explosion")) {
if ((plot != null) && plot.hasOwner())
{
if (FlagManager.isPlotFlagTrue(plot, "explosion"))
{
final Iterator<Block> iter = event.blockList().iterator();
while (iter.hasNext()) {
while (iter.hasNext())
{
final Block b = iter.next();
if (!plot.equals(MainUtil.getPlot(BukkitUtil.getLocation(b.getLocation())))) {
if (!plot.equals(MainUtil.getPlot(BukkitUtil.getLocation(b.getLocation()))))
{
iter.remove();
}
}
return;
}
}
if (MainUtil.isPlotArea(loc)) {
if (MainUtil.isPlotArea(loc))
{
event.setCancelled(true);
} else {
}
else
{
final Iterator<Block> iter = event.blockList().iterator();
while (iter.hasNext()) {
while (iter.hasNext())
{
iter.next();
if (MainUtil.isPlotArea(loc)) {
if (MainUtil.isPlotArea(loc))
{
iter.remove();
}
}

View File

@ -1,254 +1,267 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.listeners;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotHandler;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.events.PlayerEnterPlotEvent;
import com.plotsquared.bukkit.events.PlayerLeavePlotEvent;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlotListener;
/**
* Created 2014-10-30 for PlotSquared
*
* @author Citymonstret
*/
@SuppressWarnings({ "deprecation"})
public class PlotPlusListener extends PlotListener implements Listener {
private final static HashMap<String, Interval> feedRunnable = new HashMap<>();
private final static HashMap<String, Interval> healRunnable = new HashMap<>();
public static void startRunnable(final JavaPlugin plugin) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
for (Iterator<Entry<String, Interval>> iter = healRunnable.entrySet().iterator(); iter.hasNext();){
Entry<String, Interval> entry = iter.next();
final Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
final Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iter.remove();
continue;
}
final double level = player.getHealth();
if (level != value.max) {
player.setHealth(Math.min(level + value.amount, value.max));
}
}
}
for (Iterator<Entry<String, Interval>> iter = feedRunnable.entrySet().iterator(); iter.hasNext();){
Entry<String, Interval> entry = iter.next();
final Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
final Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iter.remove();
continue;
}
final int level = player.getFoodLevel();
if (level != value.max) {
player.setFoodLevel(Math.min(level + value.amount, value.max));
}
}
}
}
}, 0l, 20l);
}
@EventHandler(priority = EventPriority.HIGH)
public void onInteract(final BlockDamageEvent event) {
final Player player = event.getPlayer();
if (player.getGameMode() != GameMode.SURVIVAL) {
return;
}
final Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(player));
if (plot == null) {
return;
}
if (FlagManager.isBooleanFlag(plot, "instabreak", false)) {
event.getBlock().breakNaturally();
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onDamage(final EntityDamageEvent event) {
if (event.getEntityType() != EntityType.PLAYER) {
return;
}
final Player player = (Player) event.getEntity();
final Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(player));
if (plot == null) {
return;
}
if (FlagManager.isBooleanFlag(plot, "invincible", false)) {
event.setCancelled(true);
}
}
@EventHandler
public void onItemPickup(final PlayerPickupItemEvent event) {
final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player);
final Plot plot = MainUtil.getPlot(pp.getLocation());
if (plot == null) {
return;
}
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "drop-protection", false)) {
event.setCancelled(true);
}
}
@EventHandler
public void onItemDrop(final PlayerDropItemEvent event) {
final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player);
final Plot plot = MainUtil.getPlot(pp.getLocation());
if (plot == null) {
return;
}
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "item-drop", false)) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlotEnter(final PlayerEnterPlotEvent event) {
Player player = event.getPlayer();
final Plot plot = event.getPlot();
Flag feed = FlagManager.getPlotFlag(plot, "feed");
if (feed != null) {
Integer[] value = (Integer[]) feed.getValue();
feedRunnable.put(player.getName(), new Interval(value[0], value[1], 20));
}
Flag heal = FlagManager.getPlotFlag(plot, "heal");
if (heal != null) {
Integer[] value = (Integer[]) heal.getValue();
healRunnable.put(player.getName(), new Interval(value[0], value[1], 20));
}
}
@EventHandler
public void onPlayerQuit(final PlayerQuitEvent event) {
final Player player = event.getPlayer();
final String name = player.getName();
feedRunnable.remove(name);
healRunnable.remove(name);
}
@EventHandler
public void onPlotLeave(final PlayerLeavePlotEvent event) {
final Player leaver = event.getPlayer();
final Plot plot = event.getPlot();
if (!plot.hasOwner()) {
return;
}
final PlotPlayer pl = BukkitUtil.getPlayer(leaver);
String name = leaver.getName();
feedRunnable.remove(name);
healRunnable.remove(name);
}
public static class Interval {
public final int interval;
public final int amount;
public final int max;
public int count = 0;
public Interval(final int interval, final int amount, final int max) {
this.interval = interval;
this.amount = amount;
this.max = max;
}
}
/**
* Record Meta Class
*
* @author Citymonstret
*/
public static class RecordMeta {
public final static List<RecordMeta> metaList = new ArrayList<>();
static {
for (int x = 3; x < 12; x++) {
metaList.add(new RecordMeta(x + "", Material.valueOf("RECORD_" + x)));
}
}
private final String name;
private final Material material;
public RecordMeta(final String name, final Material material) {
this.name = name;
this.material = material;
}
@Override
public String toString() {
return this.name;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
public Material getMaterial() {
return this.material;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.listeners;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.bukkit.events.PlayerEnterPlotEvent;
import com.plotsquared.bukkit.events.PlayerLeavePlotEvent;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlotListener;
/**
* Created 2014-10-30 for PlotSquared
*
*/
@SuppressWarnings({ "deprecation" })
public class PlotPlusListener extends PlotListener implements Listener
{
private final static HashMap<String, Interval> feedRunnable = new HashMap<>();
private final static HashMap<String, Interval> healRunnable = new HashMap<>();
public static void startRunnable(final JavaPlugin plugin)
{
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable()
{
@Override
public void run()
{
for (final Iterator<Entry<String, Interval>> iter = healRunnable.entrySet().iterator(); iter.hasNext();)
{
final Entry<String, Interval> entry = iter.next();
final Interval value = entry.getValue();
++value.count;
if (value.count == value.interval)
{
value.count = 0;
final Player player = Bukkit.getPlayer(entry.getKey());
if (player == null)
{
iter.remove();
continue;
}
final double level = player.getHealth();
if (level != value.max)
{
player.setHealth(Math.min(level + value.amount, value.max));
}
}
}
for (final Iterator<Entry<String, Interval>> iter = feedRunnable.entrySet().iterator(); iter.hasNext();)
{
final Entry<String, Interval> entry = iter.next();
final Interval value = entry.getValue();
++value.count;
if (value.count == value.interval)
{
value.count = 0;
final Player player = Bukkit.getPlayer(entry.getKey());
if (player == null)
{
iter.remove();
continue;
}
final int level = player.getFoodLevel();
if (level != value.max)
{
player.setFoodLevel(Math.min(level + value.amount, value.max));
}
}
}
}
}, 0l, 20l);
}
@EventHandler(priority = EventPriority.HIGH)
public void onInteract(final BlockDamageEvent event)
{
final Player player = event.getPlayer();
if (player.getGameMode() != GameMode.SURVIVAL) { return; }
final Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(player));
if (plot == null) { return; }
if (FlagManager.isBooleanFlag(plot, "instabreak", false))
{
event.getBlock().breakNaturally();
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onDamage(final EntityDamageEvent event)
{
if (event.getEntityType() != EntityType.PLAYER) { return; }
final Player player = (Player) event.getEntity();
final Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(player));
if (plot == null) { return; }
if (FlagManager.isBooleanFlag(plot, "invincible", false))
{
event.setCancelled(true);
}
}
@EventHandler
public void onItemPickup(final PlayerPickupItemEvent event)
{
final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player);
final Plot plot = MainUtil.getPlot(pp.getLocation());
if (plot == null) { return; }
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "drop-protection", false))
{
event.setCancelled(true);
}
}
@EventHandler
public void onItemDrop(final PlayerDropItemEvent event)
{
final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player);
final Plot plot = MainUtil.getPlot(pp.getLocation());
if (plot == null) { return; }
final UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "item-drop", false))
{
event.setCancelled(true);
}
}
@EventHandler
public void onPlotEnter(final PlayerEnterPlotEvent event)
{
final Player player = event.getPlayer();
final Plot plot = event.getPlot();
final Flag feed = FlagManager.getPlotFlag(plot, "feed");
if (feed != null)
{
final Integer[] value = (Integer[]) feed.getValue();
feedRunnable.put(player.getName(), new Interval(value[0], value[1], 20));
}
final Flag heal = FlagManager.getPlotFlag(plot, "heal");
if (heal != null)
{
final Integer[] value = (Integer[]) heal.getValue();
healRunnable.put(player.getName(), new Interval(value[0], value[1], 20));
}
}
@EventHandler
public void onPlayerQuit(final PlayerQuitEvent event)
{
final Player player = event.getPlayer();
final String name = player.getName();
feedRunnable.remove(name);
healRunnable.remove(name);
}
@EventHandler
public void onPlotLeave(final PlayerLeavePlotEvent event)
{
final Player leaver = event.getPlayer();
final Plot plot = event.getPlot();
if (!plot.hasOwner()) { return; }
BukkitUtil.getPlayer(leaver);
final String name = leaver.getName();
feedRunnable.remove(name);
healRunnable.remove(name);
}
public static class Interval
{
public final int interval;
public final int amount;
public final int max;
public int count = 0;
public Interval(final int interval, final int amount, final int max)
{
this.interval = interval;
this.amount = amount;
this.max = max;
}
}
/**
* Record Meta Class
*
*/
public static class RecordMeta
{
public final static List<RecordMeta> metaList = new ArrayList<>();
static
{
for (int x = 3; x < 12; x++)
{
metaList.add(new RecordMeta(x + "", Material.valueOf("RECORD_" + x)));
}
}
private final String name;
private final Material material;
public RecordMeta(final String name, final Material material)
{
this.name = name;
this.material = material;
}
@Override
public String toString()
{
return name;
}
@Override
public int hashCode()
{
return name.hashCode();
}
public Material getMaterial()
{
return material;
}

View File

@ -19,104 +19,112 @@ import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.bukkit.util.BukkitUtil;
public class TNTListener implements Listener {
public class TNTListener implements Listener
{
private double lastRadius;
@EventHandler
public void onPrime(ExplosionPrimeEvent event) {
public void onPrime(final ExplosionPrimeEvent event)
{
lastRadius = event.getRadius() + 1;
}
@EventHandler
public void onExplode(EntityExplodeEvent event) {
Entity entity = event.getEntity();
if (entity == null) {
return;
}
World world = entity.getWorld();
String worldname = world.getName();
if (!PS.get().isPlotWorld(worldname)) {
return;
}
Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(entity));
if (plot == null) {
return;
}
if (!FlagManager.isPlotFlagTrue(plot, "explosion")) {
return;
}
Location bot = MainUtil.getPlotBottomLoc(plot.world, plot.id);
Location top = MainUtil.getPlotTopLoc(plot.world, plot.id);
List<Entity> nearby = entity.getNearbyEntities(lastRadius, lastRadius, lastRadius);
for (Entity near : nearby) {
if (near instanceof TNTPrimed || near.getType() == EntityType.MINECART_TNT) {
Vector velocity = near.getVelocity();
Location loc = BukkitUtil.getLocation(near);
Plot nearPlot = MainUtil.getPlot(loc);
if (!plot.equals(nearPlot)) {
public void onExplode(final EntityExplodeEvent event)
{
final Entity entity = event.getEntity();
if (entity == null) { return; }
final World world = entity.getWorld();
final String worldname = world.getName();
if (!PS.get().isPlotWorld(worldname)) { return; }
final Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(entity));
if (plot == null) { return; }
if (!FlagManager.isPlotFlagTrue(plot, "explosion")) { return; }
final Location bot = MainUtil.getPlotBottomLoc(plot.world, plot.id);
final Location top = MainUtil.getPlotTopLoc(plot.world, plot.id);
final List<Entity> nearby = entity.getNearbyEntities(lastRadius, lastRadius, lastRadius);
for (final Entity near : nearby)
{
if ((near instanceof TNTPrimed) || (near.getType() == EntityType.MINECART_TNT))
{
final Vector velocity = near.getVelocity();
final Location loc = BukkitUtil.getLocation(near);
final Plot nearPlot = MainUtil.getPlot(loc);
if (!plot.equals(nearPlot))
{
near.setVelocity(new Vector(0, 0, 0));
continue;
}
double vx = velocity.getX();
double vy = velocity.getX();
double vz = velocity.getX();
final double vx = velocity.getX();
velocity.getX();
final double vz = velocity.getX();
int dx;
int dz;
if (vx > 0) {
if (vx > 0)
{
dx = top.getX() - loc.getX();
}
else {
else
{
dx = bot.getX() - loc.getX();
}
if (vz > 0) {
if (vz > 0)
{
dz = top.getZ() - loc.getZ();
}
else {
else
{
dz = bot.getZ() - loc.getZ();
}
double s1 = dx / vx;
double s2 = dz / vz;
Vector v1 = new Vector(dx, 0, vz * s1);
Vector v2 = new Vector(vx * s2, 0, dz);
final double s1 = dx / vx;
final double s2 = dz / vz;
final Vector v1 = new Vector(dx, 0, vz * s1);
final Vector v2 = new Vector(vx * s2, 0, dz);
Vector shortest;
if (v1.length() < v2.length()) {
if (v1.length() < v2.length())
{
shortest = v1;
}
else {
else
{
shortest = v2;
}
Location landing = loc.add(shortest.getBlockX() + 1, 0, shortest.getBlockZ() + 1);
int ty = MainUtil.getHeighestBlock(worldname, landing.getX(), landing.getZ());
int diff = ty - loc.getY();
double calcDiff = getY(velocity, Math.sqrt(shortest.getBlockX() * shortest.getBlockX() + shortest.getBlockZ() * shortest.getBlockZ()));
if (calcDiff > diff) {
final Location landing = loc.add(shortest.getBlockX() + 1, 0, shortest.getBlockZ() + 1);
final int ty = MainUtil.getHeighestBlock(worldname, landing.getX(), landing.getZ());
final int diff = ty - loc.getY();
final double calcDiff = getY(velocity, Math.sqrt((shortest.getBlockX() * shortest.getBlockX()) + (shortest.getBlockZ() * shortest.getBlockZ())));
if (calcDiff > diff)
{
near.setVelocity(new Vector(0, 0, 0));
}
}
}
event.getEntity().setVelocity(new Vector(0, 0, 0));
}
public double getY(Vector velocity, double x) {
double g = 16;
double l1 = velocity.length();
double l2 = Math.sqrt(velocity.getX() * velocity.getX() + velocity.getZ() * velocity.getZ());
double v = l1 * 20;
double theta = Math.acos(l2/l1);
if (velocity.getY() < 0) {
public double getY(final Vector velocity, final double x)
{
final double g = 16;
final double l1 = velocity.length();
final double l2 = Math.sqrt((velocity.getX() * velocity.getX()) + (velocity.getZ() * velocity.getZ()));
final double v = l1 * 20;
double theta = Math.acos(l2 / l1);
if (velocity.getY() < 0)
{
theta = -theta;
}
double cos = Math.cos(theta);
double yDiff = (x * Math.tan(theta)) - ((g * x * x) / (2 * (v * v * cos * cos)));
final double cos = Math.cos(theta);
final double yDiff = (x * Math.tan(theta)) - ((g * x * x) / (2 * (v * v * cos * cos)));
return yDiff;
}
}

View File

@ -11,29 +11,37 @@ import com.intellectualcrafters.plot.PS;
import com.plotsquared.bukkit.generator.BukkitGeneratorWrapper;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
public class WorldEvents implements Listener {
public class WorldEvents implements Listener
{
public static String lastWorld = null;
public static String getName(World world) {
if (lastWorld != null && !lastWorld.equals("CheckingPlotSquaredGenerator")) {
public static String getName(final World world)
{
if ((lastWorld != null) && !lastWorld.equals("CheckingPlotSquaredGenerator"))
{
return lastWorld;
}
else {
else
{
return world.getName();
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public static void onWorldInit(final WorldInitEvent event) {
public static void onWorldInit(final WorldInitEvent event)
{
final World world = event.getWorld();
String name = getName(world);
final String name = getName(world);
final ChunkGenerator gen = world.getGenerator();
if (gen instanceof BukkitPlotGenerator) {
PS.get().loadWorld(name, new BukkitGeneratorWrapper(name, (BukkitPlotGenerator) gen));
if (gen instanceof BukkitPlotGenerator)
{
PS.get().loadWorld(name, new BukkitGeneratorWrapper(name, gen));
}
else {
if (PS.get().config.contains("worlds." + name)) {
else
{
if (PS.get().config.contains("worlds." + name))
{
PS.get().loadWorld(name, new BukkitGeneratorWrapper(name, null));
}
}

View File

@ -3,7 +3,6 @@ package com.plotsquared.bukkit.listeners.worldedit;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ -25,15 +24,14 @@ import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.SetBlockQueue;
import com.plotsquared.bukkit.BukkitMain;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.SetBlockFast;
import com.plotsquared.listener.WEManager;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.selections.Selection;
public class WEListener implements Listener {
public class WEListener implements Listener
{
public final HashSet<String> rad1 = new HashSet<>(Arrays.asList("forestgen", "pumpkins", "drain", "fixwater", "fixlava", "replacenear", "snow", "thaw", "ex", "butcher", "size"));
public final HashSet<String> rad2 = new HashSet<>(Arrays.asList("fill", "fillr", "removenear", "remove"));
public final HashSet<String> rad2_1 = new HashSet<>(Arrays.asList("hcyl", "cyl"));
@ -41,273 +39,356 @@ public class WEListener implements Listener {
public final HashSet<String> rad2_3 = new HashSet<>(Arrays.asList("brush smooth"));
public final HashSet<String> rad3_1 = new HashSet<>(Arrays.asList("brush gravity"));
public final HashSet<String> rad3_2 = new HashSet<>(Arrays.asList("brush sphere", "brush cylinder"));
public final HashSet<String> region = new HashSet<>(Arrays.asList("move", "set", "replace", "overlay", "walls", "outline", "deform", "hollow", "smooth", "naturalize", "paste", "count", "distr", "regen", "copy", "cut", "green", "setbiome"));
public final HashSet<String> region = new HashSet<>(Arrays.asList("move", "set", "replace", "overlay", "walls", "outline", "deform", "hollow", "smooth", "naturalize", "paste", "count", "distr",
"regen", "copy", "cut", "green", "setbiome"));
public final HashSet<String> regionExtend = new HashSet<>(Arrays.asList("stack"));
public final HashSet<String> unregioned = new HashSet<>(Arrays.asList("paste", "redo", "undo", "rotate", "flip", "generate", "schematic", "schem"));
public final HashSet<String> unsafe1 = new HashSet<>(Arrays.asList("cs", ".s", "restore", "snapshot", "delchunks", "listchunks"));
public final HashSet<String> unsafe1 = new HashSet<>(Arrays.asList("cs", ".s", "restore", "snapshot", "delchunks", "listchunks"));
public final HashSet<String> restricted = new HashSet<>(Arrays.asList("up"));
public final HashSet<String> other = new HashSet<>(Arrays.asList("undo", "redo"));
public boolean checkCommand(List<String> list, String cmd) {
for (String identifier : list) {
if (("/" + identifier).equals(cmd) || ("//" + identifier).equals(cmd) || ("/worldedit:/" + identifier).equals(cmd) || ("/worldedit:" + identifier).equals(cmd)) {
return true;
}
public boolean checkCommand(final List<String> list, final String cmd)
{
for (final String identifier : list)
{
if (("/" + identifier).equals(cmd) || ("//" + identifier).equals(cmd) || ("/worldedit:/" + identifier).equals(cmd) || ("/worldedit:" + identifier).equals(cmd)) { return true; }
}
return false;
}
public String reduceCmd(String cmd, boolean single) {
if (cmd.startsWith("/worldedit:/")) {
return cmd.substring(12);
}
if (cmd.startsWith("/worldedit:")) {
return cmd.substring(11);
}
if (cmd.startsWith("//")) {
return cmd.substring(2);
}
if (single && cmd.startsWith("/")) {
return cmd.substring(1);
}
public String reduceCmd(final String cmd, final boolean single)
{
if (cmd.startsWith("/worldedit:/")) { return cmd.substring(12); }
if (cmd.startsWith("/worldedit:")) { return cmd.substring(11); }
if (cmd.startsWith("//")) { return cmd.substring(2); }
if (single && cmd.startsWith("/")) { return cmd.substring(1); }
return cmd;
}
public int getInt(String s) {
try {
public int getInt(final String s)
{
try
{
int max = 0;
String[] split = s.split(",");
for (String rad : split) {
int val = Integer.parseInt(rad);
if (val > max) {
final String[] split = s.split(",");
for (final String rad : split)
{
final int val = Integer.parseInt(rad);
if (val > max)
{
max = val;
}
}
return max;
}
catch (NumberFormatException e) {
catch (final NumberFormatException e)
{
return 0;
}
}
public boolean checkVolume(PlotPlayer player, long volume, long max, Cancellable e) {
if (volume > max) {
public boolean checkVolume(final PlotPlayer player, final long volume, final long max, final Cancellable e)
{
if (volume > max)
{
MainUtil.sendMessage(player, C.WORLDEDIT_VOLUME.s().replaceAll("%current%", volume + "").replaceAll("%max%", max + ""));
e.setCancelled(true);
}
if (Permissions.hasPermission(player, "plots.worldedit.bypass")) {
if (Permissions.hasPermission(player, "plots.worldedit.bypass"))
{
MainUtil.sendMessage(player, C.WORLDEDIT_BYPASS);
}
return true;
}
public boolean checkSelection(Player p, PlotPlayer pp, int modifier, long max, Cancellable e) {
public boolean checkSelection(final Player p, final PlotPlayer pp, final int modifier, final long max, final Cancellable e)
{
final Selection selection = BukkitMain.worldEdit.getSelection(p);
if (selection == null) {
return true;
}
if (selection == null) { return true; }
final BlockVector pos1 = selection.getNativeMinimumPoint().toBlockVector();
final BlockVector pos2 = selection.getNativeMaximumPoint().toBlockVector();
HashSet<RegionWrapper> mask = WEManager.getMask(pp);
RegionWrapper region = new RegionWrapper(pos1.getBlockX(), pos2.getBlockX(), pos1.getBlockZ(), pos2.getBlockZ());
if (Settings.REQUIRE_SELECTION) {
final HashSet<RegionWrapper> mask = WEManager.getMask(pp);
final RegionWrapper region = new RegionWrapper(pos1.getBlockX(), pos2.getBlockX(), pos1.getBlockZ(), pos2.getBlockZ());
if (Settings.REQUIRE_SELECTION)
{
String arg = null;
if (!WEManager.regionContains(region, mask)) {
if (!WEManager.regionContains(region, mask))
{
arg = "pos1 + pos2";
}
else if (!WEManager.maskContains(mask, pos1.getBlockX(), pos1.getBlockY(), pos1.getBlockZ())) {
else if (!WEManager.maskContains(mask, pos1.getBlockX(), pos1.getBlockY(), pos1.getBlockZ()))
{
arg = "pos1";
}
else if (!WEManager.maskContains(mask, pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ())) {
else if (!WEManager.maskContains(mask, pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ()))
{
arg = "pos2";
}
if (arg != null) {
if (arg != null)
{
e.setCancelled(true);
MainUtil.sendMessage(pp, C.REQUIRE_SELECTION_IN_MASK, arg);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
if (!WEManager.regionContains(region, mask)) {
if (!WEManager.regionContains(region, mask))
{
MainUtil.sendMessage(pp, C.REQUIRE_SELECTION_IN_MASK, "pos1 + pos2");
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
}
long volume = Math.abs((pos1.getBlockX() - pos2.getBlockX()) * (pos1.getBlockY() - pos2.getBlockY()) * (pos1.getBlockZ() - pos2.getBlockZ())) * modifier;
final long volume = Math.abs((pos1.getBlockX() - pos2.getBlockX()) * (pos1.getBlockY() - pos2.getBlockY()) * (pos1.getBlockZ() - pos2.getBlockZ())) * modifier;
return checkVolume(pp, volume, max, e);
}
private boolean set = false;
public boolean delay(final Player player, final String command, boolean delayed) {
if (!Settings.QUEUE_COMMANDS || !Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT || set) {
return false;
}
boolean free = SetBlockQueue.addNotify(null);
if (free) {
if (delayed) {
private final boolean set = false;
public boolean delay(final Player player, final String command, final boolean delayed)
{
if (!Settings.QUEUE_COMMANDS || !Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT || set) { return false; }
final boolean free = SetBlockQueue.addNotify(null);
if (free)
{
if (delayed)
{
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.WORLDEDIT_RUN, command);
Bukkit.getServer().dispatchCommand(player, command.substring(1));
}
else {
else
{
return false;
}
}
else {
if (!delayed) {
else
{
if (!delayed)
{
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.WORLDEDIT_DELAYED);
}
SetBlockQueue.addNotify(new Runnable() {
SetBlockQueue.addNotify(new Runnable()
{
@Override
public void run() {
public void run()
{
delay(player, command, true);
}
});
}
return true;
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public boolean onPlayerCommand(final PlayerCommandPreprocessEvent e) {
WorldEditPlugin worldedit = BukkitMain.worldEdit;
if (worldedit == null) {
public boolean onPlayerCommand(final PlayerCommandPreprocessEvent e)
{
final WorldEditPlugin worldedit = BukkitMain.worldEdit;
if (worldedit == null)
{
HandlerList.unregisterAll(this);
return true;
}
final Player p = e.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(p);
if (!PS.get().isPlotWorld(p.getWorld().getName())) {
return true;
}
String message = e.getMessage();
String cmd = message.toLowerCase();
boolean single = true;
String[] split = cmd.split(" ");
long maxVolume = Settings.WE_MAX_VOLUME;
long maxIterations = Settings.WE_MAX_ITERATIONS;
if (pp.getAttribute("worldedit")) {
return true;
}
if (split.length >= 2) {
String reduced = reduceCmd(split[0], single);
String reduced2 = reduceCmd(split[0] + " " + split[1], single);
if (rad1.contains(reduced)) {
if (delay(p, message, false)) { e.setCancelled(true); return true; }
long volume = getInt(split[1]) * 256;
if (!PS.get().isPlotWorld(p.getWorld().getName())) { return true; }
final String message = e.getMessage();
final String cmd = message.toLowerCase();
final boolean single = true;
final String[] split = cmd.split(" ");
final long maxVolume = Settings.WE_MAX_VOLUME;
final long maxIterations = Settings.WE_MAX_ITERATIONS;
if (pp.getAttribute("worldedit")) { return true; }
if (split.length >= 2)
{
final String reduced = reduceCmd(split[0], single);
final String reduced2 = reduceCmd(split[0] + " " + split[1], single);
if (rad1.contains(reduced))
{
if (delay(p, message, false))
{
e.setCancelled(true);
return true;
}
final long volume = getInt(split[1]) * 256;
return checkVolume(pp, volume, maxVolume, e);
}
if (rad2.contains(reduced)) {
if (delay(p, message, false)) { e.setCancelled(true); return true; }
if (split.length >= 3) {
long volume = getInt(split[2]) * 256;
if (rad2.contains(reduced))
{
if (delay(p, message, false))
{
e.setCancelled(true);
return true;
}
if (split.length >= 3)
{
final long volume = getInt(split[2]) * 256;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (rad2_1.contains(reduced)) {
if (delay(p, message, false)) { e.setCancelled(true); return true; }
if (split.length >= 4) {
long volume = getInt(split[2]) * getInt(split[3]);
if (rad2_1.contains(reduced))
{
if (delay(p, message, false))
{
e.setCancelled(true);
return true;
}
if (split.length >= 4)
{
final long volume = getInt(split[2]) * getInt(split[3]);
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (rad2_2.contains(reduced)) {
if (delay(p, message, false)) { e.setCancelled(true); return true; }
if (split.length >= 3) {
long radius = getInt(split[2]);
long volume = radius * radius;
if (rad2_2.contains(reduced))
{
if (delay(p, message, false))
{
e.setCancelled(true);
return true;
}
if (split.length >= 3)
{
final long radius = getInt(split[2]);
final long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (rad2_3.contains(reduced2)) {
if (delay(p, message, false)) { e.setCancelled(true); return true; }
if (split.length >= 3) {
if (split.length == 4) {
int iterations = getInt(split[3]);
if (iterations > maxIterations) {
if (rad2_3.contains(reduced2))
{
if (delay(p, message, false))
{
e.setCancelled(true);
return true;
}
if (split.length >= 3)
{
if (split.length == 4)
{
final int iterations = getInt(split[3]);
if (iterations > maxIterations)
{
MainUtil.sendMessage(pp, C.WORLDEDIT_ITERATIONS.s().replaceAll("%current%", iterations + "").replaceAll("%max%", maxIterations + ""));
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
}
long radius = getInt(split[2]);
long volume = radius * radius;
final long radius = getInt(split[2]);
final long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (rad3_1.contains(reduced2)) {
if (delay(p, message, false)) { e.setCancelled(true); return true; }
if (split.length >= 3) {
if (rad3_1.contains(reduced2))
{
if (delay(p, message, false))
{
e.setCancelled(true);
return true;
}
if (split.length >= 3)
{
int i = 2;
if (split[i].equalsIgnoreCase("-h")) {
if (split[i].equalsIgnoreCase("-h"))
{
i = 3;
}
long radius = getInt(split[i]);
long volume = radius * radius;
final long radius = getInt(split[i]);
final long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (rad3_2.contains(reduced2)) {
if (delay(p, message, false)) { e.setCancelled(true); return true; }
if (split.length >= 4) {
if (rad3_2.contains(reduced2))
{
if (delay(p, message, false))
{
e.setCancelled(true);
return true;
}
if (split.length >= 4)
{
int i = 3;
if (split[i].equalsIgnoreCase("-h")) {
if (split[i].equalsIgnoreCase("-h"))
{
i = 4;
}
long radius = getInt(split[i]);
long volume = radius * radius;
final long radius = getInt(split[i]);
final long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (regionExtend.contains(reduced)) {
if (delay(p, message, false)) { e.setCancelled(true); return true; }
if (regionExtend.contains(reduced))
{
if (delay(p, message, false))
{
e.setCancelled(true);
return true;
}
return checkSelection(p, pp, getInt(split[1]), maxVolume, e);
}
}
String reduced = reduceCmd(split[0], single);
if (Settings.WE_BLACKLIST.contains(reduced)) {
final String reduced = reduceCmd(split[0], single);
if (Settings.WE_BLACKLIST.contains(reduced))
{
MainUtil.sendMessage(pp, C.WORLDEDIT_UNSAFE);
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
}
if (restricted.contains(reduced)) {
Plot plot = MainUtil.getPlot(pp.getLocation());
if (plot != null && plot.isAdded(pp.getUUID())) {
if (delay(p, message, false)) { e.setCancelled(true); return true; }
if (restricted.contains(reduced))
{
final Plot plot = MainUtil.getPlot(pp.getLocation());
if ((plot != null) && plot.isAdded(pp.getUUID()))
{
if (delay(p, message, false))
{
e.setCancelled(true);
return true;
}
return true;
}
e.setCancelled(true);
MainUtil.sendMessage(pp, C.NO_PLOT_PERMS);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
if (region.contains(reduced)) {
if (delay(p, message, false)) { e.setCancelled(true); return true; }
if (region.contains(reduced))
{
if (delay(p, message, false))
{
e.setCancelled(true);
return true;
}
return checkSelection(p, pp, 1, maxVolume, e);
}
if (other.contains(reduced)) {
if (delay(p, message, false)) { e.setCancelled(true); return true; }
if (other.contains(reduced))
{
if (delay(p, message, false))
{
e.setCancelled(true);
return true;
}
}
return true;
}
}

View File

@ -5,37 +5,41 @@ import org.bukkit.block.Block;
import com.intellectualcrafters.plot.object.LazyBlock;
import com.intellectualcrafters.plot.object.PlotBlock;
public class BukkitLazyBlock extends LazyBlock {
public class BukkitLazyBlock extends LazyBlock
{
private int id = -1;
private Block block;
private PlotBlock pb;
public BukkitLazyBlock(int id, Block block) {
public BukkitLazyBlock(final int id, final Block block)
{
this.id = id;
this.block = block;
}
public BukkitLazyBlock(PlotBlock pb) {
this.id = pb.id;
public BukkitLazyBlock(final PlotBlock pb)
{
id = pb.id;
this.pb = pb;
}
public BukkitLazyBlock(Block block) {
public BukkitLazyBlock(final Block block)
{
this.block = block;
}
@Override
public PlotBlock getPlotBlock() {
if (pb != null) {
return pb;
}
if (id == -1 ) {
public PlotBlock getPlotBlock()
{
if (pb != null) { return pb; }
if (id == -1)
{
id = block.getTypeId();
}
byte data;
switch(id) {
switch (id)
{
case 0:
case 2:
case 4:
@ -127,15 +131,17 @@ public class BukkitLazyBlock extends LazyBlock {
}
pb = new PlotBlock((short) id, data);
return pb;
}
@Override
public int getId() {
if (id == -1) {
public int getId()
{
if (id == -1)
{
id = block.getTypeId();
}
return id;
}
}

View File

@ -6,35 +6,41 @@ import org.bukkit.OfflinePlayer;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
public class BukkitOfflinePlayer implements OfflinePlotPlayer {
public class BukkitOfflinePlayer implements OfflinePlotPlayer
{
public final OfflinePlayer player;
/**
* Please do not use this method. Instead use BukkitUtil.getPlayer(Player), as it caches player objects.
* @param player
*/
public BukkitOfflinePlayer(final OfflinePlayer player) {
public BukkitOfflinePlayer(final OfflinePlayer player)
{
this.player = player;
}
@Override
public UUID getUUID() {
return this.player.getUniqueId();
public UUID getUUID()
{
return player.getUniqueId();
}
@Override
public long getLastPlayed() {
return this.player.getLastPlayed();
public long getLastPlayed()
{
return player.getLastPlayed();
}
@Override
public boolean isOnline() {
return this.player.isOnline();
public boolean isOnline()
{
return player.isOnline();
}
@Override
public String getName() {
return this.player.getName();
public String getName()
{
return player.getName();
}
}

View File

@ -24,8 +24,9 @@ import com.intellectualcrafters.plot.util.PlotWeather;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.util.BukkitUtil;
public class BukkitPlayer extends PlotPlayer {
public class BukkitPlayer extends PlotPlayer
{
public final Player player;
private UUID uuid;
private String name;
@ -38,73 +39,85 @@ public class BukkitPlayer extends PlotPlayer {
* Please do not use this method. Instead use BukkitUtil.getPlayer(Player), as it caches player objects.
* @param player
*/
public BukkitPlayer(final Player player) {
public BukkitPlayer(final Player player)
{
this.player = player;
}
public BukkitPlayer(final Player player, boolean offline) {
public BukkitPlayer(final Player player, final boolean offline)
{
this.player = player;
this.offline = offline;
}
public long getPreviousLogin() {
if (last == 0) {
@Override
public long getPreviousLogin()
{
if (last == 0)
{
last = player.getLastPlayed();
}
return last;
}
@Override
public Location getLocation() {
Location loc = super.getLocation();
return loc == null ? BukkitUtil.getLocation(this.player) : loc;
public Location getLocation()
{
final Location loc = super.getLocation();
return loc == null ? BukkitUtil.getLocation(player) : loc;
}
@Override
public UUID getUUID() {
if (this.uuid == null) {
this.uuid = UUIDHandler.getUUID(this);
public UUID getUUID()
{
if (uuid == null)
{
uuid = UUIDHandler.getUUID(this);
}
return this.uuid;
return uuid;
}
@Override
public boolean hasPermission(final String node) {
if (Settings.PERMISSION_CACHING) {
if (this.noPerm.contains(node)) {
return false;
}
if (this.hasPerm.contains(node)) {
return true;
}
public boolean hasPermission(final String node)
{
if (Settings.PERMISSION_CACHING)
{
if (noPerm.contains(node)) { return false; }
if (hasPerm.contains(node)) { return true; }
}
if (offline && EconHandler.manager != null) {
return EconHandler.manager.hasPermission(getName(), node);
}
boolean value = this.player.hasPermission(node);
if (Settings.PERMISSION_CACHING) {
if (value) {
this.hasPerm.add(node);
if (offline && (EconHandler.manager != null)) { return EconHandler.manager.hasPermission(getName(), node); }
final boolean value = player.hasPermission(node);
if (Settings.PERMISSION_CACHING)
{
if (value)
{
hasPerm.add(node);
}
else {
this.noPerm.add(node);
else
{
noPerm.add(node);
}
}
return value;
}
public Permission getPermission(String node) {
PluginManager manager = Bukkit.getPluginManager();
public Permission getPermission(final String node)
{
final PluginManager manager = Bukkit.getPluginManager();
Permission perm = manager.getPermission(node);
if (perm == null) {
String[] nodes = node.split("\\.");
if (perm == null)
{
final String[] nodes = node.split("\\.");
perm = new Permission(node);
final StringBuilder n = new StringBuilder();
for (int i = 0; i < (nodes.length - 1); i++) {
for (int i = 0; i < (nodes.length - 1); i++)
{
n.append(nodes[i] + ("."));
if (!node.equals(n + C.PERMISSION_STAR.s())) {
Permission parent = getPermission(n + C.PERMISSION_STAR.s());
if (parent != null) {
if (!node.equals(n + C.PERMISSION_STAR.s()))
{
final Permission parent = getPermission(n + C.PERMISSION_STAR.s());
if (parent != null)
{
perm.addParent(parent, true);
}
}
@ -115,53 +128,61 @@ public class BukkitPlayer extends PlotPlayer {
perm.recalculatePermissibles();
return perm;
}
@Override
public void sendMessage(final String message) {
this.player.sendMessage(message);
public void sendMessage(final String message)
{
player.sendMessage(message);
}
@Override
public void sendMessage(C c, String... args) {
public void sendMessage(final C c, final String... args)
{
MainUtil.sendMessage(this, c, args);
}
@Override
public void teleport(final Location loc) {
if (Math.abs(loc.getX()) >= 30000000 || Math.abs(loc.getZ()) >= 30000000) {
return;
public void teleport(final Location loc)
{
if ((Math.abs(loc.getX()) >= 30000000) || (Math.abs(loc.getZ()) >= 30000000)) { return; }
player.teleport(new org.bukkit.Location(BukkitUtil.getWorld(loc.getWorld()), loc.getX() + 0.5, loc.getY(), loc.getZ() + 0.5, loc.getYaw(), loc.getPitch()), TeleportCause.COMMAND);
}
@Override
public String getName()
{
if (name == null)
{
name = player.getName();
}
this.player.teleport(new org.bukkit.Location(BukkitUtil.getWorld(loc.getWorld()), loc.getX() + 0.5, loc.getY(), loc.getZ() + 0.5, loc.getYaw(), loc.getPitch()), TeleportCause.COMMAND);
return name;
}
@Override
public String getName() {
if (this.name == null) {
this.name = this.player.getName();
}
return this.name;
public boolean isOnline()
{
return !offline && player.isOnline();
}
@Override
public boolean isOnline() {
return !offline && this.player.isOnline();
}
@Override
public void setCompassTarget(final Location loc) {
this.player.setCompassTarget(new org.bukkit.Location(BukkitUtil.getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ()));
public void setCompassTarget(final Location loc)
{
player.setCompassTarget(new org.bukkit.Location(BukkitUtil.getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ()));
}
@Override
public Location getLocationFull() {
return BukkitUtil.getLocationFull(this.player);
public Location getLocationFull()
{
return BukkitUtil.getLocationFull(player);
}
@Override
public void setAttribute(String key) {
public void setAttribute(String key)
{
key = "plotsquared_user_attributes." + key;
if (EconHandler.manager == null || player.hasPermission("plotsquared_user_attributes.*")) {
if ((EconHandler.manager == null) || player.hasPermission("plotsquared_user_attributes.*"))
{
setMeta(key, true);
return;
}
@ -169,14 +190,17 @@ public class BukkitPlayer extends PlotPlayer {
}
@Override
public boolean getAttribute(String key) {
public boolean getAttribute(String key)
{
key = "plotsquared_user_attributes." + key;
if (EconHandler.manager == null || player.hasPermission("plotsquared_user_attributes.*")) {
Object v = getMeta(key);
if ((EconHandler.manager == null) || player.hasPermission("plotsquared_user_attributes.*"))
{
final Object v = getMeta(key);
return v == null ? false : (Boolean) v;
}
Permission perm = Bukkit.getServer().getPluginManager().getPermission(key);
if (perm == null) {
if (perm == null)
{
perm = new Permission(key, PermissionDefault.FALSE);
Bukkit.getServer().getPluginManager().addPermission(perm);
Bukkit.getServer().getPluginManager().recalculatePermissionDefaults(perm);
@ -185,9 +209,11 @@ public class BukkitPlayer extends PlotPlayer {
}
@Override
public void removeAttribute(String key) {
public void removeAttribute(String key)
{
key = "plotsquared_user_attributes." + key;
if (EconHandler.manager == null || player.hasPermission("plotsquared_user_attributes.*")) {
if ((EconHandler.manager == null) || player.hasPermission("plotsquared_user_attributes.*"))
{
deleteMeta(key);
return;
}
@ -195,24 +221,30 @@ public class BukkitPlayer extends PlotPlayer {
}
@Override
public void loadData() {
if (!player.isOnline()) {
public void loadData()
{
if (!player.isOnline())
{
player.loadData();
}
}
@Override
public void saveData() {
public void saveData()
{
player.saveData();
}
@Override
public void setWeather(PlotWeather weather) {
switch (weather) {
public void setWeather(final PlotWeather weather)
{
switch (weather)
{
case CLEAR:
player.setPlayerWeather(WeatherType.CLEAR);
return;
case RAIN: {
case RAIN:
{
player.setPlayerWeather(WeatherType.DOWNFALL);
return;
}
@ -223,8 +255,10 @@ public class BukkitPlayer extends PlotPlayer {
}
@Override
public PlotGamemode getGamemode() {
switch (player.getGameMode()) {
public PlotGamemode getGamemode()
{
switch (player.getGameMode())
{
case ADVENTURE:
return PlotGamemode.ADVENTURE;
case CREATIVE:
@ -238,8 +272,10 @@ public class BukkitPlayer extends PlotPlayer {
}
@Override
public void setGamemode(PlotGamemode gamemode) {
switch (gamemode) {
public void setGamemode(final PlotGamemode gamemode)
{
switch (gamemode)
{
case ADVENTURE:
player.setGameMode(GameMode.ADVENTURE);
return;
@ -256,22 +292,26 @@ public class BukkitPlayer extends PlotPlayer {
}
@Override
public void setTime(long time) {
public void setTime(final long time)
{
player.setPlayerTime(time, false);
}
@Override
public void setFlight(boolean fly) {
public void setFlight(final boolean fly)
{
player.setAllowFlight(fly);
}
@Override
public void playMusic(Location loc, int id) {
public void playMusic(final Location loc, final int id)
{
player.playEffect(BukkitUtil.getLocation(loc), Effect.RECORD_PLAY, id);
}
@Override
public void kick(String message) {
public void kick(final String message)
{
player.kickPlayer(message);
}
}

View File

@ -37,7 +37,8 @@ import com.intellectualcrafters.plot.object.entity.ArmorStandStats;
import com.intellectualcrafters.plot.object.entity.EntityBaseStats;
import com.intellectualcrafters.plot.object.entity.HorseStats;
public class EntityWrapper {
public class EntityWrapper
{
public short id;
public float yaw;
public float pitch;
@ -59,43 +60,52 @@ public class EntityWrapper {
private ArmorStandStats stand;
private int hash;
@Override
public boolean equals(Object obj) {
public boolean equals(final Object obj)
{
return hash == obj.hashCode();
}
@Override
public int hashCode() {
public int hashCode()
{
return hash;
}
public void storeInventory(final InventoryHolder held) {
this.inventory = held.getInventory().getContents().clone();
public void storeInventory(final InventoryHolder held)
{
inventory = held.getInventory().getContents().clone();
}
private void restoreLiving(final LivingEntity entity) {
if (this.lived.loot) {
entity.setCanPickupItems(this.lived.loot);
private void restoreLiving(final LivingEntity entity)
{
if (lived.loot)
{
entity.setCanPickupItems(lived.loot);
}
if (this.lived.name != null) {
entity.setCustomName(this.lived.name);
entity.setCustomNameVisible(this.lived.visible);
if (lived.name != null)
{
entity.setCustomName(lived.name);
entity.setCustomNameVisible(lived.visible);
}
if ((this.lived.potions != null) && (this.lived.potions.size() > 0)) {
entity.addPotionEffects(this.lived.potions);
if ((lived.potions != null) && (lived.potions.size() > 0))
{
entity.addPotionEffects(lived.potions);
}
entity.setRemainingAir(this.lived.air);
entity.setRemoveWhenFarAway(this.lived.persistent);
if (this.lived.equipped) {
entity.setRemainingAir(lived.air);
entity.setRemoveWhenFarAway(lived.persistent);
if (lived.equipped)
{
final EntityEquipment equipment = entity.getEquipment();
equipment.setItemInHand(this.lived.hands);
equipment.setHelmet(this.lived.helmet);
equipment.setChestplate(this.lived.chestplate);
equipment.setLeggings(this.lived.leggings);
equipment.setBoots(this.lived.boots);
equipment.setItemInHand(lived.hands);
equipment.setHelmet(lived.helmet);
equipment.setChestplate(lived.chestplate);
equipment.setLeggings(lived.leggings);
equipment.setBoots(lived.boots);
}
if (this.lived.leashed) {
if (lived.leashed)
{
// TODO leashes
// World world = entity.getWorld();
// Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + lived.leash_x, Math.floor(y) + lived.leash_y, Math.floor(z) + lived.leash_z), EntityType.LEASH_HITCH);
@ -103,11 +113,13 @@ public class EntityWrapper {
}
}
private void restoreInventory(final InventoryHolder entity) {
entity.getInventory().setContents(this.inventory);
private void restoreInventory(final InventoryHolder entity)
{
entity.getInventory().setContents(inventory);
}
public void storeLiving(final LivingEntity lived) {
public void storeLiving(final LivingEntity lived)
{
this.lived = new LivingEntityStats();
this.lived.potions = lived.getActivePotionEffects();
this.lived.loot = lived.getCanPickupItems();
@ -117,15 +129,17 @@ public class EntityWrapper {
this.lived.air = (short) lived.getRemainingAir();
this.lived.persistent = lived.getRemoveWhenFarAway();
this.lived.leashed = lived.isLeashed();
if (this.lived.leashed) {
if (this.lived.leashed)
{
final Location loc = lived.getLeashHolder().getLocation();
this.lived.leash_x = (short) (this.x - loc.getBlockX());
this.lived.leash_y = (short) (this.y - loc.getBlockY());
this.lived.leash_z = (short) (this.z - loc.getBlockZ());
this.lived.leash_x = (short) (x - loc.getBlockX());
this.lived.leash_y = (short) (y - loc.getBlockY());
this.lived.leash_z = (short) (z - loc.getBlockZ());
}
final EntityEquipment equipment = lived.getEquipment();
this.lived.equipped = equipment != null;
if (this.lived.equipped) {
if (this.lived.equipped)
{
this.lived.hands = equipment.getItemInHand().clone();
this.lived.boots = equipment.getBoots().clone();
this.lived.leggings = equipment.getLeggings().clone();
@ -134,70 +148,78 @@ public class EntityWrapper {
}
}
private void restoreTameable(final Tameable entity) {
if (this.tamed.tamed) {
if (this.tamed.owner != null) {
private void restoreTameable(final Tameable entity)
{
if (tamed.tamed)
{
if (tamed.owner != null)
{
entity.setTamed(true);
entity.setOwner(this.tamed.owner);
entity.setOwner(tamed.owner);
}
}
}
private void restoreAgeable(final Ageable entity) {
if (!this.aged.adult) {
private void restoreAgeable(final Ageable entity)
{
if (!aged.adult)
{
entity.setBaby();
}
if (this.aged.locked) {
entity.setAgeLock(this.aged.locked);
if (aged.locked)
{
entity.setAgeLock(aged.locked);
}
if (this.aged.age > 0) {
entity.setAge(this.aged.age);
if (aged.age > 0)
{
entity.setAge(aged.age);
}
}
public void storeAgeable(final Ageable aged) {
public void storeAgeable(final Ageable aged)
{
this.aged = new AgeableStats();
this.aged.age = aged.getAge();
this.aged.locked = aged.getAgeLock();
this.aged.adult = aged.isAdult();
}
public void storeTameable(final Tameable tamed) {
public void storeTameable(final Tameable tamed)
{
this.tamed = new TameableStats();
this.tamed.owner = tamed.getOwner();
this.tamed.tamed = tamed.isTamed();
}
@SuppressWarnings("deprecation")
public EntityWrapper(final org.bukkit.entity.Entity entity, final short depth) {
this.hash = entity.getEntityId();
public EntityWrapper(final org.bukkit.entity.Entity entity, final short depth)
{
hash = entity.getEntityId();
this.depth = depth;
final Location loc = entity.getLocation();
this.yaw = loc.getYaw();
this.pitch = loc.getPitch();
this.x = loc.getX();
this.y = loc.getY();
this.z = loc.getZ();
this.id = entity.getType().getTypeId();
if (depth == 0) {
return;
}
this.base = new EntityBaseStats();
yaw = loc.getYaw();
pitch = loc.getPitch();
x = loc.getX();
y = loc.getY();
z = loc.getZ();
id = entity.getType().getTypeId();
if (depth == 0) { return; }
base = new EntityBaseStats();
final Entity p = entity.getPassenger();
if (p != null) {
this.base.passenger = new EntityWrapper(p, depth);
if (p != null)
{
base.passenger = new EntityWrapper(p, depth);
}
this.base.fall = entity.getFallDistance();
this.base.fire = (short) entity.getFireTicks();
this.base.age = entity.getTicksLived();
base.fall = entity.getFallDistance();
base.fire = (short) entity.getFireTicks();
base.age = entity.getTicksLived();
final Vector velocity = entity.getVelocity();
this.base.v_x = velocity.getX();
this.base.v_y = velocity.getY();
this.base.v_z = velocity.getZ();
if (depth == 1) {
return;
}
switch (entity.getType()) {
base.v_x = velocity.getX();
base.v_y = velocity.getY();
base.v_z = velocity.getZ();
if (depth == 1) { return; }
switch (entity.getType())
{
case ARROW:
case BOAT:
case COMPLEX_PART:
@ -226,57 +248,66 @@ public class EntityWrapper {
case THROWN_EXP_BOTTLE:
case WEATHER:
case WITHER_SKULL:
case UNKNOWN: {
case UNKNOWN:
{
// Do this stuff later
return;
}
default: {
default:
{
PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType());
return;
}
// MISC //
case DROPPED_ITEM: {
case DROPPED_ITEM:
{
final Item item = (Item) entity;
this.stack = item.getItemStack();
stack = item.getItemStack();
return;
}
case ITEM_FRAME: {
case ITEM_FRAME:
{
final ItemFrame itemframe = (ItemFrame) entity;
this.x = Math.floor(this.x);
this.y = Math.floor(this.y);
this.z = Math.floor(this.z);
this.dataByte = getOrdinal(Rotation.values(), itemframe.getRotation());
this.stack = itemframe.getItem().clone();
x = Math.floor(x);
y = Math.floor(y);
z = Math.floor(z);
dataByte = getOrdinal(Rotation.values(), itemframe.getRotation());
stack = itemframe.getItem().clone();
return;
}
case PAINTING: {
case PAINTING:
{
final Painting painting = (Painting) entity;
this.x = Math.floor(this.x);
this.y = Math.floor(this.y);
this.z = Math.floor(this.z);
x = Math.floor(x);
y = Math.floor(y);
z = Math.floor(z);
final Art a = painting.getArt();
this.dataByte = getOrdinal(BlockFace.values(), painting.getFacing());
dataByte = getOrdinal(BlockFace.values(), painting.getFacing());
final int h = a.getBlockHeight();
if ((h % 2) == 0) {
this.y -= 1;
if ((h % 2) == 0)
{
y -= 1;
}
this.dataString = a.name();
dataString = a.name();
return;
}
// END MISC //
// INVENTORY HOLDER //
case MINECART_CHEST: {
case MINECART_CHEST:
{
storeInventory((InventoryHolder) entity);
return;
}
case MINECART_HOPPER: {
case MINECART_HOPPER:
{
storeInventory((InventoryHolder) entity);
return;
}
// START LIVING ENTITY //
// START AGEABLE //
// START TAMEABLE //
case HORSE: {
case HORSE:
{
final Horse horse = (Horse) entity;
this.horse = new HorseStats();
this.horse.jump = horse.getJumpStrength();
@ -292,17 +323,19 @@ public class EntityWrapper {
}
// END INVENTORY HOLDER //
case WOLF:
case OCELOT: {
case OCELOT:
{
storeTameable((Tameable) entity);
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
}
// END AMEABLE //
case SHEEP: {
case SHEEP:
{
final Sheep sheep = (Sheep) entity;
this.dataByte = (byte) ((sheep).isSheared() ? 1 : 0);
this.dataByte2 = sheep.getColor().getDyeData();
dataByte = (byte) ((sheep).isSheared() ? 1 : 0);
dataByte2 = sheep.getColor().getDyeData();
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
@ -311,78 +344,88 @@ public class EntityWrapper {
case CHICKEN:
case COW:
case MUSHROOM_COW:
case PIG: {
case PIG:
{
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
}
// END AGEABLE //
case RABBIT: { // NEW
this.dataByte = getOrdinal(Type.values(), ((Rabbit) entity).getRabbitType());
case RABBIT:
{ // NEW
dataByte = getOrdinal(Type.values(), ((Rabbit) entity).getRabbitType());
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
}
case GUARDIAN: { // NEW
this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0);
case GUARDIAN:
{ // NEW
dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0);
storeLiving((LivingEntity) entity);
return;
}
case SKELETON: { // NEW
this.dataByte = (byte) ((Skeleton) entity).getSkeletonType().getId();
case SKELETON:
{ // NEW
dataByte = (byte) ((Skeleton) entity).getSkeletonType().getId();
storeLiving((LivingEntity) entity);
return;
}
case ARMOR_STAND: { // NEW
// CHECK positions
case ARMOR_STAND:
{ // NEW
// CHECK positions
final ArmorStand stand = (ArmorStand) entity;
this.inventory = new ItemStack[] { stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(), stand.getLeggings().clone(), stand.getBoots().clone() };
inventory = new ItemStack[] { stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(), stand.getLeggings().clone(), stand.getBoots().clone() };
storeLiving((LivingEntity) entity);
this.stand = new ArmorStandStats();
EulerAngle head = stand.getHeadPose();
final EulerAngle head = stand.getHeadPose();
this.stand.head[0] = (float) head.getX();
this.stand.head[1] = (float) head.getY();
this.stand.head[2] = (float) head.getZ();
EulerAngle body = stand.getBodyPose();
final EulerAngle body = stand.getBodyPose();
this.stand.body[0] = (float) body.getX();
this.stand.body[1] = (float) body.getY();
this.stand.body[2] = (float) body.getZ();
EulerAngle leftLeg = stand.getLeftLegPose();
final EulerAngle leftLeg = stand.getLeftLegPose();
this.stand.leftLeg[0] = (float) leftLeg.getX();
this.stand.leftLeg[1] = (float) leftLeg.getY();
this.stand.leftLeg[2] = (float) leftLeg.getZ();
EulerAngle rightLeg = stand.getRightLegPose();
final EulerAngle rightLeg = stand.getRightLegPose();
this.stand.rightLeg[0] = (float) rightLeg.getX();
this.stand.rightLeg[1] = (float) rightLeg.getY();
this.stand.rightLeg[2] = (float) rightLeg.getZ();
EulerAngle leftArm = stand.getLeftArmPose();
final EulerAngle leftArm = stand.getLeftArmPose();
this.stand.leftArm[0] = (float) leftArm.getX();
this.stand.leftArm[1] = (float) leftArm.getY();
this.stand.leftArm[2] = (float) leftArm.getZ();
EulerAngle rightArm = stand.getRightArmPose();
final EulerAngle rightArm = stand.getRightArmPose();
this.stand.rightArm[0] = (float) rightArm.getX();
this.stand.rightArm[1] = (float) rightArm.getY();
this.stand.rightArm[2] = (float) rightArm.getZ();
if (stand.hasArms()) {
if (stand.hasArms())
{
this.stand.arms = true;
}
if (!stand.hasBasePlate()) {
if (!stand.hasBasePlate())
{
this.stand.noplate = true;
}
if (!stand.hasGravity()) {
if (!stand.hasGravity())
{
this.stand.nogravity = true;
}
if (!stand.isVisible()) {
if (!stand.isVisible())
{
this.stand.invisible = true;
}
if (stand.isSmall()) {
if (stand.isSmall())
{
this.stand.small = true;
}
return;
@ -405,7 +448,8 @@ public class EntityWrapper {
case CREEPER:
case BLAZE:
case SNOWMAN:
case IRON_GOLEM: {
case IRON_GOLEM:
{
storeLiving((LivingEntity) entity);
return;
}
@ -414,28 +458,32 @@ public class EntityWrapper {
}
@SuppressWarnings("deprecation")
public Entity spawn(final World world, final int x_offset, final int z_offset) {
final Location loc = new Location(world, this.x + x_offset, this.y, this.z + z_offset);
loc.setYaw(this.yaw);
loc.setPitch(this.pitch);
if (this.id == -1) {
return null;
}
final EntityType type = EntityType.fromId(this.id);
public Entity spawn(final World world, final int x_offset, final int z_offset)
{
final Location loc = new Location(world, x + x_offset, y, z + z_offset);
loc.setYaw(yaw);
loc.setPitch(pitch);
if (id == -1) { return null; }
final EntityType type = EntityType.fromId(id);
Entity entity;
switch (type) {
case DROPPED_ITEM: {
return world.dropItem(loc, this.stack);
switch (type)
{
case DROPPED_ITEM:
{
return world.dropItem(loc, stack);
}
case PLAYER:
case LEASH_HITCH: {
case LEASH_HITCH:
{
return null;
}
case ITEM_FRAME: {
case ITEM_FRAME:
{
entity = world.spawn(loc, ItemFrame.class);
break;
}
case PAINTING: {
case PAINTING:
{
entity = world.spawn(loc, Painting.class);
break;
}
@ -443,23 +491,32 @@ public class EntityWrapper {
entity = world.spawnEntity(loc, type);
break;
}
if (this.depth == 0) {
return entity;
}
if (this.base.passenger != null) {
try {
entity.setPassenger(this.base.passenger.spawn(world, x_offset, z_offset));
} catch (final Exception e) {
if (depth == 0) { return entity; }
if (base.passenger != null)
{
try
{
entity.setPassenger(base.passenger.spawn(world, x_offset, z_offset));
}
catch (final Exception e)
{}
}
if (this.base.fall != 0) entity.setFallDistance(this.base.fall);
if (this.base.fire != 0) entity.setFireTicks(this.base.fire);
if (this.base.age != 0) entity.setTicksLived(this.base.age);
entity.setVelocity(new Vector(this.base.v_x, this.base.v_y, this.base.v_z));
if (this.depth == 1) {
return entity;
if (base.fall != 0)
{
entity.setFallDistance(base.fall);
}
switch (entity.getType()) {
if (base.fire != 0)
{
entity.setFireTicks(base.fire);
}
if (base.age != 0)
{
entity.setTicksLived(base.age);
}
entity.setVelocity(new Vector(base.v_x, base.v_y, base.v_z));
if (depth == 1) { return entity; }
switch (entity.getType())
{
case ARROW:
case BOAT:
case COMPLEX_PART:
@ -488,41 +545,48 @@ public class EntityWrapper {
case WEATHER:
case WITHER_SKULL:
case MINECART_FURNACE:
case UNKNOWN: {
case UNKNOWN:
{
// Do this stuff later
return entity;
}
default: {
default:
{
PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType());
return entity;
}
// MISC //
case ITEM_FRAME: {
case ITEM_FRAME:
{
final ItemFrame itemframe = (ItemFrame) entity;
itemframe.setRotation(Rotation.values()[this.dataByte]);
itemframe.setItem(this.stack);
itemframe.setRotation(Rotation.values()[dataByte]);
itemframe.setItem(stack);
return entity;
}
case PAINTING: {
case PAINTING:
{
final Painting painting = (Painting) entity;
painting.setFacingDirection(BlockFace.values()[this.dataByte], true);
painting.setArt(Art.getByName(this.dataString), true);
painting.setFacingDirection(BlockFace.values()[dataByte], true);
painting.setArt(Art.getByName(dataString), true);
return entity;
}
// END MISC //
// INVENTORY HOLDER //
case MINECART_CHEST: {
case MINECART_CHEST:
{
restoreInventory((InventoryHolder) entity);
return entity;
}
case MINECART_HOPPER: {
case MINECART_HOPPER:
{
restoreInventory((InventoryHolder) entity);
return entity;
}
// START LIVING ENTITY //
// START AGEABLE //
// START TAMEABLE //
case HORSE: {
case HORSE:
{
final Horse horse = (Horse) entity;
horse.setJumpStrength(this.horse.jump);
horse.setCarryingChest(this.horse.chest);
@ -537,20 +601,24 @@ public class EntityWrapper {
}
// END INVENTORY HOLDER //
case WOLF:
case OCELOT: {
case OCELOT:
{
restoreTameable((Tameable) entity);
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
}
// END AMEABLE //
case SHEEP: {
case SHEEP:
{
final Sheep sheep = (Sheep) entity;
if (this.dataByte == 1) {
if (dataByte == 1)
{
sheep.setSheared(true);
}
if (this.dataByte2 != 0) {
sheep.setColor(DyeColor.getByDyeData(this.dataByte2));
if (dataByte2 != 0)
{
sheep.setColor(DyeColor.getByDyeData(dataByte2));
}
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
@ -560,89 +628,113 @@ public class EntityWrapper {
case CHICKEN:
case COW:
case MUSHROOM_COW:
case PIG: {
case PIG:
{
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
}
// END AGEABLE //
case RABBIT: { // NEW
if (this.dataByte != 0) {
((Rabbit) entity).setRabbitType(Type.values()[this.dataByte]);
case RABBIT:
{ // NEW
if (dataByte != 0)
{
((Rabbit) entity).setRabbitType(Type.values()[dataByte]);
}
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
}
case GUARDIAN: { // NEW
if (this.dataByte != 0) {
case GUARDIAN:
{ // NEW
if (dataByte != 0)
{
((Guardian) entity).setElder(true);
}
restoreLiving((LivingEntity) entity);
return entity;
}
case SKELETON: { // NEW
if (this.dataByte != 0) {
((Skeleton) entity).setSkeletonType(SkeletonType.values()[this.dataByte]);
case SKELETON:
{ // NEW
if (dataByte != 0)
{
((Skeleton) entity).setSkeletonType(SkeletonType.values()[dataByte]);
}
storeLiving((LivingEntity) entity);
return entity;
}
case ARMOR_STAND: { // NEW
// CHECK positions
case ARMOR_STAND:
{ // NEW
// CHECK positions
final ArmorStand stand = (ArmorStand) entity;
if (this.inventory[0] != null) {
stand.setItemInHand(this.inventory[0]);
if (inventory[0] != null)
{
stand.setItemInHand(inventory[0]);
}
if (this.inventory[1] != null) {
stand.setHelmet(this.inventory[1]);
if (inventory[1] != null)
{
stand.setHelmet(inventory[1]);
}
if (this.inventory[2] != null) {
stand.setChestplate(this.inventory[2]);
if (inventory[2] != null)
{
stand.setChestplate(inventory[2]);
}
if (this.inventory[3] != null) {
stand.setLeggings(this.inventory[3]);
if (inventory[3] != null)
{
stand.setLeggings(inventory[3]);
}
if (this.inventory[4] != null) {
stand.setBoots(this.inventory[4]);
if (inventory[4] != null)
{
stand.setBoots(inventory[4]);
}
if (this.stand.head[0] != 0 || this.stand.head[1] != 0 || this.stand.head[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]);
if ((this.stand.head[0] != 0) || (this.stand.head[1] != 0) || (this.stand.head[2] != 0))
{
final EulerAngle pose = new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]);
stand.setHeadPose(pose);
}
if (this.stand.body[0] != 0 || this.stand.body[1] != 0 || this.stand.body[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]);
if ((this.stand.body[0] != 0) || (this.stand.body[1] != 0) || (this.stand.body[2] != 0))
{
final EulerAngle pose = new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]);
stand.setBodyPose(pose);
}
if (this.stand.leftLeg[0] != 0 || this.stand.leftLeg[1] != 0 || this.stand.leftLeg[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], this.stand.leftLeg[2]);
if ((this.stand.leftLeg[0] != 0) || (this.stand.leftLeg[1] != 0) || (this.stand.leftLeg[2] != 0))
{
final EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], this.stand.leftLeg[2]);
stand.setLeftLegPose(pose);
}
if (this.stand.rightLeg[0] != 0 || this.stand.rightLeg[1] != 0 || this.stand.rightLeg[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], this.stand.rightLeg[2]);
if ((this.stand.rightLeg[0] != 0) || (this.stand.rightLeg[1] != 0) || (this.stand.rightLeg[2] != 0))
{
final EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], this.stand.rightLeg[2]);
stand.setRightLegPose(pose);
}
if (this.stand.leftArm[0] != 0 || this.stand.leftArm[1] != 0 || this.stand.leftArm[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], this.stand.leftArm[2]);
if ((this.stand.leftArm[0] != 0) || (this.stand.leftArm[1] != 0) || (this.stand.leftArm[2] != 0))
{
final EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], this.stand.leftArm[2]);
stand.setLeftArmPose(pose);
}
if (this.stand.rightArm[0] != 0 || this.stand.rightArm[1] != 0 || this.stand.rightArm[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], this.stand.rightArm[2]);
if ((this.stand.rightArm[0] != 0) || (this.stand.rightArm[1] != 0) || (this.stand.rightArm[2] != 0))
{
final EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], this.stand.rightArm[2]);
stand.setRightArmPose(pose);
}
if (this.stand.invisible) {
if (this.stand.invisible)
{
stand.setVisible(false);
}
if (this.stand.arms) {
if (this.stand.arms)
{
stand.setArms(true);
}
if (this.stand.nogravity) {
if (this.stand.nogravity)
{
stand.setGravity(false);
}
if (this.stand.noplate) {
if (this.stand.noplate)
{
stand.setBasePlate(false);
}
if (this.stand.small) {
if (this.stand.small)
{
stand.setSmall(true);
}
restoreLiving((LivingEntity) entity);
@ -666,7 +758,8 @@ public class EntityWrapper {
case CREEPER:
case BLAZE:
case SNOWMAN:
case IRON_GOLEM: {
case IRON_GOLEM:
{
restoreLiving((LivingEntity) entity);
return entity;
}
@ -674,11 +767,11 @@ public class EntityWrapper {
}
}
private byte getOrdinal(final Object[] list, final Object value) {
for (byte i = 0; i < list.length; i++) {
if (list[i].equals(value)) {
return i;
}
private byte getOrdinal(final Object[] list, final Object value)
{
for (byte i = 0; i < list.length; i++)
{
if (list[i].equals(value)) { return i; }
}
return 0;
}

View File

@ -5,7 +5,8 @@ import java.util.Collection;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
public class LivingEntityStats {
public class LivingEntityStats
{
public boolean loot;
public String name;
public boolean visible;

View File

@ -2,7 +2,8 @@ package com.plotsquared.bukkit.object.entity;
import org.bukkit.entity.AnimalTamer;
public class TameableStats {
public class TameableStats
{
public AnimalTamer owner;
public boolean tamed;
}

View File

@ -4,13 +4,18 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class DefaultTitle extends AbstractTitle {
public class DefaultTitle extends AbstractTitle
{
@Override
public void sendTitle(final PlotPlayer player, final String head, final String sub, int in, int delay, int out) {
try {
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out)
{
try
{
final DefaultTitleManager title = new DefaultTitleManager(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player);
} catch (final Throwable e) {
}
catch (final Throwable e)
{
AbstractTitle.TITLE_CLASS = new DefaultTitle_183();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
}

View File

@ -17,7 +17,8 @@ import org.bukkit.entity.Player;
* @author Maxim Van de Wynckel
*
*/
public class DefaultTitleManager {
public class DefaultTitleManager
{
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
@ -45,7 +46,8 @@ public class DefaultTitleManager {
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final String title) throws ClassNotFoundException {
public DefaultTitleManager(final String title) throws ClassNotFoundException
{
this.title = title;
loadClasses();
}
@ -59,7 +61,8 @@ public class DefaultTitleManager {
* Subtitle text
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final String title, final String subtitle) throws ClassNotFoundException {
public DefaultTitleManager(final String title, final String subtitle) throws ClassNotFoundException
{
this.title = title;
this.subtitle = subtitle;
loadClasses();
@ -72,16 +75,17 @@ public class DefaultTitleManager {
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final DefaultTitleManager title) throws ClassNotFoundException {
public DefaultTitleManager(final DefaultTitleManager title) throws ClassNotFoundException
{
// Copy title
this.title = title.title;
this.subtitle = title.subtitle;
this.titleColor = title.titleColor;
this.subtitleColor = title.subtitleColor;
this.fadeInTime = title.fadeInTime;
this.fadeOutTime = title.fadeOutTime;
this.stayTime = title.stayTime;
this.ticks = title.ticks;
subtitle = title.subtitle;
titleColor = title.titleColor;
subtitleColor = title.subtitleColor;
fadeInTime = title.fadeInTime;
fadeOutTime = title.fadeOutTime;
stayTime = title.stayTime;
ticks = title.ticks;
loadClasses();
}
@ -100,7 +104,8 @@ public class DefaultTitleManager {
* Fade out time
* @throws ClassNotFoundException
*/
public DefaultTitleManager(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException {
public DefaultTitleManager(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException
{
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
@ -113,11 +118,12 @@ public class DefaultTitleManager {
* Load spigot and NMS classes
* @throws ClassNotFoundException
*/
private void loadClasses() throws ClassNotFoundException {
this.packetTitle = getNMSClass("PacketPlayOutTitle");
this.packetActions = getNMSClass("EnumTitleAction");
this.chatBaseComponent = getNMSClass("IChatBaseComponent");
this.nmsChatSerializer = getNMSClass("ChatSerializer");
private void loadClasses() throws ClassNotFoundException
{
packetTitle = getNMSClass("PacketPlayOutTitle");
packetActions = getNMSClass("EnumTitleAction");
chatBaseComponent = getNMSClass("IChatBaseComponent");
nmsChatSerializer = getNMSClass("ChatSerializer");
}
/**
@ -126,7 +132,8 @@ public class DefaultTitleManager {
* @param title
* Title
*/
public void setTitle(final String title) {
public void setTitle(final String title)
{
this.title = title;
}
@ -135,8 +142,9 @@ public class DefaultTitleManager {
*
* @return Title text
*/
public String getTitle() {
return this.title;
public String getTitle()
{
return title;
}
/**
@ -145,7 +153,8 @@ public class DefaultTitleManager {
* @param subtitle
* Subtitle text
*/
public void setSubtitle(final String subtitle) {
public void setSubtitle(final String subtitle)
{
this.subtitle = subtitle;
}
@ -154,8 +163,9 @@ public class DefaultTitleManager {
*
* @return Subtitle text
*/
public String getSubtitle() {
return this.subtitle;
public String getSubtitle()
{
return subtitle;
}
/**
@ -164,8 +174,9 @@ public class DefaultTitleManager {
* @param color
* Chat color
*/
public void setTitleColor(final ChatColor color) {
this.titleColor = color;
public void setTitleColor(final ChatColor color)
{
titleColor = color;
}
/**
@ -174,8 +185,9 @@ public class DefaultTitleManager {
* @param color
* Chat color
*/
public void setSubtitleColor(final ChatColor color) {
this.subtitleColor = color;
public void setSubtitleColor(final ChatColor color)
{
subtitleColor = color;
}
/**
@ -184,8 +196,9 @@ public class DefaultTitleManager {
* @param time
* Time
*/
public void setFadeInTime(final int time) {
this.fadeInTime = time;
public void setFadeInTime(final int time)
{
fadeInTime = time;
}
/**
@ -194,8 +207,9 @@ public class DefaultTitleManager {
* @param time
* Time
*/
public void setFadeOutTime(final int time) {
this.fadeOutTime = time;
public void setFadeOutTime(final int time)
{
fadeOutTime = time;
}
/**
@ -204,22 +218,25 @@ public class DefaultTitleManager {
* @param time
* Time
*/
public void setStayTime(final int time) {
this.stayTime = time;
public void setStayTime(final int time)
{
stayTime = time;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks() {
this.ticks = true;
public void setTimingsToTicks()
{
ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds() {
this.ticks = false;
public void setTimingsToSeconds()
{
ticks = false;
}
/**
@ -231,28 +248,35 @@ public class DefaultTitleManager {
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void send(final Player player) throws Exception {
if (this.packetTitle != null) {
public void send(final Player player) throws Exception
{
if (packetTitle != null)
{
// First reset previous settings
resetTitle(player);
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], null, this.fadeInTime * (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20));
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], null,
fadeInTime * (ticks ? 1 : 20), stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
// Send if set
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1))
{
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized);
Object serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', title) + "\",color:" + titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (this.subtitle != "") {
if (subtitle != "")
{
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized);
serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', subtitle) + "\",color:" + subtitleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
@ -262,8 +286,10 @@ public class DefaultTitleManager {
* Broadcast the title to all players
* @throws Exception
*/
public void broadcast() throws Exception {
for (final Player p : Bukkit.getOnlinePlayers()) {
public void broadcast() throws Exception
{
for (final Player p : Bukkit.getOnlinePlayers())
{
send(p);
}
}
@ -273,17 +299,18 @@ public class DefaultTitleManager {
*
* @param player
* Player
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public void clearTitle(final Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
public void clearTitle(final Player player) throws Exception
{
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
}
/**
@ -292,88 +319,103 @@ public class DefaultTitleManager {
* @param player
* Player
*/
public void resetTitle(final Player player) throws Exception {
// Send timings first
public void resetTitle(final Player player) throws Exception
{
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[4], null);
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
private Class<?> getPrimitiveType(final Class<?> clazz) {
private Class<?> getPrimitiveType(final Class<?> clazz)
{
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes)
{
final int a = classes != null ? classes.length : 0;
final Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
for (int i = 0; i < a; i++)
{
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o)
{
if (a.length != o.length) { return false; }
for (int i = 0; i < a.length; i++)
{
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) { return false; }
}
return true;
}
private Object getHandle(final Object obj) {
try {
private Object getHandle(final Object obj)
{
try
{
return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (final Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) {
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes)
{
final Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (final Method m : clazz.getMethods()) {
for (final Method m : clazz.getMethods())
{
final Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
if (m.getName().equals(name) && equalsTypeArray(types, t)) { return m; }
}
return null;
}
private String getVersion() {
private String getVersion()
{
final String name = Bukkit.getServer().getClass().getPackage().getName();
final String version = name.substring(name.lastIndexOf('.') + 1) + ".";
return version;
}
private Class<?> getNMSClass(final String className) throws ClassNotFoundException {
private Class<?> getNMSClass(final String className) throws ClassNotFoundException
{
final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
clazz = Class.forName(fullName);
return clazz;
}
private Field getField(final Class<?> clazz, final String name) {
try {
private Field getField(final Class<?> clazz, final String name)
{
try
{
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (final Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
for (final Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args)
{
for (final Method m : clazz.getMethods())
{
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes())))
{
m.setAccessible(true);
return m;
}
@ -381,13 +423,14 @@ public class DefaultTitleManager {
return null;
}
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2)
{
boolean equal = true;
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
if (l1.length != l2.length) { return false; }
for (int i = 0; i < l1.length; i++)
{
if (l1[i] != l2[i])
{
equal = false;
break;
}

View File

@ -17,7 +17,8 @@ import org.bukkit.entity.Player;
* @author Maxim Van de Wynckel
*
*/
public class DefaultTitleManager_183 {
public class DefaultTitleManager_183
{
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
@ -45,7 +46,8 @@ public class DefaultTitleManager_183 {
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final String title) throws ClassNotFoundException {
public DefaultTitleManager_183(final String title) throws ClassNotFoundException
{
this.title = title;
loadClasses();
}
@ -59,7 +61,8 @@ public class DefaultTitleManager_183 {
* Subtitle text
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final String title, final String subtitle) throws ClassNotFoundException {
public DefaultTitleManager_183(final String title, final String subtitle) throws ClassNotFoundException
{
this.title = title;
this.subtitle = subtitle;
loadClasses();
@ -72,16 +75,17 @@ public class DefaultTitleManager_183 {
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final DefaultTitleManager_183 title) throws ClassNotFoundException {
public DefaultTitleManager_183(final DefaultTitleManager_183 title) throws ClassNotFoundException
{
// Copy title
this.title = title.title;
this.subtitle = title.subtitle;
this.titleColor = title.titleColor;
this.subtitleColor = title.subtitleColor;
this.fadeInTime = title.fadeInTime;
this.fadeOutTime = title.fadeOutTime;
this.stayTime = title.stayTime;
this.ticks = title.ticks;
subtitle = title.subtitle;
titleColor = title.titleColor;
subtitleColor = title.subtitleColor;
fadeInTime = title.fadeInTime;
fadeOutTime = title.fadeOutTime;
stayTime = title.stayTime;
ticks = title.ticks;
loadClasses();
}
@ -100,7 +104,8 @@ public class DefaultTitleManager_183 {
* Fade out time
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException {
public DefaultTitleManager_183(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException
{
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
@ -113,12 +118,13 @@ public class DefaultTitleManager_183 {
* Load spigot and NMS classes
* @throws ClassNotFoundException
*/
private void loadClasses() throws ClassNotFoundException {
this.packetTitle = getNMSClass("PacketPlayOutTitle");
this.chatBaseComponent = getNMSClass("IChatBaseComponent");
this.packetActions = getNMSClass("PacketPlayOutTitle$EnumTitleAction");
this.nmsChatSerializer = getNMSClass("IChatBaseComponent$ChatSerializer");
private void loadClasses() throws ClassNotFoundException
{
packetTitle = getNMSClass("PacketPlayOutTitle");
chatBaseComponent = getNMSClass("IChatBaseComponent");
packetActions = getNMSClass("PacketPlayOutTitle$EnumTitleAction");
nmsChatSerializer = getNMSClass("IChatBaseComponent$ChatSerializer");
}
/**
@ -127,7 +133,8 @@ public class DefaultTitleManager_183 {
* @param title
* Title
*/
public void setTitle(final String title) {
public void setTitle(final String title)
{
this.title = title;
}
@ -136,8 +143,9 @@ public class DefaultTitleManager_183 {
*
* @return Title text
*/
public String getTitle() {
return this.title;
public String getTitle()
{
return title;
}
/**
@ -146,7 +154,8 @@ public class DefaultTitleManager_183 {
* @param subtitle
* Subtitle text
*/
public void setSubtitle(final String subtitle) {
public void setSubtitle(final String subtitle)
{
this.subtitle = subtitle;
}
@ -155,8 +164,9 @@ public class DefaultTitleManager_183 {
*
* @return Subtitle text
*/
public String getSubtitle() {
return this.subtitle;
public String getSubtitle()
{
return subtitle;
}
/**
@ -165,8 +175,9 @@ public class DefaultTitleManager_183 {
* @param color
* Chat color
*/
public void setTitleColor(final ChatColor color) {
this.titleColor = color;
public void setTitleColor(final ChatColor color)
{
titleColor = color;
}
/**
@ -175,8 +186,9 @@ public class DefaultTitleManager_183 {
* @param color
* Chat color
*/
public void setSubtitleColor(final ChatColor color) {
this.subtitleColor = color;
public void setSubtitleColor(final ChatColor color)
{
subtitleColor = color;
}
/**
@ -185,8 +197,9 @@ public class DefaultTitleManager_183 {
* @param time
* Time
*/
public void setFadeInTime(final int time) {
this.fadeInTime = time;
public void setFadeInTime(final int time)
{
fadeInTime = time;
}
/**
@ -195,8 +208,9 @@ public class DefaultTitleManager_183 {
* @param time
* Time
*/
public void setFadeOutTime(final int time) {
this.fadeOutTime = time;
public void setFadeOutTime(final int time)
{
fadeOutTime = time;
}
/**
@ -205,22 +219,25 @@ public class DefaultTitleManager_183 {
* @param time
* Time
*/
public void setStayTime(final int time) {
this.stayTime = time;
public void setStayTime(final int time)
{
stayTime = time;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks() {
this.ticks = true;
public void setTimingsToTicks()
{
ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds() {
this.ticks = false;
public void setTimingsToSeconds()
{
ticks = false;
}
/**
@ -232,28 +249,35 @@ public class DefaultTitleManager_183 {
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void send(final Player player) throws Exception {
if (this.packetTitle != null) {
public void send(final Player player) throws Exception
{
if (packetTitle != null)
{
// First reset previous settings
resetTitle(player);
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], null, this.fadeInTime * (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20));
Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], null,
fadeInTime * (ticks ? 1 : 20), stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
// Send if set
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1))
{
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized);
Object serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', title) + "\",color:" + titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (this.subtitle != "") {
if (subtitle != "")
{
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized);
serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', subtitle) + "\",color:" + subtitleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
@ -263,8 +287,10 @@ public class DefaultTitleManager_183 {
* Broadcast the title to all players
* @throws Exception
*/
public void broadcast() throws Exception {
for (final Player p : Bukkit.getOnlinePlayers()) {
public void broadcast() throws Exception
{
for (final Player p : Bukkit.getOnlinePlayers())
{
send(p);
}
}
@ -274,17 +300,18 @@ public class DefaultTitleManager_183 {
*
* @param player
* Player
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public void clearTitle(final Player player) throws Exception {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
public void clearTitle(final Player player) throws Exception
{
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
}
/**
@ -292,95 +319,110 @@ public class DefaultTitleManager_183 {
*
* @param player
* Player
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public void resetTitle(final Player player) throws Exception {
public void resetTitle(final Player player) throws Exception
{
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[4], null);
final Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent).newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
private Class<?> getPrimitiveType(final Class<?> clazz) {
private Class<?> getPrimitiveType(final Class<?> clazz)
{
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes)
{
final int a = classes != null ? classes.length : 0;
final Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
for (int i = 0; i < a; i++)
{
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o)
{
if (a.length != o.length) { return false; }
for (int i = 0; i < a.length; i++)
{
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) { return false; }
}
return true;
}
private Object getHandle(final Object obj) {
try {
private Object getHandle(final Object obj)
{
try
{
return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (final Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) {
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes)
{
final Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (final Method m : clazz.getMethods()) {
for (final Method m : clazz.getMethods())
{
final Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
if (m.getName().equals(name) && equalsTypeArray(types, t)) { return m; }
}
return null;
}
private String getVersion() {
private String getVersion()
{
final String name = Bukkit.getServer().getClass().getPackage().getName();
final String version = name.substring(name.lastIndexOf('.') + 1) + ".";
return version;
}
private Class<?> getNMSClass(final String className) throws ClassNotFoundException {
private Class<?> getNMSClass(final String className) throws ClassNotFoundException
{
final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
clazz = Class.forName(fullName);
return clazz;
}
private Field getField(final Class<?> clazz, final String name) {
try {
private Field getField(final Class<?> clazz, final String name)
{
try
{
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (final Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
for (final Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args)
{
for (final Method m : clazz.getMethods())
{
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes())))
{
m.setAccessible(true);
return m;
}
@ -388,13 +430,14 @@ public class DefaultTitleManager_183 {
return null;
}
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2)
{
boolean equal = true;
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
if (l1.length != l2.length) { return false; }
for (int i = 0; i < l1.length; i++)
{
if (l1[i] != l2[i])
{
equal = false;
break;
}

View File

@ -4,13 +4,18 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class DefaultTitle_183 extends AbstractTitle {
public class DefaultTitle_183 extends AbstractTitle
{
@Override
public void sendTitle(final PlotPlayer player, final String head, final String sub, int in, int delay, int out) {
try {
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out)
{
try
{
final DefaultTitleManager_183 title = new DefaultTitleManager_183(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player);
} catch (final Throwable e) {
}
catch (final Throwable e)
{
AbstractTitle.TITLE_CLASS = new HackTitle();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
}

View File

@ -6,13 +6,18 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class HackTitle extends AbstractTitle {
public class HackTitle extends AbstractTitle
{
@Override
public void sendTitle(final PlotPlayer player, final String head, final String sub, int in, int delay, int out) {
try {
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out)
{
try
{
final HackTitleManager title = new HackTitleManager(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player);
} catch (final Throwable e) {
}
catch (final Throwable e)
{
PS.debug("&cYour server version does not support titles!");
Settings.TITLES = false;
AbstractTitle.TITLE_CLASS = null;

View File

@ -15,7 +15,8 @@ import org.bukkit.entity.Player;
* @version 1.0.4
* @author Maxim Van de Wynckel
*/
public class HackTitleManager {
public class HackTitleManager
{
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
@ -42,7 +43,8 @@ public class HackTitleManager {
* Title
* @throws ClassNotFoundException
*/
public HackTitleManager(final String title) throws ClassNotFoundException {
public HackTitleManager(final String title) throws ClassNotFoundException
{
this.title = title;
loadClasses();
}
@ -56,7 +58,8 @@ public class HackTitleManager {
* Subtitle text
* @throws ClassNotFoundException
*/
public HackTitleManager(final String title, final String subtitle) throws ClassNotFoundException {
public HackTitleManager(final String title, final String subtitle) throws ClassNotFoundException
{
this.title = title;
this.subtitle = subtitle;
loadClasses();
@ -69,16 +72,17 @@ public class HackTitleManager {
* Title
* @throws ClassNotFoundException
*/
public HackTitleManager(final HackTitleManager title) throws ClassNotFoundException {
public HackTitleManager(final HackTitleManager title) throws ClassNotFoundException
{
// Copy title
this.title = title.title;
this.subtitle = title.subtitle;
this.titleColor = title.titleColor;
this.subtitleColor = title.subtitleColor;
this.fadeInTime = title.fadeInTime;
this.fadeOutTime = title.fadeOutTime;
this.stayTime = title.stayTime;
this.ticks = title.ticks;
subtitle = title.subtitle;
titleColor = title.titleColor;
subtitleColor = title.subtitleColor;
fadeInTime = title.fadeInTime;
fadeOutTime = title.fadeOutTime;
stayTime = title.stayTime;
ticks = title.ticks;
loadClasses();
}
@ -97,7 +101,8 @@ public class HackTitleManager {
* Fade out time
* @throws ClassNotFoundException
*/
public HackTitleManager(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException {
public HackTitleManager(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) throws ClassNotFoundException
{
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
@ -110,10 +115,11 @@ public class HackTitleManager {
* Load spigot and NMS classes
* @throws ClassNotFoundException
*/
private void loadClasses() throws ClassNotFoundException {
this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
this.nmsChatSerializer = getNMSClass("ChatSerializer");
private void loadClasses() throws ClassNotFoundException
{
packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
nmsChatSerializer = getNMSClass("ChatSerializer");
}
/**
@ -122,7 +128,8 @@ public class HackTitleManager {
* @param title
* Title
*/
public void setTitle(final String title) {
public void setTitle(final String title)
{
this.title = title;
}
@ -131,8 +138,9 @@ public class HackTitleManager {
*
* @return Title text
*/
public String getTitle() {
return this.title;
public String getTitle()
{
return title;
}
/**
@ -141,7 +149,8 @@ public class HackTitleManager {
* @param subtitle
* Subtitle text
*/
public void setSubtitle(final String subtitle) {
public void setSubtitle(final String subtitle)
{
this.subtitle = subtitle;
}
@ -150,8 +159,9 @@ public class HackTitleManager {
*
* @return Subtitle text
*/
public String getSubtitle() {
return this.subtitle;
public String getSubtitle()
{
return subtitle;
}
/**
@ -160,8 +170,9 @@ public class HackTitleManager {
* @param color
* Chat color
*/
public void setTitleColor(final ChatColor color) {
this.titleColor = color;
public void setTitleColor(final ChatColor color)
{
titleColor = color;
}
/**
@ -170,8 +181,9 @@ public class HackTitleManager {
* @param color
* Chat color
*/
public void setSubtitleColor(final ChatColor color) {
this.subtitleColor = color;
public void setSubtitleColor(final ChatColor color)
{
subtitleColor = color;
}
/**
@ -180,8 +192,9 @@ public class HackTitleManager {
* @param time
* Time
*/
public void setFadeInTime(final int time) {
this.fadeInTime = time;
public void setFadeInTime(final int time)
{
fadeInTime = time;
}
/**
@ -190,8 +203,9 @@ public class HackTitleManager {
* @param time
* Time
*/
public void setFadeOutTime(final int time) {
this.fadeOutTime = time;
public void setFadeOutTime(final int time)
{
fadeOutTime = time;
}
/**
@ -200,22 +214,25 @@ public class HackTitleManager {
* @param time
* Time
*/
public void setStayTime(final int time) {
this.stayTime = time;
public void setStayTime(final int time)
{
stayTime = time;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks() {
this.ticks = true;
public void setTimingsToTicks()
{
ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds() {
this.ticks = false;
public void setTimingsToSeconds()
{
ticks = false;
}
/**
@ -224,28 +241,35 @@ public class HackTitleManager {
* @param player
* Player
*/
public void send(final Player player) throws Exception {
if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) {
public void send(final Player player) throws Exception
{
if ((getProtocolVersion(player) >= 47) && isSpigot() && (packetTitle != null))
{
// First reset previous settings
resetTitle(player);
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], this.fadeInTime * (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20));
Object packet = packetTitle.getConstructor(packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20));
// Send if set
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
if ((fadeInTime != -1) && (fadeOutTime != -1) && (stayTime != -1))
{
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized);
Object serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', title) + "\",color:" + titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (this.subtitle != "") {
if (subtitle != "")
{
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized);
serialized = getMethod(nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', subtitle) + "\",color:" + subtitleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
@ -254,8 +278,10 @@ public class HackTitleManager {
/**
* Broadcast the title to all players
*/
public void broadcast() throws Exception {
for (final Player p : Bukkit.getOnlinePlayers()) {
public void broadcast() throws Exception
{
for (final Player p : Bukkit.getOnlinePlayers())
{
send(p);
}
}
@ -265,16 +291,18 @@ public class HackTitleManager {
*
* @param player
* Player
* @throws Exception
* @throws Exception
*/
public void clearTitle(final Player player) throws Exception {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
public void clearTitle(final Player player) throws Exception
{
if ((getProtocolVersion(player) >= 47) && isSpigot())
{
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]);
final Object packet = packetTitle.getConstructor(packetActions).newInstance(actions[3]);
sendPacket.invoke(connection, packet);
}
}
@ -284,16 +312,18 @@ public class HackTitleManager {
*
* @param player
* Player
* @throws Exception
* @throws Exception
*/
public void resetTitle(final Player player) throws Exception {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
public void resetTitle(final Player player) throws Exception
{
if ((getProtocolVersion(player) >= 47) && isSpigot())
{
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Object[] actions = packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]);
final Object packet = packetTitle.getConstructor(packetActions).newInstance(actions[4]);
sendPacket.invoke(connection, packet);
}
}
@ -304,13 +334,14 @@ public class HackTitleManager {
* @param player
* Player
* @return Protocol version
* @throws Exception
* @throws Exception
*/
private int getProtocolVersion(final Player player) throws Exception {
private int getProtocolVersion(final Player player) throws Exception
{
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object networkManager = getValue("networkManager", connection);
Integer version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager);
final Integer version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager);
return version;
}
@ -319,7 +350,8 @@ public class HackTitleManager {
*
* @return Spigot
*/
private boolean isSpigot() {
private boolean isSpigot()
{
return Bukkit.getVersion().contains("Spigot");
}
@ -330,96 +362,115 @@ public class HackTitleManager {
* Namespace url
* @return Class
*/
private Class<?> getClass(final String namespace) {
try {
private Class<?> getClass(final String namespace)
{
try
{
return Class.forName(namespace);
} catch (final Exception e) {
}
catch (final Exception e)
{}
return null;
}
private Field getField(final String name, final Class<?> clazz) throws Exception {
private Field getField(final String name, final Class<?> clazz) throws Exception
{
return clazz.getDeclaredField(name);
}
private Object getValue(final String name, final Object obj) throws Exception {
private Object getValue(final String name, final Object obj) throws Exception
{
final Field f = getField(name, obj.getClass());
f.setAccessible(true);
return f.get(obj);
}
private Class<?> getPrimitiveType(final Class<?> clazz) {
private Class<?> getPrimitiveType(final Class<?> clazz)
{
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes)
{
final int a = classes != null ? classes.length : 0;
final Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
for (int i = 0; i < a; i++)
{
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o)
{
if (a.length != o.length) { return false; }
for (int i = 0; i < a.length; i++)
{
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) { return false; }
}
return true;
}
private Object getHandle(final Object obj) {
try {
private Object getHandle(final Object obj)
{
try
{
return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (final Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) {
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes)
{
final Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (final Method m : clazz.getMethods()) {
for (final Method m : clazz.getMethods())
{
final Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
if (m.getName().equals(name) && equalsTypeArray(types, t)) { return m; }
}
return null;
}
private String getVersion() {
private String getVersion()
{
final String name = Bukkit.getServer().getClass().getPackage().getName();
final String version = name.substring(name.lastIndexOf('.') + 1) + ".";
return version;
}
private Class<?> getNMSClass(final String className) throws ClassNotFoundException {
private Class<?> getNMSClass(final String className) throws ClassNotFoundException
{
final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
clazz = Class.forName(fullName);
return clazz;
}
private Field getField(final Class<?> clazz, final String name) {
try {
private Field getField(final Class<?> clazz, final String name)
{
try
{
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (final Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
for (final Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args)
{
for (final Method m : clazz.getMethods())
{
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes())))
{
m.setAccessible(true);
return m;
}
@ -427,13 +478,14 @@ public class HackTitleManager {
return null;
}
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2)
{
boolean equal = true;
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
if (l1.length != l2.length) { return false; }
for (int i = 0; i < l1.length; i++)
{
if (l1[i] != l2[i])
{
equal = false;
break;
}

View File

@ -13,50 +13,61 @@ import com.intellectualcrafters.plot.util.ChatManager;
import com.plotsquared.bukkit.chat.FancyMessage;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class BukkitChatManager extends ChatManager<FancyMessage> {
public class BukkitChatManager extends ChatManager<FancyMessage>
{
@Override
public FancyMessage builder() {
public FancyMessage builder()
{
return new FancyMessage("");
}
@Override
public void color(PlotMessage m, String color) {
public void color(final PlotMessage m, final String color)
{
m.$(this).color(ChatColor.getByChar(C.color(color).substring(1)));
}
@Override
public void tooltip(PlotMessage m, PlotMessage... tooltips) {
List<FancyMessage> lines = new ArrayList<>();
for (PlotMessage tooltip : tooltips) {
public void tooltip(final PlotMessage m, final PlotMessage... tooltips)
{
final List<FancyMessage> lines = new ArrayList<>();
for (final PlotMessage tooltip : tooltips)
{
lines.add(tooltip.$(this));
}
m.$(this).formattedTooltip(lines);
}
@Override
public void command(PlotMessage m, String command) {
public void command(final PlotMessage m, final String command)
{
m.$(this).command(command);
}
@Override
public void text(PlotMessage m, String text) {
public void text(final PlotMessage m, final String text)
{
m.$(this).then(ChatColor.stripColor(text));
}
@Override
public void send(PlotMessage m, PlotPlayer player) {
if (ConsolePlayer.isConsole(player)) {
public void send(final PlotMessage m, final PlotPlayer player)
{
if (ConsolePlayer.isConsole(player))
{
player.sendMessage(m.$(this).toOldMessageFormat());
}
else {
else
{
m.$(this).send(((BukkitPlayer) player).player);
}
}
@Override
public void suggest(PlotMessage m, String command) {
public void suggest(final PlotMessage m, final String command)
{
m.$(this).suggest(command);
}
}

View File

@ -1,85 +1,85 @@
package com.plotsquared.bukkit.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.commands.DebugUUID;
import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.StringComparison;
import com.plotsquared.general.commands.Command;
/**
* Created 2015-02-20 for PlotSquared
*
* @author Citymonstret
*/
public class BukkitCommand implements CommandExecutor, TabCompleter {
public BukkitCommand() {
MainCommand.getInstance().addCommand(new DebugUUID());
}
@Override
public boolean onCommand(final CommandSender commandSender, final org.bukkit.command.Command command, final String commandLabel, final String[] args) {
if (commandSender instanceof Player) {
return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), commandLabel, args);
}
return MainCommand.onCommand(ConsolePlayer.getConsole(), commandLabel, args);
}
@Override
public List<String> onTabComplete(final CommandSender commandSender, final org.bukkit.command.Command command, final String s, final String[] strings) {
if (!(commandSender instanceof Player)) {
return null;
}
final PlotPlayer player = BukkitUtil.getPlayer((Player) commandSender);
if (strings.length < 1) {
if ((strings.length == 0) || "plots".startsWith(s)) {
return Collections.singletonList("plots");
}
}
if (strings.length > 1) {
return null;
}
if (!command.getLabel().equalsIgnoreCase("plots")) {
return null;
}
final Set<String> tabOptions = new HashSet<>();
ArrayList<Command<PlotPlayer>> commands = MainCommand.getInstance().getCommands();
String best = new StringComparison(strings[0], commands).getBestMatch();
tabOptions.add(best);
final String arg = strings[0].toLowerCase();
for (final Command<PlotPlayer> cmd : MainCommand.getInstance().getCommands()) {
String label = cmd.getCommand();
if (!label.equalsIgnoreCase(best)) {
if (label.startsWith(arg)) {
if (Permissions.hasPermission(player, cmd.getPermission())) {
tabOptions.add(cmd.getCommand());
} else if (cmd.getAliases().size() > 0) {
for (String alias : cmd.getAliases()) {
if (alias.startsWith(arg)) {
tabOptions.add(label);
break;
}
}
}
}
}
}
if (tabOptions.size() > 0) {
return new ArrayList<>(tabOptions);
}
return null;
}
}
package com.plotsquared.bukkit.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.commands.DebugUUID;
import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.StringComparison;
import com.plotsquared.general.commands.Command;
/**
* Created 2015-02-20 for PlotSquared
*
*/
public class BukkitCommand implements CommandExecutor, TabCompleter
{
public BukkitCommand()
{
MainCommand.getInstance().addCommand(new DebugUUID());
}
@Override
public boolean onCommand(final CommandSender commandSender, final org.bukkit.command.Command command, final String commandLabel, final String[] args)
{
if (commandSender instanceof Player) { return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), commandLabel, args); }
return MainCommand.onCommand(ConsolePlayer.getConsole(), commandLabel, args);
}
@Override
public List<String> onTabComplete(final CommandSender commandSender, final org.bukkit.command.Command command, final String s, final String[] strings)
{
if (!(commandSender instanceof Player)) { return null; }
final PlotPlayer player = BukkitUtil.getPlayer((Player) commandSender);
if (strings.length < 1)
{
if ((strings.length == 0) || "plots".startsWith(s)) { return Collections.singletonList("plots"); }
}
if (strings.length > 1) { return null; }
if (!command.getLabel().equalsIgnoreCase("plots")) { return null; }
final Set<String> tabOptions = new HashSet<>();
final ArrayList<Command<PlotPlayer>> commands = MainCommand.getInstance().getCommands();
final String best = new StringComparison(strings[0], commands).getBestMatch();
tabOptions.add(best);
final String arg = strings[0].toLowerCase();
for (final Command<PlotPlayer> cmd : MainCommand.getInstance().getCommands())
{
final String label = cmd.getCommand();
if (!label.equalsIgnoreCase(best))
{
if (label.startsWith(arg))
{
if (Permissions.hasPermission(player, cmd.getPermission()))
{
tabOptions.add(cmd.getCommand());
}
else if (cmd.getAliases().size() > 0)
{
for (final String alias : cmd.getAliases())
{
if (alias.startsWith(arg))
{
tabOptions.add(label);
break;
}
}
}
}
}
}
if (tabOptions.size() > 0) { return new ArrayList<>(tabOptions); }
return null;
}

View File

@ -4,7 +4,6 @@ import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.plugin.RegisteredServiceProvider;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
@ -12,33 +11,39 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.EconHandler;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
public class BukkitEconHandler extends EconHandler {
public class BukkitEconHandler extends EconHandler
{
private Economy econ;
private Permission perms;
public Economy getEconomy() {
public Economy getEconomy()
{
init();
return econ;
}
public Permission getPermissions() {
public Permission getPermissions()
{
init();
return perms;
}
public boolean init() {
if (econ == null || perms == null) {
public boolean init()
{
if ((econ == null) || (perms == null))
{
setupPermissions();
setupEconomy();
}
return econ != null && perms != null;
return (econ != null) && (perms != null);
}
private boolean setupPermissions()
{
RegisteredServiceProvider<Permission> permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null) {
final RegisteredServiceProvider<Permission> permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null)
{
perms = permissionProvider.getProvider();
}
return (perms != null);
@ -46,49 +51,56 @@ public class BukkitEconHandler extends EconHandler {
private boolean setupEconomy()
{
RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
final RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null)
{
econ = economyProvider.getProvider();
}
return (econ != null);
}
@Override
public double getMoney(PlotPlayer player) {
double bal = super.getMoney(player);
if (Double.isNaN(bal)) {
return econ.getBalance(player.getName());
}
public double getMoney(final PlotPlayer player)
{
final double bal = super.getMoney(player);
if (Double.isNaN(bal)) { return econ.getBalance(player.getName()); }
return bal;
}
@Override
public void withdrawMoney(PlotPlayer player, double amount) {
public void withdrawMoney(final PlotPlayer player, final double amount)
{
econ.withdrawPlayer(player.getName(), amount);
}
@Override
public void depositMoney(PlotPlayer player, double amount) {
public void depositMoney(final PlotPlayer player, final double amount)
{
econ.depositPlayer(player.getName(), amount);
}
@Override
public void depositMoney(OfflinePlotPlayer player, double amount) {
public void depositMoney(final OfflinePlotPlayer player, final double amount)
{
econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount);
}
@Override
public void setPermission(String world, String player, String perm, boolean value) {
if (value) {
public void setPermission(final String world, final String player, final String perm, final boolean value)
{
if (value)
{
perms.playerAdd(world, player, perm);
}
else {
else
{
perms.playerRemove(world, player, perm);
}
}
@Override
public boolean hasPermission(String world, String player, String perm) {
public boolean hasPermission(final String world, final String player, final String perm)
{
return perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm);
}
}

View File

@ -33,98 +33,112 @@ import com.plotsquared.bukkit.events.PlotRateEvent;
import com.plotsquared.bukkit.events.PlotUnlinkEvent;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class BukkitEventUtil extends EventUtil {
public class BukkitEventUtil extends EventUtil
{
public Player getPlayer(PlotPlayer player) {
if (player instanceof BukkitPlayer) {
return ((BukkitPlayer) player).player;
}
public Player getPlayer(final PlotPlayer player)
{
if (player instanceof BukkitPlayer) { return ((BukkitPlayer) player).player; }
return null;
}
public boolean callEvent(Event event) {
public boolean callEvent(final Event event)
{
Bukkit.getServer().getPluginManager().callEvent(event);
if (event instanceof Cancellable) {
return !((Cancellable) event).isCancelled();
}
if (event instanceof Cancellable) { return !((Cancellable) event).isCancelled(); }
return true;
}
@Override
public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) {
public boolean callClaim(final PlotPlayer player, final Plot plot, final boolean auto)
{
return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto));
}
@Override
public boolean callTeleport(PlotPlayer player, Location from, Plot plot) {
public boolean callTeleport(final PlotPlayer player, final Location from, final Plot plot)
{
return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot));
}
@Override
public boolean callClear(String world, PlotId id) {
public boolean callClear(final String world, final PlotId id)
{
return callEvent(new PlotClearEvent(world, id));
}
@Override
public void callDelete(String world, PlotId id) {
public void callDelete(final String world, final PlotId id)
{
callEvent(new PlotDeleteEvent(world, id));
}
@Override
public boolean callFlagAdd(Flag flag, Plot plot) {
public boolean callFlagAdd(final Flag flag, final Plot plot)
{
return callEvent(new PlotFlagAddEvent(flag, plot));
}
@Override
public boolean callFlagRemove(Flag flag, Plot plot) {
public boolean callFlagRemove(final Flag flag, final Plot plot)
{
return callEvent(new PlotFlagRemoveEvent(flag, plot));
}
@Override
public boolean callMerge(String world, Plot plot, ArrayList<PlotId> plots) {
public boolean callMerge(final String world, final Plot plot, final ArrayList<PlotId> plots)
{
return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(world), plot, plots));
}
@Override
public boolean callUnlink(String world, ArrayList<PlotId> plots) {
public boolean callUnlink(final String world, final ArrayList<PlotId> plots)
{
return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(world), plots));
}
@Override
public void callEntry(PlotPlayer player, Plot plot) {
public void callEntry(final PlotPlayer player, final Plot plot)
{
callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot));
}
@Override
public void callLeave(PlotPlayer player, Plot plot) {
public void callLeave(final PlotPlayer player, final Plot plot)
{
callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot));
}
@Override
public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
public void callDenied(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added)
{
callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added));
}
@Override
public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
public void callTrusted(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added)
{
callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added));
}
@Override
public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
public void callMember(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added)
{
callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added));
}
@Override
public boolean callFlagRemove(Flag flag, PlotCluster cluster) {
public boolean callFlagRemove(final Flag flag, final PlotCluster cluster)
{
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}
@Override
public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
PlotRateEvent event = new PlotRateEvent(player, rating, plot);
public Rating callRating(final PlotPlayer player, final Plot plot, final Rating rating)
{
final PlotRateEvent event = new PlotRateEvent(player, rating, plot);
Bukkit.getServer().getPluginManager().callEvent(event);
return event.getRating();
}
}

View File

@ -15,11 +15,9 @@ import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.material.Directional;
import org.bukkit.material.MaterialData;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotAnalysis;
@ -30,10 +28,12 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.TaskManager;
public class BukkitHybridUtils extends HybridUtils {
public class BukkitHybridUtils extends HybridUtils
{
@Override
public void analyzePlot(final Plot plot, final RunnableVal<PlotAnalysis> whenDone) {
public void analyzePlot(final Plot plot, final RunnableVal<PlotAnalysis> whenDone)
{
// int diff, int variety, int verticies, int rotation, int height_sd
/*
* diff: compare to base by looping through all blocks
@ -46,15 +46,28 @@ public class BukkitHybridUtils extends HybridUtils {
* - recheck each block
*
*/
TaskManager.runTaskAsync(new Runnable() {
TaskManager.runTaskAsync(new Runnable()
{
@Override
public void run() {
public void run()
{
final World world = Bukkit.getWorld(plot.world);
final ChunkGenerator gen = world.getGenerator();
if (gen == null) {
return;
return;
}
final BiomeGrid base = new BiomeGrid() { @Override public void setBiome(int a, int b, Biome c) {} @Override public Biome getBiome(int a, int b) {return null;}};
final BiomeGrid base = new BiomeGrid()
{
@Override
public void setBiome(final int a, final int b, final Biome c)
{}
@Override
public Biome getBiome(final int a, final int b)
{
return null;
}
};
final Location bot = MainUtil.getPlotBottomLoc(plot.world, plot.id).add(1, 0, 1);
final Location top = MainUtil.getPlotTopLoc(plot.world, plot.id);
final int bx = bot.getX();
@ -67,92 +80,143 @@ public class BukkitHybridUtils extends HybridUtils {
final int ctz = tz >> 4;
final Random r = new Random();
MainUtil.initCache();
final int width = tx - bx + 1;
final int length = tz - bz + 1;
final int width = (tx - bx) + 1;
final int length = (tz - bz) + 1;
System.gc();
System.gc();
final short[][][] oldblocks = new short[256][width][length];
final short[][][] newblocks = new short[256][width][length];
final Runnable run = new Runnable() {
final Runnable run = new Runnable()
{
@Override
public void run() {
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>() {
public void run()
{
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>()
{
@Override
public void run() {
public void run()
{
// TODO [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge]
int X = value[0];
int Z = value[1];
short[][] result = gen.generateExtBlockSections(world, r, X, Z, base);
int xb = ((X) << 4) - bx;
int zb = ((Z) << 4) - bz;
for (int i = 0; i < result.length; i++) {
if (result[i] == null) {
for (int j = 0; j < 4096; j++) {
int x = MainUtil.x_loc[i][j] + xb;
if (x < 0 || x >= width) continue;
int z = MainUtil.z_loc[i][j] + zb;
if (z < 0 || z >= length) continue;
int y = MainUtil.y_loc[i][j];
final int X = value[0];
final int Z = value[1];
final short[][] result = gen.generateExtBlockSections(world, r, X, Z, base);
final int xb = ((X) << 4) - bx;
final int zb = ((Z) << 4) - bz;
for (int i = 0; i < result.length; i++)
{
if (result[i] == null)
{
for (int j = 0; j < 4096; j++)
{
final int x = MainUtil.x_loc[i][j] + xb;
if ((x < 0) || (x >= width))
{
continue;
}
final int z = MainUtil.z_loc[i][j] + zb;
if ((z < 0) || (z >= length))
{
continue;
}
final int y = MainUtil.y_loc[i][j];
oldblocks[y][x][z] = 0;
}
continue;
}
for (int j = 0; j < result[i].length; j++) {
int x = MainUtil.x_loc[i][j] + xb;
if (x < 0 || x >= width) continue;
int z = MainUtil.z_loc[i][j] + zb;
if (z < 0 || z >= length) continue;
int y = MainUtil.y_loc[i][j];
for (int j = 0; j < result[i].length; j++)
{
final int x = MainUtil.x_loc[i][j] + xb;
if ((x < 0) || (x >= width))
{
continue;
}
final int z = MainUtil.z_loc[i][j] + zb;
if ((z < 0) || (z >= length))
{
continue;
}
final int y = MainUtil.y_loc[i][j];
oldblocks[y][x][z] = result[i][j];
}
}
}
}, new Runnable() {
}, new Runnable()
{
@Override
public void run() {
TaskManager.runTaskAsync(new Runnable() {
public void run()
{
TaskManager.runTaskAsync(new Runnable()
{
@Override
public void run() {
int size = width * length;
int[] changes = new int[size];
int[] faces = new int[size];
int[] data = new int[size];
int[] air = new int[size];
int[] variety = new int[size];
public void run()
{
final int size = width * length;
final int[] changes = new int[size];
final int[] faces = new int[size];
final int[] data = new int[size];
final int[] air = new int[size];
final int[] variety = new int[size];
int i = 0;
for (int x = 0; x < width;x++) {
for (int z = 0; z < length;z++) {
HashSet<Short> types = new HashSet<>();
for (int y = 0; y < 256; y++) {
short old = oldblocks[y][x][z];
short now = newblocks[y][x][z];
if (old != now) {
for (int x = 0; x < width; x++)
{
for (int z = 0; z < length; z++)
{
final HashSet<Short> types = new HashSet<>();
for (int y = 0; y < 256; y++)
{
final short old = oldblocks[y][x][z];
final short now = newblocks[y][x][z];
if (old != now)
{
changes[i]++;
}
if (now == 0) {
if (now == 0)
{
air[i]++;
}
else {
else
{
// check verticies
// modifications_adjacent
if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 && y < 255) {
if (newblocks[y - 1][x][z] == 0) faces[i]++;
if (newblocks[y][x - 1][z] == 0) faces[i]++;
if (newblocks[y][x][z - 1] == 0) faces[i]++;
if (newblocks[y + 1][x][z] == 0) faces[i]++;
if (newblocks[y][x + 1][z] == 0) faces[i]++;
if (newblocks[y][x][z + 1] == 0) faces[i]++;
if ((x > 0) && (z > 0) && (y > 0) && (x < (width - 1)) && (z < (length - 1)) && (y < 255))
{
if (newblocks[y - 1][x][z] == 0)
{
faces[i]++;
}
if (newblocks[y][x - 1][z] == 0)
{
faces[i]++;
}
if (newblocks[y][x][z - 1] == 0)
{
faces[i]++;
}
if (newblocks[y + 1][x][z] == 0)
{
faces[i]++;
}
if (newblocks[y][x + 1][z] == 0)
{
faces[i]++;
}
if (newblocks[y][x][z + 1] == 0)
{
faces[i]++;
}
}
Material material = Material.getMaterial(now);
Class<? extends MaterialData> md = material.getData();
if (md.equals(Directional.class)) {
final Material material = Material.getMaterial(now);
final Class<? extends MaterialData> md = material.getData();
if (md.equals(Directional.class))
{
data[i] += 8;
}
else if (!md.equals(MaterialData.class)) {
else if (!md.equals(MaterialData.class))
{
data[i]++;
}
types.add(now);
@ -164,34 +228,34 @@ public class BukkitHybridUtils extends HybridUtils {
}
// analyze plot
// put in analysis obj
// run whenDone
PlotAnalysis analysis = new PlotAnalysis();
final PlotAnalysis analysis = new PlotAnalysis();
analysis.changes = (int) (MathMan.getMean(changes) * 100);
analysis.faces = (int) (MathMan.getMean(faces) * 100);
analysis.data = (int) (MathMan.getMean(data) * 100);
analysis.air = (int) (MathMan.getMean(air) * 100);
analysis.variety = (int) (MathMan.getMean(variety) * 100);
analysis.changes_sd = (int) (MathMan.getSD(changes, analysis.changes));
analysis.faces_sd = (int) (MathMan.getSD(faces, analysis.faces));
analysis.data_sd = (int) (MathMan.getSD(data, analysis.data));
analysis.air_sd = (int) (MathMan.getSD(air, analysis.air));
analysis.variety_sd = (int) (MathMan.getSD(variety, analysis.variety));
List<Integer> result = new ArrayList<>();
final List<Integer> result = new ArrayList<>();
result.add(analysis.changes);
result.add(analysis.faces);
result.add(analysis.data);
result.add(analysis.air);
result.add(analysis.variety);
result.add(analysis.changes_sd);
result.add(analysis.faces_sd);
result.add(analysis.data_sd);
result.add(analysis.air_sd);
result.add(analysis.variety_sd);
Flag flag = new Flag(FlagManager.getFlag("analysis"), result);
final Flag flag = new Flag(FlagManager.getFlag("analysis"), result);
FlagManager.addPlotFlag(plot, flag);
System.gc();
System.gc();
@ -201,53 +265,84 @@ public class BukkitHybridUtils extends HybridUtils {
});
}
}, 5);
}
};
System.gc();
MainUtil.initCache();
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>() {
ChunkManager.chunkTask(bot, top, new RunnableVal<int[]>()
{
@Override
public void run() {
int X = value[0];
int Z = value[1];
public void run()
{
final int X = value[0];
final int Z = value[1];
world.loadChunk(X, Z);
int minX;
int minZ;
int maxX;
int maxZ;
if (X == cbx) minX = bx & 15;
else minX = 0;
if (Z == cbz) minZ = bz & 15;
else minZ = 0;
if (X == ctx) maxX = tx & 15;
else maxX = 16;
if (Z == ctz) maxZ = tz & 15;
else maxZ = 16;
int cbx = X << 4;
int cbz = Z << 4;
int xb = (cbx) - bx;
int zb = (cbz) - bz;
for (int x = minX; x <= maxX; x++) {
int xx = cbx + x;
for (int z = minZ; z <= maxZ; z++) {
int zz = cbz + z;
for (int y = 0; y < 256; y++) {
Block block = world.getBlockAt(xx, y, zz);
int xr = xb + x;
int zr = zb + z;
if (X == cbx)
{
minX = bx & 15;
}
else
{
minX = 0;
}
if (Z == cbz)
{
minZ = bz & 15;
}
else
{
minZ = 0;
}
if (X == ctx)
{
maxX = tx & 15;
}
else
{
maxX = 16;
}
if (Z == ctz)
{
maxZ = tz & 15;
}
else
{
maxZ = 16;
}
final int cbx = X << 4;
final int cbz = Z << 4;
final int xb = (cbx) - bx;
final int zb = (cbz) - bz;
for (int x = minX; x <= maxX; x++)
{
final int xx = cbx + x;
for (int z = minZ; z <= maxZ; z++)
{
final int zz = cbz + z;
for (int y = 0; y < 256; y++)
{
final Block block = world.getBlockAt(xx, y, zz);
final int xr = xb + x;
final int zr = zb + z;
newblocks[y][xr][zr] = (short) block.getTypeId();
}
}
}
world.unloadChunkRequest(X, Z, true);
}
}, new Runnable() {
}, new Runnable()
{
@Override
public void run() {
public void run()
{
TaskManager.runTaskAsync(run);
}
}, 5);
@ -256,22 +351,29 @@ public class BukkitHybridUtils extends HybridUtils {
}
@Override
public int checkModified(final String worldname, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks) {
public int checkModified(final String worldname, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks)
{
final World world = BukkitUtil.getWorld(worldname);
int count = 0;
for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) {
for (int z = z1; z <= z2; z++) {
for (int y = y1; y <= y2; y++)
{
for (int x = x1; x <= x2; x++)
{
for (int z = z1; z <= z2; z++)
{
final Block block = world.getBlockAt(x, y, z);
final int id = block.getTypeId();
boolean same = false;
for (final PlotBlock p : blocks) {
if (id == p.id) {
for (final PlotBlock p : blocks)
{
if (id == p.id)
{
same = true;
break;
}
}
if (!same) {
if (!same)
{
count++;
}
}
@ -281,16 +383,22 @@ public class BukkitHybridUtils extends HybridUtils {
}
@Override
public int get_ey(final String worldname, final int sx, final int ex, final int sz, final int ez, final int sy) {
public int get_ey(final String worldname, final int sx, final int ex, final int sz, final int ez, final int sy)
{
final World world = BukkitUtil.getWorld(worldname);
final int maxY = world.getMaxHeight();
int ey = sy;
for (int x = sx; x <= ex; x++) {
for (int z = sz; z <= ez; z++) {
for (int y = sy; y < maxY; y++) {
if (y > ey) {
for (int x = sx; x <= ex; x++)
{
for (int z = sz; z <= ez; z++)
{
for (int y = sy; y < maxY; y++)
{
if (y > ey)
{
final Block block = world.getBlockAt(x, y, z);
if (block.getTypeId() != 0) {
if (block.getTypeId() != 0)
{
ey = y;
}
}

View File

@ -18,16 +18,20 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.InventoryUtil;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class BukkitInventoryUtil extends InventoryUtil {
public class BukkitInventoryUtil extends InventoryUtil
{
@Override
public void open(PlotInventory inv) {
BukkitPlayer bp = ((BukkitPlayer) inv.player);
Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle());
PlotItemStack[] items = inv.getItems();
for (int i = 0; i < inv.size * 9; i++) {
PlotItemStack item = items[i];
if (item != null) {
public void open(final PlotInventory inv)
{
final BukkitPlayer bp = ((BukkitPlayer) inv.player);
final Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle());
final PlotItemStack[] items = inv.getItems();
for (int i = 0; i < (inv.size * 9); i++)
{
final PlotItemStack item = items[i];
if (item != null)
{
inventory.setItem(i, getItem(item));
}
}
@ -36,92 +40,97 @@ public class BukkitInventoryUtil extends InventoryUtil {
}
@Override
public void close(PlotInventory inv) {
if (!inv.isOpen()) {
return;
}
public void close(final PlotInventory inv)
{
if (!inv.isOpen()) { return; }
inv.player.deleteMeta("inventory");
BukkitPlayer bp = ((BukkitPlayer) inv.player);
final BukkitPlayer bp = ((BukkitPlayer) inv.player);
bp.player.closeInventory();
}
@Override
public void setItem(PlotInventory inv, int index, PlotItemStack item) {
BukkitPlayer bp = ((BukkitPlayer) inv.player);
InventoryView opened = bp.player.getOpenInventory();
if (!inv.isOpen()) {
return;
}
public void setItem(final PlotInventory inv, final int index, final PlotItemStack item)
{
final BukkitPlayer bp = ((BukkitPlayer) inv.player);
final InventoryView opened = bp.player.getOpenInventory();
if (!inv.isOpen()) { return; }
opened.setItem(index, getItem(item));
bp.player.updateInventory();
}
public PlotItemStack getItem(ItemStack item ) {
if (item == null) {
return null;
}
int id = item.getTypeId();
short data = item.getDurability();
int amount = item.getAmount();
public PlotItemStack getItem(final ItemStack item)
{
if (item == null) { return null; }
final int id = item.getTypeId();
final short data = item.getDurability();
final int amount = item.getAmount();
String name = null;
String[] lore = null;
if (item.hasItemMeta()) {
ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName()) {
if (item.hasItemMeta())
{
final ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName())
{
name = meta.getDisplayName();
}
if (meta.hasLore()) {
List<String> itemLore = meta.getLore();
if (meta.hasLore())
{
final List<String> itemLore = meta.getLore();
lore = itemLore.toArray(new String[itemLore.size()]);
}
}
return new PlotItemStack(id, data, amount, name, lore);
}
public static ItemStack getItem(PlotItemStack item) {
if (item == null) {
return null;
}
ItemStack stack = new ItemStack(item.id, item.amount, item.data);
public static ItemStack getItem(final PlotItemStack item)
{
if (item == null) { return null; }
final ItemStack stack = new ItemStack(item.id, item.amount, item.data);
ItemMeta meta = null;
if (item.name != null) {
if (item.name != null)
{
meta = stack.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', item.name));
}
if (item.lore != null) {
if (meta == null) {
if (item.lore != null)
{
if (meta == null)
{
meta = stack.getItemMeta();
}
List<String> lore = new ArrayList<>();
for (String entry : item.lore) {
final List<String> lore = new ArrayList<>();
for (final String entry : item.lore)
{
lore.add(ChatColor.translateAlternateColorCodes('&', entry));
}
meta.setLore(lore);
}
if (meta != null) {
if (meta != null)
{
stack.setItemMeta(meta);
}
return stack;
}
@Override
public PlotItemStack[] getItems(PlotPlayer player) {
BukkitPlayer bp = ((BukkitPlayer) player);
PlayerInventory inv = bp.player.getInventory();
PlotItemStack[] items = new PlotItemStack[36];
for (int i = 0; i < 36; i++) {
public PlotItemStack[] getItems(final PlotPlayer player)
{
final BukkitPlayer bp = ((BukkitPlayer) player);
final PlayerInventory inv = bp.player.getInventory();
final PlotItemStack[] items = new PlotItemStack[36];
for (int i = 0; i < 36; i++)
{
items[i] = getItem(inv.getItem(i));
}
return items;
}
@Override
public boolean isOpen(PlotInventory inv) {
if (!inv.isOpen()) {
return false;
}
BukkitPlayer bp = ((BukkitPlayer) inv.player);
InventoryView opened = bp.player.getOpenInventory();
return (inv.isOpen() && opened.getType() == InventoryType.CRAFTING && opened.getTitle() == null);
public boolean isOpen(final PlotInventory inv)
{
if (!inv.isOpen()) { return false; }
final BukkitPlayer bp = ((BukkitPlayer) inv.player);
final InventoryView opened = bp.player.getOpenInventory();
return (inv.isOpen() && (opened.getType() == InventoryType.CRAFTING) && (opened.getTitle() == null));
}
}

View File

@ -5,48 +5,53 @@ import java.util.List;
import org.bukkit.ChatColor;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotMessage;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ChatManager;
import com.plotsquared.bukkit.chat.FancyMessage;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class BukkitPlainChatManager extends ChatManager<List<StringBuilder>> {
public class BukkitPlainChatManager extends ChatManager<List<StringBuilder>>
{
@Override
public List<StringBuilder> builder() {
public List<StringBuilder> builder()
{
return new ArrayList<StringBuilder>();
}
@Override
public void color(PlotMessage m, String color) {
List<StringBuilder> parts = m.$(this);
public void color(final PlotMessage m, final String color)
{
final List<StringBuilder> parts = m.$(this);
parts.get(parts.size() - 1).insert(0, color);
}
@Override
public void tooltip(PlotMessage m, PlotMessage... tooltips) {}
public void tooltip(final PlotMessage m, final PlotMessage... tooltips)
{}
@Override
public void command(PlotMessage m, String command) {}
public void command(final PlotMessage m, final String command)
{}
@Override
public void text(PlotMessage m, String text) {
public void text(final PlotMessage m, final String text)
{
m.$(this).add(new StringBuilder(ChatColor.stripColor(text)));
}
@Override
public void send(PlotMessage m, PlotPlayer player) {
StringBuilder built = new StringBuilder();
for (StringBuilder sb : m.$(this)) {
public void send(final PlotMessage m, final PlotPlayer player)
{
final StringBuilder built = new StringBuilder();
for (final StringBuilder sb : m.$(this))
{
built.append(sb);
}
player.sendMessage(built.toString());
}
@Override
public void suggest(PlotMessage m, String command) {}
public void suggest(final PlotMessage m, final String command)
{}
}

View File

@ -37,7 +37,8 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
/**
* Functions involving players, plots and locations.
*/
public class BukkitPlayerFunctions {
public class BukkitPlayerFunctions
{
/*
* =========== NOTICE ================
@ -51,29 +52,31 @@ public class BukkitPlayerFunctions {
* @param plot
* @param isDelete
*/
public static void clear(final Player player, final String world, final Plot plot, final boolean isDelete) {
public static void clear(final Player player, final String world, final Plot plot, final boolean isDelete)
{
final long start = System.currentTimeMillis();
final Runnable whenDone = new Runnable() {
final Runnable whenDone = new Runnable()
{
@Override
public void run() {
if ((player != null) && player.isOnline()) {
public void run()
{
if ((player != null) && player.isOnline())
{
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.CLEARING_DONE, "" + (System.currentTimeMillis() - start));
}
}
};
if (!MainUtil.clearAsPlayer(plot, isDelete, whenDone)) {
if (!MainUtil.clearAsPlayer(plot, isDelete, whenDone))
{
MainUtil.sendMessage(null, C.WAIT_FOR_TIMER);
}
}
public static String getPlayerName(final UUID uuid) {
if (uuid == null) {
return "unknown";
}
public static String getPlayerName(final UUID uuid)
{
if (uuid == null) { return "unknown"; }
final String name = UUIDHandler.getName(uuid);
if (name == null) {
return "unknown";
}
if (name == null) { return "unknown"; }
return name;
}
@ -82,22 +85,28 @@ public class BukkitPlayerFunctions {
*
* @return boolean
*/
public static boolean isInPlot(final Player player) {
public static boolean isInPlot(final Player player)
{
return getCurrentPlot(player) != null;
}
public static ArrayList<PlotId> getMaxPlotSelectionIds(final String world, PlotId pos1, PlotId pos2) {
public static ArrayList<PlotId> getMaxPlotSelectionIds(final String world, PlotId pos1, PlotId pos2)
{
final Plot plot1 = PS.get().getPlot(world, pos1);
final Plot plot2 = PS.get().getPlot(world, pos2);
if (plot1 != null) {
if (plot1 != null)
{
pos1 = MainUtil.getBottomPlot(plot1).id;
}
if (plot2 != null) {
if (plot2 != null)
{
pos2 = MainUtil.getTopPlot(plot2).id;
}
final ArrayList<PlotId> myplots = new ArrayList<>();
for (int x = pos1.x; x <= pos2.x; x++) {
for (int y = pos1.y; y <= pos2.y; y++) {
for (int x = pos1.x; x <= pos2.x; x++)
{
for (int y = pos1.y; y <= pos2.y; y++)
{
myplots.add(new PlotId(x, y));
}
}
@ -111,15 +120,12 @@ public class BukkitPlayerFunctions {
*
* @return boolean
*/
public static Plot getCurrentPlot(final Player player) {
if (!PS.get().isPlotWorld(player.getWorld().getName())) {
return null;
}
public static Plot getCurrentPlot(final Player player)
{
if (!PS.get().isPlotWorld(player.getWorld().getName())) { return null; }
final PlotId id = MainUtil.getPlotId(BukkitUtil.getLocation(player));
final String world = player.getWorld().getName();
if (id == null) {
return null;
}
if (id == null) { return null; }
return MainUtil.getPlot(world, id);
}
@ -130,11 +136,10 @@ public class BukkitPlayerFunctions {
*
* @return boolean
*/
public static Set<Plot> getPlayerPlots(final String world, final Player plr) {
public static Set<Plot> getPlayerPlots(final String world, final Player plr)
{
final Set<Plot> p = PS.get().getPlots(world, plr.getName());
if (p == null) {
return new HashSet<>();
}
if (p == null) { return new HashSet<>(); }
return p;
}
}

View File

@ -1,321 +1,348 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import com.intellectualcrafters.jnbt.ByteArrayTag;
import com.intellectualcrafters.jnbt.CompoundTag;
import com.intellectualcrafters.jnbt.IntTag;
import com.intellectualcrafters.jnbt.ListTag;
import com.intellectualcrafters.jnbt.ShortTag;
import com.intellectualcrafters.jnbt.StringTag;
import com.intellectualcrafters.jnbt.Tag;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.object.schematic.StateWrapper;
/**
* Schematic Handler
*
* @author Citymonstret
* @author Empire92
*/
public class BukkitSchematicHandler extends SchematicHandler {
@Override
public void getCompoundTag(final String world, final Location pos1, final Location pos2, final RunnableVal<CompoundTag> whenDone) {
// async
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
// Main positions
final int p1x = pos1.getX();
final int p1z = pos1.getZ();
final int p2x = pos2.getX();
final int p2z = pos2.getZ();
final int bcx = p1x >> 4;
final int bcz = p1z >> 4;
final int tcx = p2x >> 4;
final int tcz = p2z >> 4;
final int sy = pos1.getY();
final int ey = pos2.getY();
final int width = (pos2.getX() - pos1.getX()) + 1;
final int height = (pos2.getY() - pos1.getY()) + 1;
final int length = (pos2.getZ() - pos1.getZ()) + 1;
// Main Schematic tag
final HashMap<String, Tag> schematic = new HashMap<>();
schematic.put("Width", new ShortTag("Width", (short) width));
schematic.put("Length", new ShortTag("Length", (short) length));
schematic.put("Height", new ShortTag("Height", (short) height));
schematic.put("Materials", new StringTag("Materials", "Alpha"));
schematic.put("WEOriginX", new IntTag("WEOriginX", 0));
schematic.put("WEOriginY", new IntTag("WEOriginY", 0));
schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0));
schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0));
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0));
schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0));
// Arrays of data types
final List<Tag> tileEntities = new ArrayList<Tag>();
final byte[] blocks = new byte[width * height * length];
final byte[] blockData = new byte[width * height * length];
// Generate list of chunks
final ArrayList<ChunkLoc> chunks = new ArrayList<ChunkLoc>();
for (int x = bcx; x <= tcx; x++) {
for (int z = bcz; z <= tcz; z++) {
chunks.add(new ChunkLoc(x, z));
}
}
final World worldObj = Bukkit.getWorld(world);
// Main thread
TaskManager.runTask(new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
while (chunks.size() > 0 && System.currentTimeMillis() - start < 20) {
// save schematics
ChunkLoc chunk = chunks.remove(0);
Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z);
if (!bc.load(false)) {
continue;
}
int X = chunk.x;
int Z = chunk.z;
int xxb = X << 4;
int zzb = Z << 4;
int xxt = xxb + 15;
int zzt = zzb + 15;
if (X == bcx) {
xxb = p1x;
}
if (X == tcx) {
xxt = p2x;
}
if (Z == bcz) {
zzb = p1z;
}
if (Z == tcz) {
zzt = p2z;
}
for (int y = sy; y <= Math.min(255, ey); y++) {
int ry = y - sy;
int i1 = (ry * width * length);
for (int z = zzb; z <= zzt; z++) {
int rz = z - p1z;
int i2 = i1 + (rz * width);
for (int x = xxb; x <= xxt; x++) {
int rx = x - p1x;
final int index = i2 + rx;
Block block = worldObj.getBlockAt(x, y, z);
int id = block.getTypeId();
switch (id) {
case 0:
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 24:
case 30:
case 32:
case 37:
case 39:
case 40:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 50:
case 51:
case 55:
case 56:
case 57:
case 58:
case 60:
case 7:
case 8:
case 9:
case 10:
case 11:
case 73:
case 74:
case 75:
case 76:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 121:
case 122:
case 129:
case 133:
case 165:
case 166:
case 169:
case 170:
case 172:
case 173:
case 174:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192: {
break;
}
case 54:
case 130:
case 142:
case 27:
case 137:
case 52:
case 154:
case 84:
case 25:
case 144:
case 138:
case 176:
case 177:
case 63:
case 68:
case 323:
case 117:
case 116:
case 28:
case 66:
case 157:
case 61:
case 62:
case 140:
case 146:
case 149:
case 150:
case 158:
case 23:
case 123:
case 124:
case 29:
case 33:
case 151:
case 178: {
// TODO implement fully
BlockState state = block.getState();
if (state != null) {
StateWrapper wrapper = new StateWrapper(state);
CompoundTag rawTag = wrapper.getTag();
if (rawTag != null) {
Map<String, Tag> values = new HashMap<String, Tag>();
for (Entry<String, Tag> entry : rawTag.getValue().entrySet()) {
values.put(entry.getKey(), entry.getValue());
}
values.put("id", new StringTag("id", wrapper.getId()));
values.put("x", new IntTag("x", x));
values.put("y", new IntTag("y", y));
values.put("z", new IntTag("z", z));
CompoundTag tileEntityTag = new CompoundTag(values);
tileEntities.add(tileEntityTag);
}
}
}
default: {
blockData[index] = block.getData();
}
}
// For optimization reasons, we are not supporting custom data types
// Especially since the most likely reason beyond this range is modded servers in which the blocks have NBT
// if (id > 255) {
// if (addBlocks == null) {
// addBlocks = new byte[(blocks.length >> 1) + 1];
// }
// addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? (addBlocks[index >> 1] & 0xF0) | ((id >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((id >> 8) & 0xF) << 4));
// }
blocks[index] = (byte) id;
}
}
}
}
if (chunks.size() != 0) {
TaskManager.runTaskLater(this, 1);
} else {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
schematic.put("Blocks", new ByteArrayTag("Blocks", blocks));
schematic.put("Data", new ByteArrayTag("Data", blockData));
schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList<Tag>()));
schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, tileEntities));
whenDone.value = new CompoundTag("Schematic", schematic);
TaskManager.runTask(whenDone);
System.gc();
System.gc();
}
});
}
}
});
}
});
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import com.intellectualcrafters.jnbt.ByteArrayTag;
import com.intellectualcrafters.jnbt.CompoundTag;
import com.intellectualcrafters.jnbt.IntTag;
import com.intellectualcrafters.jnbt.ListTag;
import com.intellectualcrafters.jnbt.ShortTag;
import com.intellectualcrafters.jnbt.StringTag;
import com.intellectualcrafters.jnbt.Tag;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.object.schematic.StateWrapper;
/**
* Schematic Handler
*
*/
public class BukkitSchematicHandler extends SchematicHandler
{
@Override
public void getCompoundTag(final String world, final Location pos1, final Location pos2, final RunnableVal<CompoundTag> whenDone)
{
// async
TaskManager.runTaskAsync(new Runnable()
{
@Override
public void run()
{
// Main positions
final int p1x = pos1.getX();
final int p1z = pos1.getZ();
final int p2x = pos2.getX();
final int p2z = pos2.getZ();
final int bcx = p1x >> 4;
final int bcz = p1z >> 4;
final int tcx = p2x >> 4;
final int tcz = p2z >> 4;
final int sy = pos1.getY();
final int ey = pos2.getY();
final int width = (pos2.getX() - pos1.getX()) + 1;
final int height = (pos2.getY() - pos1.getY()) + 1;
final int length = (pos2.getZ() - pos1.getZ()) + 1;
// Main Schematic tag
final HashMap<String, Tag> schematic = new HashMap<>();
schematic.put("Width", new ShortTag("Width", (short) width));
schematic.put("Length", new ShortTag("Length", (short) length));
schematic.put("Height", new ShortTag("Height", (short) height));
schematic.put("Materials", new StringTag("Materials", "Alpha"));
schematic.put("WEOriginX", new IntTag("WEOriginX", 0));
schematic.put("WEOriginY", new IntTag("WEOriginY", 0));
schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0));
schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0));
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0));
schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0));
// Arrays of data types
final List<Tag> tileEntities = new ArrayList<Tag>();
final byte[] blocks = new byte[width * height * length];
final byte[] blockData = new byte[width * height * length];
// Generate list of chunks
final ArrayList<ChunkLoc> chunks = new ArrayList<ChunkLoc>();
for (int x = bcx; x <= tcx; x++)
{
for (int z = bcz; z <= tcz; z++)
{
chunks.add(new ChunkLoc(x, z));
}
}
final World worldObj = Bukkit.getWorld(world);
// Main thread
TaskManager.runTask(new Runnable()
{
@Override
public void run()
{
final long start = System.currentTimeMillis();
while ((chunks.size() > 0) && ((System.currentTimeMillis() - start) < 20))
{
// save schematics
final ChunkLoc chunk = chunks.remove(0);
final Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z);
if (!bc.load(false))
{
continue;
}
final int X = chunk.x;
final int Z = chunk.z;
int xxb = X << 4;
int zzb = Z << 4;
int xxt = xxb + 15;
int zzt = zzb + 15;
if (X == bcx)
{
xxb = p1x;
}
if (X == tcx)
{
xxt = p2x;
}
if (Z == bcz)
{
zzb = p1z;
}
if (Z == tcz)
{
zzt = p2z;
}
for (int y = sy; y <= Math.min(255, ey); y++)
{
final int ry = y - sy;
final int i1 = (ry * width * length);
for (int z = zzb; z <= zzt; z++)
{
final int rz = z - p1z;
final int i2 = i1 + (rz * width);
for (int x = xxb; x <= xxt; x++)
{
final int rx = x - p1x;
final int index = i2 + rx;
final Block block = worldObj.getBlockAt(x, y, z);
final int id = block.getTypeId();
switch (id)
{
case 0:
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 24:
case 30:
case 32:
case 37:
case 39:
case 40:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 50:
case 51:
case 55:
case 56:
case 57:
case 58:
case 60:
case 7:
case 8:
case 9:
case 10:
case 11:
case 73:
case 74:
case 75:
case 76:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 121:
case 122:
case 129:
case 133:
case 165:
case 166:
case 169:
case 170:
case 172:
case 173:
case 174:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192:
{
break;
}
case 54:
case 130:
case 142:
case 27:
case 137:
case 52:
case 154:
case 84:
case 25:
case 144:
case 138:
case 176:
case 177:
case 63:
case 68:
case 323:
case 117:
case 116:
case 28:
case 66:
case 157:
case 61:
case 62:
case 140:
case 146:
case 149:
case 150:
case 158:
case 23:
case 123:
case 124:
case 29:
case 33:
case 151:
case 178:
{
// TODO implement fully
final BlockState state = block.getState();
if (state != null)
{
final StateWrapper wrapper = new StateWrapper(state);
final CompoundTag rawTag = wrapper.getTag();
if (rawTag != null)
{
final Map<String, Tag> values = new HashMap<String, Tag>();
for (final Entry<String, Tag> entry : rawTag.getValue().entrySet())
{
values.put(entry.getKey(), entry.getValue());
}
values.put("id", new StringTag("id", wrapper.getId()));
values.put("x", new IntTag("x", x));
values.put("y", new IntTag("y", y));
values.put("z", new IntTag("z", z));
final CompoundTag tileEntityTag = new CompoundTag(values);
tileEntities.add(tileEntityTag);
}
}
}
default:
{
blockData[index] = block.getData();
}
}
// For optimization reasons, we are not supporting custom data types
// Especially since the most likely reason beyond this range is modded servers in which the blocks have NBT
// if (id > 255) {
// if (addBlocks == null) {
// addBlocks = new byte[(blocks.length >> 1) + 1];
// }
// addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? (addBlocks[index >> 1] & 0xF0) | ((id >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((id >> 8) & 0xF) << 4));
// }
blocks[index] = (byte) id;
}
}
}
}
if (chunks.size() != 0)
{
TaskManager.runTaskLater(this, 1);
}
else
{
TaskManager.runTaskAsync(new Runnable()
{
@Override
public void run()
{
schematic.put("Blocks", new ByteArrayTag("Blocks", blocks));
schematic.put("Data", new ByteArrayTag("Data", blockData));
schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList<Tag>()));
schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, tileEntities));
whenDone.value = new CompoundTag("Schematic", schematic);
TaskManager.runTask(whenDone);
System.gc();
System.gc();
}
});
}
}
});
}
});

View File

@ -9,18 +9,21 @@ import org.bukkit.World;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.util.BlockUpdateUtil;
public abstract class BukkitSetBlockManager extends BlockUpdateUtil {
public abstract class BukkitSetBlockManager extends BlockUpdateUtil
{
public static BukkitSetBlockManager setBlockManager = null;
public abstract void set(final org.bukkit.World world, final int x, final int y, final int z, final int blockId, final byte data);
public abstract void update(Collection<Chunk> list);
public abstract void update(final Collection<Chunk> list);
@Override
public void update(final String worldname, final Collection<ChunkLoc> chunkLocs) {
public void update(final String worldname, final Collection<ChunkLoc> chunkLocs)
{
final World world = BukkitUtil.getWorld(worldname);
final ArrayList<Chunk> chunks = new ArrayList<Chunk>();
for (final ChunkLoc loc : chunkLocs) {
for (final ChunkLoc loc : chunkLocs)
{
chunks.add(world.getChunkAt(loc.x, loc.z));
}
setBlockManager.update(chunks);

View File

@ -23,126 +23,136 @@ import com.plotsquared.bukkit.generator.AugmentedPopulator;
import com.plotsquared.bukkit.generator.BukkitGeneratorWrapper;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
public class BukkitSetupUtils extends SetupUtils {
public class BukkitSetupUtils extends SetupUtils
{
@Override
public void updateGenerators() {
if (SetupUtils.generators.size() > 0) {
return;
}
public void updateGenerators()
{
if (SetupUtils.generators.size() > 0) { return; }
final String testWorld = "CheckingPlotSquaredGenerator";
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (plugin.isEnabled()) {
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins())
{
if (plugin.isEnabled())
{
final ChunkGenerator generator = plugin.getDefaultWorldGenerator(testWorld, "");
if (generator != null) {
if (generator != null)
{
PS.get().removePlotWorld(testWorld);
final String name = plugin.getDescription().getName();
SetupUtils.generators.put(name, new BukkitGeneratorWrapper("CheckingPlotSquaredGenerator", generator));
SetupUtils.generators.put(name, new BukkitGeneratorWrapper("CheckingPlotSquaredGenerator", generator));
}
}
}
}
@Override
public String setupWorld(final SetupObject object) {
public String setupWorld(final SetupObject object)
{
SetupUtils.manager.updateGenerators();
final ConfigurationNode[] steps = object.step;
final String world = object.world;
for (final ConfigurationNode step : steps) {
for (final ConfigurationNode step : steps)
{
PS.get().config.set("worlds." + world + "." + step.getConstant(), step.getValue());
}
if (object.type != 0) {
if (object.type != 0)
{
PS.get().config.set("worlds." + world + "." + "generator.type", object.type);
PS.get().config.set("worlds." + world + "." + "generator.terrain", object.terrain);
PS.get().config.set("worlds." + world + "." + "generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) {
if ((object.setupGenerator != null) && !object.setupGenerator.equals(object.plotManager))
{
PS.get().config.set("worlds." + world + "." + "generator.init", object.setupGenerator);
}
PlotGenerator<ChunkGenerator> gen = (PlotGenerator<ChunkGenerator>) generators.get(object.setupGenerator);
if (gen != null && gen.generator instanceof BukkitPlotGenerator) {
final PlotGenerator<ChunkGenerator> gen = (PlotGenerator<ChunkGenerator>) generators.get(object.setupGenerator);
if ((gen != null) && (gen.generator instanceof BukkitPlotGenerator))
{
object.setupGenerator = null;
}
}
try {
try
{
PS.get().config.save(PS.get().configFile);
} catch (final IOException e) {
}
catch (final IOException e)
{
e.printStackTrace();
}
if (object.setupGenerator != null) {
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
if (object.setupGenerator != null)
{
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled())
{
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator);
setGenerator(world, object.setupGenerator);
if (Bukkit.getWorld(world) != null) {
return world;
}
if (Bukkit.getWorld(world) != null) { return world; }
}
if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled())
{
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world + " plugin:" + object.setupGenerator);
setGenerator(world, object.setupGenerator);
if (Bukkit.getWorld(world) != null) {
return world;
}
if (Bukkit.getWorld(world) != null) { return world; }
}
final WorldCreator wc = new WorldCreator(object.world);
wc.generator(object.setupGenerator);
wc.environment(Environment.NORMAL);
Bukkit.createWorld(wc);
setGenerator(world, object.setupGenerator);
} else {
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
}
else
{
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled())
{
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal");
if (Bukkit.getWorld(world) != null) {
return world;
}
if (Bukkit.getWorld(world) != null) { return world; }
}
if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled())
{
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world);
if (Bukkit.getWorld(world) != null) {
return world;
}
if (Bukkit.getWorld(world) != null) { return world; }
}
Bukkit.createWorld(new WorldCreator(object.world).environment(World.Environment.NORMAL));
}
return object.world;
}
public void setGenerator(String world, String generator) {
if (Bukkit.getWorlds().size() == 0 || !Bukkit.getWorlds().get(0).getName().equals(world)) {
return;
}
File file = new File("bukkit.yml").getAbsoluteFile();
YamlConfiguration yml = YamlConfiguration.loadConfiguration(file);
public void setGenerator(final String world, final String generator)
{
if ((Bukkit.getWorlds().size() == 0) || !Bukkit.getWorlds().get(0).getName().equals(world)) { return; }
final File file = new File("bukkit.yml").getAbsoluteFile();
final YamlConfiguration yml = YamlConfiguration.loadConfiguration(file);
yml.set("worlds." + world + ".generator", generator);
try {
try
{
yml.save(file);
} catch (IOException e) {
}
catch (final IOException e)
{
e.printStackTrace();
}
}
@Override
public String getGenerator(PlotWorld plotworld) {
if (SetupUtils.generators.size() == 0) {
public String getGenerator(final PlotWorld plotworld)
{
if (SetupUtils.generators.size() == 0)
{
updateGenerators();
}
World world = Bukkit.getWorld(plotworld.worldname);
if (world == null) {
return null;
}
ChunkGenerator generator = world.getGenerator();
if (!(generator instanceof BukkitPlotGenerator)) {
return null;
}
for (Entry<String, PlotGenerator<?>> entry : generators.entrySet()) {
if (entry.getValue().generator.getClass().getName().equals(generator.getClass().getName())) {
return entry.getKey();
}
final World world = Bukkit.getWorld(plotworld.worldname);
if (world == null) { return null; }
final ChunkGenerator generator = world.getGenerator();
if (!(generator instanceof BukkitPlotGenerator)) { return null; }
for (final Entry<String, PlotGenerator<?>> entry : generators.entrySet())
{
if (entry.getValue().generator.getClass().getName().equals(generator.getClass().getName())) { return entry.getKey(); }
}
return null;
}
@Override
public void removePopulator(String world, PlotCluster cluster) {
public void removePopulator(final String world, final PlotCluster cluster)
{
AugmentedPopulator.removePopulator(world, cluster);
}
}

View File

@ -5,40 +5,49 @@ import org.bukkit.Bukkit;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.BukkitMain;
public class BukkitTaskManager extends TaskManager {
public class BukkitTaskManager extends TaskManager
{
@Override
public int taskRepeat(final Runnable r, final int interval) {
public int taskRepeat(final Runnable r, final int interval)
{
return BukkitMain.THIS.getServer().getScheduler().scheduleSyncRepeatingTask(BukkitMain.THIS, r, interval, interval);
}
@Override
public int taskRepeatAsync(final Runnable r, final int interval) {
public int taskRepeatAsync(final Runnable r, final int interval)
{
return BukkitMain.THIS.getServer().getScheduler().scheduleAsyncRepeatingTask(BukkitMain.THIS, r, interval, interval);
}
@Override
public void taskAsync(final Runnable r) {
public void taskAsync(final Runnable r)
{
BukkitMain.THIS.getServer().getScheduler().runTaskAsynchronously(BukkitMain.THIS, r).getTaskId();
}
@Override
public void task(final Runnable r) {
public void task(final Runnable r)
{
BukkitMain.THIS.getServer().getScheduler().runTask(BukkitMain.THIS, r).getTaskId();
}
@Override
public void taskLater(final Runnable r, final int delay) {
public void taskLater(final Runnable r, final int delay)
{
BukkitMain.THIS.getServer().getScheduler().runTaskLater(BukkitMain.THIS, r, delay).getTaskId();
}
@Override
public void taskLaterAsync(final Runnable r, final int delay) {
public void taskLaterAsync(final Runnable r, final int delay)
{
BukkitMain.THIS.getServer().getScheduler().runTaskLaterAsynchronously(BukkitMain.THIS, r, delay);
}
@Override
public void cancelTask(final int task) {
if (task != -1) {
public void cancelTask(final int task)
{
if (task != -1)
{
Bukkit.getScheduler().cancelTask(task);
}
}

View File

@ -1,7 +1,6 @@
package com.plotsquared.bukkit.util;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.bukkit.Bukkit;
@ -35,189 +34,204 @@ import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class BukkitUtil extends BlockManager {
public class BukkitUtil extends BlockManager
{
private static String lastString = null;
private static World lastWorld = null;
private static Player lastPlayer = null;
private static PlotPlayer lastPlotPlayer = null;
public static void removePlayer(final String plr) {
public static void removePlayer(final String plr)
{
lastPlayer = null;
lastPlotPlayer = null;
UUIDHandler.getPlayers().remove(plr);
}
// These weren't being used, but they might be useful later, so I'm just commenting them out
// private static int getMaxHeight(final String world) {
// return getWorld(world).getMaxHeight();
// }
//
// private static void unloadChunkAt(String worldname, int X, int Z, boolean save, boolean safe) {
// final World world = getWorld(worldname);
// world.unloadChunk(X, Z, save, safe);
// }
//
// private static void loadChunkAt(final String worldname, int X, int Z, boolean force) {
// final World world = getWorld(worldname);
// world.loadChunk(X, Z, force);
// }
//
// private static Chunk getChunkAt(final String worldname, final int x, final int z) {
// final World world = getWorld(worldname);
// return world.getChunkAt(x, z);
// }
//
// private static void teleportPlayer(final Player player, final Location loc) {
// final org.bukkit.Location bukkitLoc = new org.bukkit.Location(getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ());
// player.teleport(bukkitLoc);
// }
//
// private static void setBiome(final String worldname, final int pos1_x, final int pos1_z, final int pos2_x, final int pos2_z, final String biome) {
// final Biome b = Biome.valueOf(biome.toUpperCase());
// final World world = getWorld(worldname);
// for (int x = pos1_x; x <= pos2_x; x++) {
// for (int z = pos1_z; z <= pos2_z; z++) {
// if (world.getBiome(x, z) == b) {
// continue;
// }
// world.setBiome(x, z, b);
// }
// }
// }
//
// private static void refreshChunk(final String name, final int x, final int z) {
// World world = getWorld(name);
// world.refreshChunk(x, z);
// world.loadChunk(x, z);
// }
//
// private static void regenerateChunk(final String world, final int x, final int z) {
// World worldObj = getWorld(world);
// Chunk chunk = worldObj.getChunkAt(x, z);
// if (chunk.isLoaded() || chunk.load(false)) {
// ChunkManager.manager.regenerateChunk(world, new ChunkLoc(x, z));
// }
// }
//
// private static Location getLocationFull(final org.bukkit.Location loc) {
// final String world = loc.getWorld().getName();
// return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), loc.getYaw(), loc.getPitch());
// }
//
// private static int getViewDistance() {
// return Bukkit.getViewDistance();
// }
// These weren't being used, but they might be useful later, so I'm just commenting them out
// private static int getMaxHeight(final String world) {
// return getWorld(world).getMaxHeight();
// }
//
// private static void unloadChunkAt(String worldname, int X, int Z, boolean save, boolean safe) {
// final World world = getWorld(worldname);
// world.unloadChunk(X, Z, save, safe);
// }
//
// private static void loadChunkAt(final String worldname, int X, int Z, boolean force) {
// final World world = getWorld(worldname);
// world.loadChunk(X, Z, force);
// }
//
// private static Chunk getChunkAt(final String worldname, final int x, final int z) {
// final World world = getWorld(worldname);
// return world.getChunkAt(x, z);
// }
//
// private static void teleportPlayer(final Player player, final Location loc) {
// final org.bukkit.Location bukkitLoc = new org.bukkit.Location(getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ());
// player.teleport(bukkitLoc);
// }
//
// private static void setBiome(final String worldname, final int pos1_x, final int pos1_z, final int pos2_x, final int pos2_z, final String biome) {
// final Biome b = Biome.valueOf(biome.toUpperCase());
// final World world = getWorld(worldname);
// for (int x = pos1_x; x <= pos2_x; x++) {
// for (int z = pos1_z; z <= pos2_z; z++) {
// if (world.getBiome(x, z) == b) {
// continue;
// }
// world.setBiome(x, z, b);
// }
// }
// }
//
// private static void refreshChunk(final String name, final int x, final int z) {
// World world = getWorld(name);
// world.refreshChunk(x, z);
// world.loadChunk(x, z);
// }
//
// private static void regenerateChunk(final String world, final int x, final int z) {
// World worldObj = getWorld(world);
// Chunk chunk = worldObj.getChunkAt(x, z);
// if (chunk.isLoaded() || chunk.load(false)) {
// ChunkManager.manager.regenerateChunk(world, new ChunkLoc(x, z));
// }
// }
//
// private static Location getLocationFull(final org.bukkit.Location loc) {
// final String world = loc.getWorld().getName();
// return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), loc.getYaw(), loc.getPitch());
// }
//
// private static int getViewDistance() {
// return Bukkit.getViewDistance();
// }
////////////////////////////////////////////////////////////////////////
/////////////////// USED BY EVENT SYSTEM AND SUCH //////////////////////
////////////////////////////////////////////////////////////////////////
public static PlotPlayer getPlayer(final OfflinePlayer op) {
if (op.isOnline()) {
return getPlayer(op.getPlayer());
}
Player player = OfflinePlayerUtil.loadPlayer(op);
public static PlotPlayer getPlayer(final OfflinePlayer op)
{
if (op.isOnline()) { return getPlayer(op.getPlayer()); }
final Player player = OfflinePlayerUtil.loadPlayer(op);
player.loadData();
return new BukkitPlayer(player, true);
}
public static PlotPlayer getPlayer(final Player player) {
if (player == lastPlayer) {
return lastPlotPlayer;
}
String name = player.getName();
PlotPlayer pp = UUIDHandler.getPlayers().get(name);
if (pp != null) {
return pp;
}
public static PlotPlayer getPlayer(final Player player)
{
if (player == lastPlayer) { return lastPlotPlayer; }
final String name = player.getName();
final PlotPlayer pp = UUIDHandler.getPlayers().get(name);
if (pp != null) { return pp; }
lastPlotPlayer = new BukkitPlayer(player);
UUIDHandler.getPlayers().put(name, lastPlotPlayer);
lastPlayer = player;
return lastPlotPlayer;
}
public static Location getLocation(final org.bukkit.Location loc) {
public static Location getLocation(final org.bukkit.Location loc)
{
return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ()));
}
public static org.bukkit.Location getLocation(final Location loc) {
public static org.bukkit.Location getLocation(final Location loc)
{
return new org.bukkit.Location(getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ());
}
public static World getWorld(final String string) {
if (StringMan.isEqual(string, lastString)) {
if (lastWorld != null) {
return lastWorld;
}
public static World getWorld(final String string)
{
if (StringMan.isEqual(string, lastString))
{
if (lastWorld != null) { return lastWorld; }
}
World world = Bukkit.getWorld(string);
final World world = Bukkit.getWorld(string);
lastString = string;
lastWorld = world;
return world;
}
public static String getWorld(final Entity entity) {
public static String getWorld(final Entity entity)
{
return entity.getWorld().getName();
}
public static List<Entity> getEntities(final String worldname) {
public static List<Entity> getEntities(final String worldname)
{
return getWorld(worldname).getEntities();
}
public static Location getLocation(final Entity entity) {
public static Location getLocation(final Entity entity)
{
final org.bukkit.Location loc = entity.getLocation();
final String world = loc.getWorld().getName();
return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
}
public static Location getLocationFull(final Entity entity) {
org.bukkit.Location loc = entity.getLocation();
public static Location getLocationFull(final Entity entity)
{
final org.bukkit.Location loc = entity.getLocation();
return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ()), loc.getYaw(), loc.getPitch());
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////// CLASS ONLY METHODS //////////////////////////////
////////////////////////////////////////////////////////////////////////
private static void setBlock(final World world, final int x, final int y, final int z, final int id, final byte data) {
try {
private static void setBlock(final World world, final int x, final int y, final int z, final int id, final byte data)
{
try
{
BukkitSetBlockManager.setBlockManager.set(world, x, y, z, id, data);
} catch (final Throwable e) {
}
catch (final Throwable e)
{
BukkitSetBlockManager.setBlockManager = new SetBlockSlow();
BukkitSetBlockManager.setBlockManager.set(world, x, y, z, id, data);
}
}
////////////////////////////////////////////////////////////////////////
@Override
public boolean isWorld(final String world) {
public boolean isWorld(final String world)
{
return getWorld(world) != null;
}
@Override
public String getBiome(String world, int x, int z) {
public String getBiome(final String world, final int x, final int z)
{
return getWorld(world).getBiome(x, z).name();
}
@Override
public void functionSetBlocks(final String worldname, final int[] x, final int[] y, final int[] z, final int[] id, final byte[] data) {
public void functionSetBlocks(final String worldname, final int[] x, final int[] y, final int[] z, final int[] id, final byte[] data)
{
final World world = getWorld(worldname);
for (int i = 0; i < x.length; i++) {
for (int i = 0; i < x.length; i++)
{
BukkitUtil.setBlock(world, x[i], y[i], z[i], id[i], data[i]);
}
}
@Override
public void functionSetSign(final String worldname, final int x, final int y, final int z, final String[] lines) {
public void functionSetSign(final String worldname, final int x, final int y, final int z, final String[] lines)
{
final World world = getWorld(worldname);
final Block block = world.getBlockAt(x, y, z);
block.setType(Material.AIR);
block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false);
final BlockState blockstate = block.getState();
if ((blockstate instanceof Sign)) {
for (int i = 0; i < lines.length; i++) {
if ((blockstate instanceof Sign))
{
for (int i = 0; i < lines.length; i++)
{
((Sign) blockstate).setLine(i, lines[i]);
}
((Sign) blockstate).update(true);
@ -225,107 +239,129 @@ public class BukkitUtil extends BlockManager {
}
@Override
public void functionSetBiomes(final String worldname, final int[] x, final int[] z, final String biomeStr) {
public void functionSetBiomes(final String worldname, final int[] x, final int[] z, final String biomeStr)
{
final World world = getWorld(worldname);
final Biome biome = Biome.valueOf(biomeStr.toUpperCase());
for (int i = 0; i < x.length; i++) {
for (int i = 0; i < x.length; i++)
{
world.setBiome(x[i], z[i], biome);
}
}
@Override
public void functionSetBlock(final String worldname, final int x, final int y, final int z, final int id, final byte data) {
public void functionSetBlock(final String worldname, final int x, final int y, final int z, final int id, final byte data)
{
BukkitUtil.setBlock(getWorld(worldname), x, y, z, id, data);
}
@Override
public String[] getSign(final Location loc) {
public String[] getSign(final Location loc)
{
final Block block = getWorld(loc.getWorld()).getBlockAt(loc.getX(), loc.getY(), loc.getZ());
if (block != null) {
if (block.getState() instanceof Sign) {
if (block != null)
{
if (block.getState() instanceof Sign)
{
final Sign sign = (Sign) block.getState();
return sign.getLines();
}
}
return null;
}
@Override
public Location getSpawn(final String world) {
public Location getSpawn(final String world)
{
final org.bukkit.Location temp = getWorld(world).getSpawnLocation();
return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch());
}
@Override
public int getHeighestBlock(String world, int x, int z) {
public int getHeighestBlock(final String world, final int x, final int z)
{
return getWorld(world).getHighestBlockAt(x, z).getY();
}
@Override
public int getBiomeFromString(final String biomeStr) {
try {
public int getBiomeFromString(final String biomeStr)
{
try
{
final Biome biome = Biome.valueOf(biomeStr.toUpperCase());
if (biome == null) {
return -1;
}
if (biome == null) { return -1; }
return Arrays.asList(Biome.values()).indexOf(biome);
}
catch (IllegalArgumentException e) {
catch (final IllegalArgumentException e)
{
return -1;
}
}
@Override
public String[] getBiomeList() {
public String[] getBiomeList()
{
final Biome[] biomes = Biome.values();
final String[] list = new String[biomes.length];
for (int i = 0; i < biomes.length; i++) {
for (int i = 0; i < biomes.length; i++)
{
list[i] = biomes[i].name();
}
return list;
}
@Override
public PlotBlock getPlotBlockFromString(final String block) {
public PlotBlock getPlotBlockFromString(final String block)
{
final Material material = Material.valueOf(block.toUpperCase());
if (material == null) {
return new PlotBlock((short) -1, (byte) 0);
}
if (material == null) { return new PlotBlock((short) -1, (byte) 0); }
return new PlotBlock((short) material.getId(), (byte) 0);
}
@Override
public boolean addItems(String worldname, PlotItem items) {
World world = getWorld(worldname);
Block block = world.getBlockAt(items.x, items.y, items.z);
if (block == null) {
return false;
}
BlockState state = block.getState();
if (state != null && state instanceof InventoryHolder) {
InventoryHolder holder = ((InventoryHolder) state);
Inventory inv = holder.getInventory();
for (int i = 0; i < items.id.length; i++) {
ItemStack item = new ItemStack(items.id[i], items.amount[i], items.data[i]);
public boolean addItems(final String worldname, final PlotItem items)
{
final World world = getWorld(worldname);
final Block block = world.getBlockAt(items.x, items.y, items.z);
if (block == null) { return false; }
final BlockState state = block.getState();
if ((state != null) && (state instanceof InventoryHolder))
{
final InventoryHolder holder = ((InventoryHolder) state);
final Inventory inv = holder.getInventory();
for (int i = 0; i < items.id.length; i++)
{
final ItemStack item = new ItemStack(items.id[i], items.amount[i], items.data[i]);
inv.addItem(item);
}
state.update(true);
return true;
}
return false;
}
@Override
public boolean isBlockSolid(PlotBlock block) {
try {
Material material = Material.getMaterial(block.id);
if (material.isBlock() && material.isSolid() && !material.hasGravity()) {
Class<? extends MaterialData> data = material.getData();
if ((data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding()) || data.equals(Tree.class) || data.equals(Sandstone.class) || data.equals(Wool.class) || data.equals(Step.class) || data.equals(WoodenStep.class)) {
switch (material) {
public boolean isBlockSolid(final PlotBlock block)
{
try
{
final Material material = Material.getMaterial(block.id);
if (material.isBlock() && material.isSolid() && !material.hasGravity())
{
final Class<? extends MaterialData> data = material.getData();
if ((data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding())
|| data.equals(Tree.class)
|| data.equals(Sandstone.class)
|| data.equals(Wool.class)
|| data.equals(Step.class)
|| data.equals(WoodenStep.class))
{
switch (material)
{
case NOTE_BLOCK:
case MOB_SPAWNER: {
case MOB_SPAWNER:
{
return false;
}
default:
@ -335,60 +371,70 @@ public class BukkitUtil extends BlockManager {
}
return false;
}
catch (Exception e) {
catch (final Exception e)
{
return false;
}
}
@Override
public String getClosestMatchingName(PlotBlock block) {
try {
public String getClosestMatchingName(final PlotBlock block)
{
try
{
return Material.getMaterial(block.id).name();
}
catch (Exception e) {
catch (final Exception e)
{
return null;
}
}
@Override
public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try {
public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name)
{
try
{
double match;
short id;
byte data;
String[] split = name.split(":");
if (split.length == 2) {
final String[] split = name.split(":");
if (split.length == 2)
{
data = Byte.parseByte(split[1]);
name = split[0];
}
else {
else
{
data = 0;
}
if (MathMan.isInteger(split[0])) {
if (MathMan.isInteger(split[0]))
{
id = Short.parseShort(split[0]);
match = 0;
}
else {
StringComparison<Material>.ComparisonResult comparison = new StringComparison<Material>(name, Material.values()).getBestMatchAdvanced();
else
{
final StringComparison<Material>.ComparisonResult comparison = new StringComparison<Material>(name, Material.values()).getBestMatchAdvanced();
match = comparison.match;
id = (short) comparison.best.getId();
id = (short) comparison.best.getId();
}
PlotBlock block = new PlotBlock(id, data);
StringComparison<PlotBlock> outer = new StringComparison<PlotBlock>();
final PlotBlock block = new PlotBlock(id, data);
final StringComparison<PlotBlock> outer = new StringComparison<PlotBlock>();
return outer.new ComparisonResult(match, block);
}
catch (Exception e) {}
catch (final Exception e)
{}
return null;
}
@Override
public PlotBlock getBlock(Location loc) {
public PlotBlock getBlock(final Location loc)
{
final World world = getWorld(loc.getWorld());
final Block block = world.getBlockAt(loc.getX(), loc.getY(), loc.getZ());
if (block == null) {
return new PlotBlock((short) 0, (byte) 0);
}
if (block == null) { return new PlotBlock((short) 0, (byte) 0); }
return new PlotBlock((short) block.getTypeId(), block.getData());
}
}

View File

@ -51,7 +51,8 @@ import com.intellectualcrafters.configuration.InvalidConfigurationException;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
public class Metrics {
public class Metrics
{
/**
* The current revision number
*/
@ -101,26 +102,26 @@ public class Metrics {
*/
private volatile BukkitTask task = null;
public Metrics(final Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
public Metrics(final Plugin plugin) throws IOException
{
if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null"); }
this.plugin = plugin;
// load the config
this.configurationFile = getConfigFile();
this.configuration = YamlConfiguration.loadConfiguration(this.configurationFile);
configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
this.configuration.addDefault("opt-out", false);
this.configuration.addDefault("guid", UUID.randomUUID().toString());
this.configuration.addDefault("debug", false);
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (this.configuration.get("guid", null) == null) {
this.configuration.options().header("http://mcstats.org").copyDefaults(true);
this.configuration.save(this.configurationFile);
if (configuration.get("guid", null) == null)
{
configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
this.guid = this.configuration.getString("guid");
this.debug = this.configuration.getBoolean("debug", false);
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
}
/**
@ -130,20 +131,29 @@ public class Metrics {
*
* @return byte[] the file as a byte array
*/
public static byte[] gzip(final String input) {
public static byte[] gzip(final String input)
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
try
{
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (final IOException e) {
}
catch (final IOException e)
{
e.printStackTrace();
} finally {
if (gzos != null) {
try {
}
finally
{
if (gzos != null)
{
try
{
gzos.close();
} catch (final IOException ignore) {
}
catch (final IOException ignore)
{}
}
}
return baos.toByteArray();
@ -158,24 +168,33 @@ public class Metrics {
*
* @throws UnsupportedEncodingException
*/
private static void appendJSONPair(final StringBuilder json, final String key, final String value) throws UnsupportedEncodingException {
private static void appendJSONPair(final StringBuilder json, final String key, final String value) throws UnsupportedEncodingException
{
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
try
{
if (value.equals("0") || !value.endsWith("0"))
{
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (final NumberFormatException e) {
}
catch (final NumberFormatException e)
{
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
if (json.charAt(json.length() - 1) != '{')
{
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
if (isValueNumeric)
{
json.append(value);
} else {
}
else
{
json.append(escapeJSON(value));
}
}
@ -187,12 +206,15 @@ public class Metrics {
*
* @return String
*/
private static String escapeJSON(final String text) {
private static String escapeJSON(final String text)
{
final StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
for (int index = 0; index < text.length(); index++)
{
final char chr = text.charAt(index);
switch (chr) {
switch (chr)
{
case '"':
case '\\':
builder.append('\\');
@ -211,10 +233,13 @@ public class Metrics {
builder.append("\\r");
break;
default:
if (chr < ' ') {
if (chr < ' ')
{
final String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
}
else
{
builder.append(chr);
}
break;
@ -231,7 +256,8 @@ public class Metrics {
*
* @return the encoded text, as UTF-8
*/
private static String urlEncode(final String text) throws UnsupportedEncodingException {
private static String urlEncode(final String text) throws UnsupportedEncodingException
{
return URLEncoder.encode(text, "UTF-8");
}
@ -243,14 +269,13 @@ public class Metrics {
*
* @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
*/
public Graph createGraph(final String name) {
if (name == null) {
throw new IllegalArgumentException("Graph name cannot be null");
}
public Graph createGraph(final String name)
{
if (name == null) { throw new IllegalArgumentException("Graph name cannot be null"); }
// Construct the graph object
final Graph graph = new Graph(name);
// Now we can add our graph
this.graphs.add(graph);
graphs.add(graph);
// and return back
return graph;
}
@ -260,11 +285,10 @@ public class Metrics {
*
* @param graph The name of the graph
*/
public void addGraph(final Graph graph) {
if (graph == null) {
throw new IllegalArgumentException("Graph cannot be null");
}
this.graphs.add(graph);
public void addGraph(final Graph graph)
{
if (graph == null) { throw new IllegalArgumentException("Graph cannot be null"); }
graphs.add(graph);
}
/**
@ -274,36 +298,40 @@ public class Metrics {
*
* @return True if statistics measuring is running, otherwise false.
*/
public boolean start() {
synchronized (this.optOutLock) {
public boolean start()
{
synchronized (optOutLock)
{
// Did we opt out?
if (isOptOut()) {
return false;
}
if (isOptOut()) { return false; }
// Is metrics already running?
if (this.task != null) {
return true;
}
if (task != null) { return true; }
// Begin hitting the server with glorious data
this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() {
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable()
{
private boolean firstPost = true;
@Override
public void run() {
try {
public void run()
{
try
{
// This has to be synchronized or it can collide
// with
// the disable method.
synchronized (Metrics.this.optOutLock) {
synchronized (optOutLock)
{
// Disable Task, if it is running and the
// server
// owner decided to opt-out
if (isOptOut() && (Metrics.this.task != null)) {
Metrics.this.task.cancel();
Metrics.this.task = null;
if (isOptOut() && (task != null))
{
task.cancel();
task = null;
// Tell all plotters to stop gathering
// information.
for (final Graph graph : Metrics.this.graphs) {
for (final Graph graph : graphs)
{
graph.onOptOut();
}
}
@ -316,13 +344,16 @@ public class Metrics {
// Each time thereafter it will evaluate to
// TRUE, i.e
// PING!
postPlugin(!this.firstPost);
postPlugin(!firstPost);
// After the first post we set firstPost to
// false
// Each post thereafter will be a ping
this.firstPost = false;
} catch (final IOException e) {
if (Metrics.this.debug) {
firstPost = false;
}
catch (final IOException e)
{
if (debug)
{
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
@ -337,23 +368,32 @@ public class Metrics {
*
* @return true if metrics should be opted out of it
*/
public boolean isOptOut() {
synchronized (this.optOutLock) {
try {
public boolean isOptOut()
{
synchronized (optOutLock)
{
try
{
// Reload the metrics file
this.configuration.load(getConfigFile());
} catch (final IOException ex) {
if (this.debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (final InvalidConfigurationException ex) {
if (this.debug) {
configuration.load(getConfigFile());
}
catch (final IOException ex)
{
if (debug)
{
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return this.configuration.getBoolean("opt-out", false);
catch (final InvalidConfigurationException ex)
{
if (debug)
{
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
}
@ -362,18 +402,22 @@ public class Metrics {
*
* @throws java.io.IOException
*/
public void enable() throws IOException {
public void enable() throws IOException
{
// This has to be synchronized or it can collide with the check in the
// task.
synchronized (this.optOutLock) {
synchronized (optOutLock)
{
// Check if the server owner has already set opt-out, if not, set
// it.
if (isOptOut()) {
this.configuration.set("opt-out", false);
this.configuration.save(this.configurationFile);
if (isOptOut())
{
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (this.task == null) {
if (task == null)
{
start();
}
}
@ -384,20 +428,24 @@ public class Metrics {
*
* @throws java.io.IOException
*/
public void disable() throws IOException {
public void disable() throws IOException
{
// This has to be synchronized or it can collide with the check in the
// task.
synchronized (this.optOutLock) {
synchronized (optOutLock)
{
// Check if the server owner has already set opt-out, if not, set
// it.
if (!isOptOut()) {
this.configuration.set("opt-out", true);
this.configuration.save(this.configurationFile);
if (!isOptOut())
{
configuration.set("opt-out", true);
configuration.save(configurationFile);
}
// Disable Task, if it is running
if (this.task != null) {
this.task.cancel();
this.task = null;
if (task != null)
{
task.cancel();
task = null;
}
}
}
@ -407,14 +455,15 @@ public class Metrics {
*
* @return the File object for the config file
*/
public File getConfigFile() {
public File getConfigFile()
{
// I believe the easiest way to get the base folder (e.g craftbukkit set
// via -P) for plugins to use
// is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory.
final File pluginsFolder = this.plugin.getDataFolder().getParentFile();
final File pluginsFolder = plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
}
@ -422,9 +471,10 @@ public class Metrics {
/**
* Generic method that posts a plugin to the metrics website
*/
private void postPlugin(final boolean isPing) throws IOException {
private void postPlugin(final boolean isPing) throws IOException
{
// Server software specific section
final PluginDescriptionFile description = this.plugin.getDescription();
final PluginDescriptionFile description = plugin.getDescription();
final String pluginName = description.getName();
final boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE
// if
@ -435,14 +485,19 @@ public class Metrics {
final String pluginVersion = description.getVersion();
final String serverVersion = Bukkit.getVersion();
int playersOnline = 0;
try {
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class) {
try
{
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class)
{
playersOnline = ((Collection<?>) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).size();
} else {
}
else
{
playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null, new Object[0])).length;
}
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
}
catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex)
{}
// END server software specific section -- all code below does not use
// any code outside of this class / Java
// Construct the post data
@ -450,7 +505,7 @@ public class Metrics {
json.append('{');
// The plugin's description file containg all of the plugin data such as
// name, version, author, etc
appendJSONPair(json, "guid", this.guid);
appendJSONPair(json, "guid", guid);
appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline));
@ -461,7 +516,8 @@ public class Metrics {
final String java_version = System.getProperty("java.version");
final int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) {
if (osarch.equals("amd64"))
{
osarch = "x86_64";
}
appendJSONPair(json, "osname", osname);
@ -471,11 +527,14 @@ public class Metrics {
appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it
if (isPing) {
if (isPing)
{
appendJSONPair(json, "ping", "1");
}
if (this.graphs.size() > 0) {
synchronized (this.graphs) {
if (graphs.size() > 0)
{
synchronized (graphs)
{
json.append(',');
json.append('"');
json.append("graphs");
@ -483,14 +542,17 @@ public class Metrics {
json.append(':');
json.append('{');
boolean firstGraph = true;
for (final Graph graph : this.graphs) {
for (final Graph graph : graphs)
{
final StringBuilder graphJson = new StringBuilder();
graphJson.append('{');
for (final Plotter plotter : graph.getPlotters()) {
for (final Plotter plotter : graph.getPlotters())
{
appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue()));
}
graphJson.append('}');
if (!firstGraph) {
if (!firstGraph)
{
json.append(',');
}
json.append(escapeJSON(graph.getName()));
@ -509,9 +571,12 @@ public class Metrics {
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
if (isMineshafterPresent())
{
connection = url.openConnection(Proxy.NO_PROXY);
} else {
}
else
{
connection = url.openConnection();
}
final byte[] uncompressed = json.toString().getBytes();
@ -524,7 +589,8 @@ public class Metrics {
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (this.debug) {
if (debug)
{
PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
}
// Write the data
@ -537,19 +603,29 @@ public class Metrics {
// close resources
os.close();
reader.close();
if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
if ((response == null) || response.startsWith("ERR") || response.startsWith("7"))
{
if (response == null)
{
response = "null";
} else if (response.startsWith("7")) {
}
else if (response.startsWith("7"))
{
response = response.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
} else {
}
else
{
// Is this the first update this hour?
if (response.equals("1") || response.contains("This is your first update this hour")) {
synchronized (this.graphs) {
for (final Graph graph : this.graphs) {
for (final Plotter plotter : graph.getPlotters()) {
if (response.equals("1") || response.contains("This is your first update this hour"))
{
synchronized (graphs)
{
for (final Graph graph : graphs)
{
for (final Plotter plotter : graph.getPlotters())
{
plotter.reset();
}
}
@ -563,11 +639,15 @@ public class Metrics {
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
private boolean isMineshafterPresent()
{
try
{
Class.forName("mineshafter.MineServer");
return true;
} catch (final Exception e) {
}
catch (final Exception e)
{
return false;
}
}
@ -575,7 +655,8 @@ public class Metrics {
/**
* Represents a custom graph on the website
*/
public static class Graph {
public static class Graph
{
/**
* The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is
* rejected
@ -586,7 +667,8 @@ public class Metrics {
*/
private final Set<Plotter> plotters = new LinkedHashSet<Plotter>();
private Graph(final String name) {
private Graph(final String name)
{
this.name = name;
}
@ -595,8 +677,9 @@ public class Metrics {
*
* @return the Graph's name
*/
public String getName() {
return this.name;
public String getName()
{
return name;
}
/**
@ -604,8 +687,9 @@ public class Metrics {
*
* @param plotter the plotter to add to the graph
*/
public void addPlotter(final Plotter plotter) {
this.plotters.add(plotter);
public void addPlotter(final Plotter plotter)
{
plotters.add(plotter);
}
/**
@ -613,8 +697,9 @@ public class Metrics {
*
* @param plotter the plotter to remove from the graph
*/
public void removePlotter(final Plotter plotter) {
this.plotters.remove(plotter);
public void removePlotter(final Plotter plotter)
{
plotters.remove(plotter);
}
/**
@ -622,35 +707,37 @@ public class Metrics {
*
* @return an unmodifiable {@link java.util.Set} of the plotter objects
*/
public Set<Plotter> getPlotters() {
return Collections.unmodifiableSet(this.plotters);
public Set<Plotter> getPlotters()
{
return Collections.unmodifiableSet(plotters);
}
@Override
public int hashCode() {
return this.name.hashCode();
public int hashCode()
{
return name.hashCode();
}
@Override
public boolean equals(final Object object) {
if (!(object instanceof Graph)) {
return false;
}
public boolean equals(final Object object)
{
if (!(object instanceof Graph)) { return false; }
final Graph graph = (Graph) object;
return graph.name.equals(this.name);
return graph.name.equals(name);
}
/**
* Called when the server owner decides to opt-out of BukkitMetrics while the server is running.
*/
protected void onOptOut() {
}
protected void onOptOut()
{}
}
/**
* Interface used to collect custom data for a plugin
*/
public static abstract class Plotter {
public static abstract class Plotter
{
/**
* The plot's name
*/
@ -659,7 +746,8 @@ public class Metrics {
/**
* Construct a plotter with the default plot name
*/
public Plotter() {
public Plotter()
{
this("Default");
}
@ -668,7 +756,8 @@ public class Metrics {
*
* @param name the name of the plotter to use, which will show up on the website
*/
public Plotter(final String name) {
public Plotter(final String name)
{
this.name = name;
}
@ -686,28 +775,29 @@ public class Metrics {
*
* @return the plotted point's column name
*/
public String getColumnName() {
return this.name;
public String getColumnName()
{
return name;
}
/**
* Called after the website graphs have been updated
*/
public void reset() {
}
public void reset()
{}
@Override
public int hashCode() {
public int hashCode()
{
return getColumnName().hashCode();
}
@Override
public boolean equals(final Object object) {
if (!(object instanceof Plotter)) {
return false;
}
public boolean equals(final Object object)
{
if (!(object instanceof Plotter)) { return false; }
final Plotter plotter = (Plotter) object;
return plotter.name.equals(this.name) && (plotter.getValue() == getValue());
return plotter.name.equals(name) && (plotter.getValue() == getValue());
}
}
}

View File

@ -17,54 +17,62 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
public class OfflinePlayerUtil {
public class OfflinePlayerUtil
{
public static Player loadPlayer(final String name) {
public static Player loadPlayer(final String name)
{
return loadPlayer(Bukkit.getOfflinePlayer(name));
}
public static Player loadPlayer(final UUID id) {
public static Player loadPlayer(final UUID id)
{
return loadPlayer(Bukkit.getOfflinePlayer(id));
}
public static Player loadPlayer(final OfflinePlayer player) {
if (player == null) {
return null;
}
if (player instanceof Player) {
return (Player) player;
}
public static Player loadPlayer(final OfflinePlayer player)
{
if (player == null) { return null; }
if (player instanceof Player) { return (Player) player; }
return loadPlayer(player.getUniqueId(), player.getName());
}
private static Player loadPlayer(final UUID id, final String name) {
private static Player loadPlayer(final UUID id, final String name)
{
final Object server = getMinecraftServer();
final Object interactManager = newPlayerInteractManager();
final Object worldServer = getWorldServer();
final Object profile = newGameProfile(id, name);
final Class<?> entityPlayerClass = getNmsClass("EntityPlayer");
final Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"), getUtilClass("com.mojang.authlib.GameProfile"), getNmsClass("PlayerInteractManager"));
final Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"), getUtilClass("com.mojang.authlib.GameProfile"),
getNmsClass("PlayerInteractManager"));
final Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager);
final Player player = (Player) getBukkitEntity(entityPlayer);
return player;
}
private static Object newGameProfile(final UUID id, final String name) {
private static Object newGameProfile(final UUID id, final String name)
{
final Class<?> gameProfileClass = getUtilClass("com.mojang.authlib.GameProfile");
if (gameProfileClass == null) { //Before uuids
if (gameProfileClass == null)
{ //Before uuids
return name;
}
Constructor gameProfileConstructor = null;
gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class);
if (gameProfileConstructor == null) { //Verson has string constructor
if (gameProfileConstructor == null)
{ //Verson has string constructor
gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class);
return callConstructor(gameProfileConstructor, id.toString(), name);
} else { //Version has uuid constructor
}
else
{ //Version has uuid constructor
return callConstructor(gameProfileConstructor, id, name);
}
}
private static Object newPlayerInteractManager() {
private static Object newPlayerInteractManager()
{
final Object worldServer = getWorldServer();
final Class<?> playerInteractClass = getNmsClass("PlayerInteractManager");
final Class<?> worldClass = getNmsClass("World");
@ -72,7 +80,8 @@ public class OfflinePlayerUtil {
return callConstructor(c, worldServer);
}
private static Object getWorldServer() {
private static Object getWorldServer()
{
final Object server = getMinecraftServer();
final Class<?> minecraftServerClass = getNmsClass("MinecraftServer");
final Method getWorldServer = makeMethod(minecraftServerClass, "getWorldServer", int.class);
@ -81,11 +90,13 @@ public class OfflinePlayerUtil {
//NMS Utils
private static Object getMinecraftServer() {
private static Object getMinecraftServer()
{
return callMethod(makeMethod(getCbClass("CraftServer"), "getServer"), Bukkit.getServer());
}
private static Entity getBukkitEntity(final Object o) {
private static Entity getBukkitEntity(final Object o)
{
final Method getBukkitEntity = makeMethod(o.getClass(), "getBukkitEntity");
return callMethod(getBukkitEntity, o);
}

View File

@ -11,137 +11,187 @@ import org.bukkit.Bukkit;
* Reflection Utilities for minecraft
*
*/
public class ReflectionUtil {
public static Class<?> getNmsClass(final String name) {
public class ReflectionUtil
{
public static Class<?> getNmsClass(final String name)
{
final String className = "net.minecraft.server." + getVersion() + "." + name;
return getClass(className);
}
public static Class<?> getCbClass(final String name) {
public static Class<?> getCbClass(final String name)
{
final String className = "org.bukkit.craftbukkit." + getVersion() + "." + name;
return getClass(className);
}
public static Class<?> getUtilClass(final String name) {
try {
public static Class<?> getUtilClass(final String name)
{
try
{
return Class.forName(name); //Try before 1.8 first
} catch (final ClassNotFoundException ex) {
try {
}
catch (final ClassNotFoundException ex)
{
try
{
return Class.forName("net.minecraft.util." + name); //Not 1.8
} catch (final ClassNotFoundException ex2) {
}
catch (final ClassNotFoundException ex2)
{
return null;
}
}
}
public static String getVersion() {
public static String getVersion()
{
final String packageName = Bukkit.getServer().getClass().getPackage().getName();
return packageName.substring(packageName.lastIndexOf('.') + 1);
}
public static Object getHandle(final Object wrapper) {
public static Object getHandle(final Object wrapper)
{
final Method getHandle = makeMethod(wrapper.getClass(), "getHandle");
return callMethod(getHandle, wrapper);
}
//Utils
public static Method makeMethod(final Class<?> clazz, final String methodName, final Class<?>... paramaters) {
try {
public static Method makeMethod(final Class<?> clazz, final String methodName, final Class<?>... paramaters)
{
try
{
return clazz.getDeclaredMethod(methodName, paramaters);
} catch (final NoSuchMethodException ex) {
}
catch (final NoSuchMethodException ex)
{
return null;
} catch (final Exception ex) {
}
catch (final Exception ex)
{
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> T callMethod(final Method method, final Object instance, final Object... paramaters) {
if (method == null) {
throw new RuntimeException("No such method");
}
public static <T> T callMethod(final Method method, final Object instance, final Object... paramaters)
{
if (method == null) { throw new RuntimeException("No such method"); }
method.setAccessible(true);
try {
try
{
return (T) method.invoke(instance, paramaters);
} catch (final InvocationTargetException ex) {
}
catch (final InvocationTargetException ex)
{
throw new RuntimeException(ex.getCause());
} catch (final Exception ex) {
}
catch (final Exception ex)
{
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> Constructor<T> makeConstructor(final Class<?> clazz, final Class<?>... paramaterTypes) {
try {
public static <T> Constructor<T> makeConstructor(final Class<?> clazz, final Class<?>... paramaterTypes)
{
try
{
return (Constructor<T>) clazz.getConstructor(paramaterTypes);
} catch (final NoSuchMethodException ex) {
}
catch (final NoSuchMethodException ex)
{
return null;
} catch (final Exception ex) {
}
catch (final Exception ex)
{
throw new RuntimeException(ex);
}
}
public static <T> T callConstructor(final Constructor<T> constructor, final Object... paramaters) {
if (constructor == null) {
throw new RuntimeException("No such constructor");
}
public static <T> T callConstructor(final Constructor<T> constructor, final Object... paramaters)
{
if (constructor == null) { throw new RuntimeException("No such constructor"); }
constructor.setAccessible(true);
try {
try
{
return constructor.newInstance(paramaters);
} catch (final InvocationTargetException ex) {
}
catch (final InvocationTargetException ex)
{
throw new RuntimeException(ex.getCause());
} catch (final Exception ex) {
}
catch (final Exception ex)
{
throw new RuntimeException(ex);
}
}
public static Field makeField(final Class<?> clazz, final String name) {
try {
public static Field makeField(final Class<?> clazz, final String name)
{
try
{
return clazz.getDeclaredField(name);
} catch (final NoSuchFieldException ex) {
}
catch (final NoSuchFieldException ex)
{
return null;
} catch (final Exception ex) {
}
catch (final Exception ex)
{
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> T getField(final Field field, final Object instance) {
if (field == null) {
throw new RuntimeException("No such field");
}
public static <T> T getField(final Field field, final Object instance)
{
if (field == null) { throw new RuntimeException("No such field"); }
field.setAccessible(true);
try {
try
{
return (T) field.get(instance);
} catch (final Exception ex) {
}
catch (final Exception ex)
{
throw new RuntimeException(ex);
}
}
public static void setField(final Field field, final Object instance, final Object value) {
if (field == null) {
throw new RuntimeException("No such field");
}
public static void setField(final Field field, final Object instance, final Object value)
{
if (field == null) { throw new RuntimeException("No such field"); }
field.setAccessible(true);
try {
try
{
field.set(instance, value);
} catch (final Exception ex) {
}
catch (final Exception ex)
{
throw new RuntimeException(ex);
}
}
public static Class<?> getClass(final String name) {
try {
public static Class<?> getClass(final String name)
{
try
{
return Class.forName(name);
} catch (final ClassNotFoundException ex) {
}
catch (final ClassNotFoundException ex)
{
return null;
}
}
public static <T> Class<? extends T> getClass(final String name, final Class<T> superClass) {
try {
public static <T> Class<? extends T> getClass(final String name, final Class<T> superClass)
{
try
{
return Class.forName(name).asSubclass(superClass);
} catch (ClassCastException | ClassNotFoundException ex) {
}
catch (ClassCastException | ClassNotFoundException ex)
{
return null;
}
}

View File

@ -1,196 +1,212 @@
package com.plotsquared.bukkit.util;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import org.bukkit.Chunk;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.object.BukkitPlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.Bukkit;
/**
* An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy NMS)
*
* @author Empire92
*/
public class SendChunk {
// // Ref Class
private final RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer");
private final RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk");
private final RefClass classPacket = getRefClass("{nms}.Packet");
private final RefClass classConnection = getRefClass("{nms}.PlayerConnection");
private final RefClass classChunk = getRefClass("{nms}.Chunk");
private final RefClass classCraftPlayer = getRefClass("{cb}.entity.CraftPlayer");
private final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
private RefMethod methodGetHandlePlayer;
private RefMethod methodGetHandleChunk;
private RefConstructor MapChunk;
private RefField connection;
private RefMethod send;
private RefMethod methodInitLighting;
/**
* Constructor
*
* @throws NoSuchMethodException
*/
public SendChunk() throws NoSuchMethodException {
methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle");
methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
methodInitLighting = classChunk.getMethod("initLighting");
MapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class);
connection = classEntityPlayer.getField("playerConnection");
send = classConnection.getMethod("sendPacket", classPacket.getRealClass());
}
public void sendChunk(final Collection<Chunk> input) {
HashSet<Chunk> chunks = new HashSet<Chunk>(input);
HashMap<String, ArrayList<Chunk>> map = new HashMap<>();
int view = Bukkit.getServer().getViewDistance();
for (Chunk chunk : chunks) {
String world = chunk.getWorld().getName();
ArrayList<Chunk> list = map.get(world);
if (list == null) {
list = new ArrayList<>();
map.put(world, list);
}
list.add(chunk);
Object c = methodGetHandleChunk.of(chunk).call();
methodInitLighting.of(c).call();
}
for (PlotPlayer pp : UUIDHandler.getPlayers().values() ) {
Plot plot = pp.getCurrentPlot();
Location loc = null;
String world;
if (plot != null) {
world = plot.world;
}
else {
loc = pp.getLocation();
world = loc.getWorld();
}
ArrayList<Chunk> list = map.get(world);
if (list == null) {
continue;
}
if (loc == null) {
loc = pp.getLocation();
}
int cx = loc.getX() >> 4;
int cz = loc.getZ() >> 4;
Player player = ((BukkitPlayer) pp).player;
Object entity = methodGetHandlePlayer.of(player).call();
for (Chunk chunk : list) {
int dx = Math.abs(cx - chunk.getX());
int dz = Math.abs(cz - chunk.getZ());
if (dx > view || dz > view) {
continue;
}
Object c = methodGetHandleChunk.of(chunk).call();
chunks.remove(chunk);
Object con = connection.of(entity).get();
// if (dx != 0 || dz != 0) {
// Object packet = MapChunk.create(c, true, 0);
// send.of(con).call(packet);
// }
Object packet = MapChunk.create(c, true, 65535);
send.of(con).call(packet);
}
}
for (final Chunk chunk : chunks) {
TaskManager.runTask(new Runnable() {
@Override
public void run() {
try {
chunk.unload(true, false);
}
catch (Exception e) {
String worldname = chunk.getWorld().getName();
PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ());
PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname + "level_old.dat may be corrupt (try repairing or removing these)");
}
}
});
}
//
//
// int diffx, diffz;
// << 4;
// for (final Chunk chunk : chunks) {
// if (!chunk.isLoaded()) {
// continue;
// }
// boolean unload = true;
// final Object c = methodGetHandle.of(chunk).call();
// final Object w = world.of(c).get();
// final Object p = players.of(w).get();
// for (final Object ep : (List<Object>) p) {
// final int x = ((Double) locX.of(ep).get()).intValue();
// final int z = ((Double) locZ.of(ep).get()).intValue();
// diffx = Math.abs(x - (chunk.getX() << 4));
// diffz = Math.abs(z - (chunk.getZ() << 4));
// if ((diffx <= view) && (diffz <= view)) {
// unload = false;
// if (v1_7_10) {
// chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
// chunk.load(true);
// }
// else {
// final Object pair = ChunkCoordIntPairCon.create(chunk.getX(), chunk.getZ());
// final Object pq = chunkCoordIntPairQueue.of(ep).get();
// ((List) pq).add(pair);
// }
// }
// }
// if (unload) {
// TaskManager.runTask(new Runnable() {
// @Override
// public void run() {
// try {
// chunk.unload(true, true);
// }
// catch (Exception e) {
// String worldname = chunk.getWorld().getName();
// PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ());
// PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
// PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname + "level_old.dat may be corrupt (try repairing or removing these)");
// }
// }
// });
// }
//
// }
}
public void sendChunk(final String worldname, final List<ChunkLoc> locs) {
final World myworld = Bukkit.getWorld(worldname);
final ArrayList<Chunk> chunks = new ArrayList<>();
for (final ChunkLoc loc : locs) {
chunks.add(myworld.getChunkAt(loc.x, loc.z));
}
sendChunk(chunks);
}
}
package com.plotsquared.bukkit.util;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.object.BukkitPlayer;
/**
* An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy NMS)
*
*/
public class SendChunk
{
// // Ref Class
private final RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer");
private final RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk");
private final RefClass classPacket = getRefClass("{nms}.Packet");
private final RefClass classConnection = getRefClass("{nms}.PlayerConnection");
private final RefClass classChunk = getRefClass("{nms}.Chunk");
private final RefClass classCraftPlayer = getRefClass("{cb}.entity.CraftPlayer");
private final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
private final RefMethod methodGetHandlePlayer;
private final RefMethod methodGetHandleChunk;
private final RefConstructor MapChunk;
private final RefField connection;
private final RefMethod send;
private final RefMethod methodInitLighting;
/**
* Constructor
*
* @throws NoSuchMethodException
*/
public SendChunk() throws NoSuchMethodException
{
methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle");
methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
methodInitLighting = classChunk.getMethod("initLighting");
MapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class);
connection = classEntityPlayer.getField("playerConnection");
send = classConnection.getMethod("sendPacket", classPacket.getRealClass());
}
public void sendChunk(final Collection<Chunk> input)
{
final HashSet<Chunk> chunks = new HashSet<Chunk>(input);
final HashMap<String, ArrayList<Chunk>> map = new HashMap<>();
final int view = Bukkit.getServer().getViewDistance();
for (final Chunk chunk : chunks)
{
final String world = chunk.getWorld().getName();
ArrayList<Chunk> list = map.get(world);
if (list == null)
{
list = new ArrayList<>();
map.put(world, list);
}
list.add(chunk);
final Object c = methodGetHandleChunk.of(chunk).call();
methodInitLighting.of(c).call();
}
for (final PlotPlayer pp : UUIDHandler.getPlayers().values())
{
final Plot plot = pp.getCurrentPlot();
Location loc = null;
String world;
if (plot != null)
{
world = plot.world;
}
else
{
loc = pp.getLocation();
world = loc.getWorld();
}
final ArrayList<Chunk> list = map.get(world);
if (list == null)
{
continue;
}
if (loc == null)
{
loc = pp.getLocation();
}
final int cx = loc.getX() >> 4;
final int cz = loc.getZ() >> 4;
final Player player = ((BukkitPlayer) pp).player;
final Object entity = methodGetHandlePlayer.of(player).call();
for (final Chunk chunk : list)
{
final int dx = Math.abs(cx - chunk.getX());
final int dz = Math.abs(cz - chunk.getZ());
if ((dx > view) || (dz > view))
{
continue;
}
final Object c = methodGetHandleChunk.of(chunk).call();
chunks.remove(chunk);
final Object con = connection.of(entity).get();
// if (dx != 0 || dz != 0) {
// Object packet = MapChunk.create(c, true, 0);
// send.of(con).call(packet);
// }
final Object packet = MapChunk.create(c, true, 65535);
send.of(con).call(packet);
}
}
for (final Chunk chunk : chunks)
{
TaskManager.runTask(new Runnable()
{
@Override
public void run()
{
try
{
chunk.unload(true, false);
}
catch (final Exception e)
{
final String worldname = chunk.getWorld().getName();
PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ());
PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname + "level_old.dat may be corrupt (try repairing or removing these)");
}
}
});
}
//
//
// int diffx, diffz;
// << 4;
// for (final Chunk chunk : chunks) {
// if (!chunk.isLoaded()) {
// continue;
// }
// boolean unload = true;
// final Object c = methodGetHandle.of(chunk).call();
// final Object w = world.of(c).get();
// final Object p = players.of(w).get();
// for (final Object ep : (List<Object>) p) {
// final int x = ((Double) locX.of(ep).get()).intValue();
// final int z = ((Double) locZ.of(ep).get()).intValue();
// diffx = Math.abs(x - (chunk.getX() << 4));
// diffz = Math.abs(z - (chunk.getZ() << 4));
// if ((diffx <= view) && (diffz <= view)) {
// unload = false;
// if (v1_7_10) {
// chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
// chunk.load(true);
// }
// else {
// final Object pair = ChunkCoordIntPairCon.create(chunk.getX(), chunk.getZ());
// final Object pq = chunkCoordIntPairQueue.of(ep).get();
// ((List) pq).add(pair);
// }
// }
// }
// if (unload) {
// TaskManager.runTask(new Runnable() {
// @Override
// public void run() {
// try {
// chunk.unload(true, true);
// }
// catch (Exception e) {
// String worldname = chunk.getWorld().getName();
// PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ());
// PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
// PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname + "level_old.dat may be corrupt (try repairing or removing these)");
// }
// }
// });
// }
//
// }
}
public void sendChunk(final String worldname, final List<ChunkLoc> locs)
{
final World myworld = Bukkit.getWorld(worldname);
final ArrayList<Chunk> chunks = new ArrayList<>();
for (final ChunkLoc loc : locs)
{
chunks.add(myworld.getChunkAt(loc.x, loc.z));
}
sendChunk(chunks);
}

View File

@ -1,138 +1,149 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.util;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import java.util.Collection;
import java.util.HashMap;
import org.bukkit.Chunk;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
/**
* SetBlockFast class<br> Used to do fast world editing
*
* @author Empire92
*/
public class SetBlockFast extends BukkitSetBlockManager {
private final RefClass classBlock = getRefClass("{nms}.Block");
private final RefClass classChunk = getRefClass("{nms}.Chunk");
private final RefClass classWorld = getRefClass("{nms}.World");
private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private RefMethod methodGetHandle;
private RefMethod methodGetChunkAt;
private RefMethod methodA;
private RefMethod methodGetById;
private SendChunk chunksender;
public HashMap<ChunkLoc, Chunk> toUpdate = new HashMap<>();
/**
* Constructor
*
* @throws NoSuchMethodException
*/
public SetBlockFast() throws NoSuchMethodException {
methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class);
methodGetById = classBlock.getMethod("getById", int.class);
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
update(toUpdate.values());
toUpdate = new HashMap<>();
}
}, 20);
this.chunksender = new SendChunk();
}
private ChunkLoc lastLoc = null;
/**
* Set the block at the location
*
* @param world World in which the block should be set
* @param x X Coordinate
* @param y Y Coordinate
* @param z Z Coordinate
* @param blockId Block ID
* @param data Block Data Value
*
*/
@Override
public void set(final org.bukkit.World world, final int x, final int y, final int z, final int blockId, final byte data) {
if (blockId == -1) {
world.getBlockAt(x, y, z).setData(data, false);
return;
}
int X = x >> 4;
int Z = z >> 4;
ChunkLoc loc = new ChunkLoc(X, Z);
if (!loc.equals(lastLoc)) {
Chunk chunk = toUpdate.get(loc);
if (chunk == null) {
chunk = world.getChunkAt(X, Z);
toUpdate.put(loc, chunk);
}
chunk.load(false);
}
final Object w = methodGetHandle.of(world).call();
final Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
final Object block = methodGetById.of(null).call(blockId);
methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data);
}
/**
* Update chunks
*
* @param chunks list of chunks to update
*/
@Override
public void update(final Collection<Chunk> chunks) {
if (chunks.size() == 0) {
return;
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try {
chunksender.sendChunk(chunks);
} catch (final Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.util;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import java.util.Collection;
import java.util.HashMap;
import org.bukkit.Chunk;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
/**
* SetBlockFast class<br> Used to do fast world editing
*
*/
public class SetBlockFast extends BukkitSetBlockManager
{
private final RefClass classBlock = getRefClass("{nms}.Block");
private final RefClass classChunk = getRefClass("{nms}.Chunk");
private final RefClass classWorld = getRefClass("{nms}.World");
private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private final RefMethod methodGetHandle;
private final RefMethod methodGetChunkAt;
private final RefMethod methodA;
private final RefMethod methodGetById;
private final SendChunk chunksender;
public HashMap<ChunkLoc, Chunk> toUpdate = new HashMap<>();
/**
* Constructor
*
* @throws NoSuchMethodException
*/
public SetBlockFast() throws NoSuchMethodException
{
methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class);
methodGetById = classBlock.getMethod("getById", int.class);
TaskManager.runTaskRepeat(new Runnable()
{
@Override
public void run()
{
// TODO Auto-generated method stub
update(toUpdate.values());
toUpdate = new HashMap<>();
}
}, 20);
chunksender = new SendChunk();
}
private final ChunkLoc lastLoc = null;
/**
* Set the block at the location
*
* @param world World in which the block should be set
* @param x X Coordinate
* @param y Y Coordinate
* @param z Z Coordinate
* @param blockId Block ID
* @param data Block Data Value
*
*/
@Override
public void set(final org.bukkit.World world, final int x, final int y, final int z, final int blockId, final byte data)
{
if (blockId == -1)
{
world.getBlockAt(x, y, z).setData(data, false);
return;
}
final int X = x >> 4;
final int Z = z >> 4;
final ChunkLoc loc = new ChunkLoc(X, Z);
if (!loc.equals(lastLoc))
{
Chunk chunk = toUpdate.get(loc);
if (chunk == null)
{
chunk = world.getChunkAt(X, Z);
toUpdate.put(loc, chunk);
}
chunk.load(false);
}
final Object w = methodGetHandle.of(world).call();
final Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
final Object block = methodGetById.of(null).call(blockId);
methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data);
}
/**
* Update chunks
*
* @param chunks list of chunks to update
*/
@Override
public void update(final Collection<Chunk> chunks)
{
if (chunks.size() == 0) { return; }
if (!MainUtil.canSendChunk)
{
for (final Chunk chunk : chunks)
{
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try
{
chunksender.sendChunk(chunks);
}
catch (final Throwable e)
{
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}

View File

@ -1,356 +1,383 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.util;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
/**
* SetBlockFast class<br> Used to do fast world editing
*
* @author Empire92
*/
public class SetBlockFast_1_8 extends BukkitSetBlockManager {
private final RefClass classBlock = getRefClass("{nms}.Block");
private final RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
private final RefClass classIBlockData = getRefClass("{nms}.IBlockData");
private final RefClass classChunk = getRefClass("{nms}.Chunk");
private final RefClass classWorld = getRefClass("{nms}.World");
private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private RefMethod methodGetHandle;
private RefMethod methodGetChunkAt;
private RefMethod methodA;
private RefMethod methodGetByCombinedId;
private RefConstructor constructorBlockPosition;
private SendChunk chunksender;
public static HashMap<ChunkLoc, Chunk> toUpdate = new HashMap<>();
/**
* Constructor
*
* @throws NoSuchMethodException
*/
public SetBlockFast_1_8() throws NoSuchMethodException {
constructorBlockPosition = classBlockPosition.getConstructor(int.class, int.class, int.class);
methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class);
methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", classBlockPosition, classIBlockData);
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
if (toUpdate.size() == 0) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<Chunk>();
Iterator<Entry<ChunkLoc, Chunk>> i = toUpdate.entrySet().iterator();
while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue());
i.remove();
count++;
}
if (count == 0) {
return;
}
update(chunks);
}
}, 1);
this.chunksender = new SendChunk();
}
private ChunkLoc lastLoc = null;
/**
* Set the block at the location
*
* @param world World in which the block should be set
* @param x X Coordinate
* @param y Y Coordinate
* @param z Z Coordinate
* @param id Block ID
* @param data Block Data Value
*/
@SuppressWarnings("deprecation")
@Override
public void set(final World world, final int x, final int y, final int z, final int id, final byte data) {
if (id == -1) {
world.getBlockAt(x, y, z).setData(data, false);
return;
}
// Start blockstate workaround //
switch (id) {
case 54:
case 130:
case 142:
case 132:
case 27:
case 137:
case 52:
case 154:
case 84:
case 25:
case 144:
case 138:
case 176:
case 177:
case 119:
case 63:
case 68:
case 323:
case 117:
case 116:
case 28:
case 66:
case 157:
case 61:
case 62:
case 140:
case 146:
case 149:
case 150:
case 158:
case 23:
case 123:
case 124:
case 29:
case 33:
case 151:
case 178: {
final Block block = world.getBlockAt(x, y, z);
if (block.getData() == data) {
if (block.getTypeId() != id) {
block.setTypeId(id, false);
}
} else {
if (block.getTypeId() == id) {
block.setData(data, false);
} else {
block.setTypeIdAndData(id, data, false);
}
}
return;
}
}
// Start data value shortcut
Block block = world.getBlockAt(x, y, z);
int currentId = block.getTypeId();
if (currentId == id) {
switch(id) {
case 0:
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 24:
case 25:
case 30:
case 32:
case 37:
case 39:
case 40:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 51:
case 52:
case 54:
case 55:
case 56:
case 57:
case 58:
case 60:
case 61:
case 62:
case 7:
case 8:
case 9:
case 10:
case 11:
case 73:
case 74:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 84:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 117:
case 121:
case 122:
case 123:
case 124:
case 129:
case 133:
case 138:
case 137:
case 140:
case 165:
case 166:
case 169:
case 170:
case 172:
case 173:
case 174:
case 176:
case 177:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192: {
return;
}
}
if (block.getData() == data) {
return;
}
block.setData(data);
return;
}
// blockstate
switch(currentId) {
case 54:
case 130:
case 132:
case 142:
case 27:
case 137:
case 52:
case 154:
case 84:
case 25:
case 144:
case 138:
case 176:
case 177:
case 63:
case 68:
case 323:
case 117:
case 119:
case 116:
case 28:
case 66:
case 157:
case 61:
case 62:
case 140:
case 146:
case 149:
case 150:
case 158:
case 23:
case 123:
case 124:
case 29:
case 33:
case 151:
case 178: {
if (block.getData() == data) {
block.setTypeId(id, false);
} else {
block.setTypeIdAndData(id, data, false);
}
return;
}
}
// End blockstate workaround //
int X = x >> 4;
int Z = z >> 4;
ChunkLoc loc = new ChunkLoc(X, Z);
if (!loc.equals(lastLoc)) {
Chunk chunk = toUpdate.get(loc);
if (chunk == null) {
chunk = world.getChunkAt(X, Z);
toUpdate.put(loc, chunk);
}
chunk.load(false);
}
// check sign
final Object w = methodGetHandle.of(world).call();
final Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
final Object pos = constructorBlockPosition.create(x & 0x0f, y, z & 0x0f);
final Object combined = methodGetByCombinedId.of(null).call(id + (data << 12));
methodA.of(chunk).call(pos, combined);
}
@Override
public void update(final Collection<Chunk> chunks) {
if (chunks.size() == 0) {
return;
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try {
chunksender.sendChunk(chunks);
} catch (final Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.util;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
/**
* SetBlockFast class<br> Used to do fast world editing
*
*/
public class SetBlockFast_1_8 extends BukkitSetBlockManager
{
private final RefClass classBlock = getRefClass("{nms}.Block");
private final RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
private final RefClass classIBlockData = getRefClass("{nms}.IBlockData");
private final RefClass classChunk = getRefClass("{nms}.Chunk");
private final RefClass classWorld = getRefClass("{nms}.World");
private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private RefMethod methodGetHandle;
private RefMethod methodGetChunkAt;
private RefMethod methodA;
private RefMethod methodGetByCombinedId;
private RefConstructor constructorBlockPosition;
private SendChunk chunksender;
public static HashMap<ChunkLoc, Chunk> toUpdate = new HashMap<>();
/**
* Constructor
*
* @throws NoSuchMethodException
*/
public SetBlockFast_1_8() throws NoSuchMethodException
{
constructorBlockPosition = classBlockPosition.getConstructor(int.class, int.class, int.class);
methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class);
methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", classBlockPosition, classIBlockData);
TaskManager.runTaskRepeat(new Runnable()
{
@Override
public void run()
{
if (toUpdate.size() == 0) {
return;
}
int count = 0;
final ArrayList<Chunk> chunks = new ArrayList<Chunk>();
final Iterator<Entry<ChunkLoc, Chunk>> i = toUpdate.entrySet().iterator();
while (i.hasNext() && (count < 128))
{
chunks.add(i.next().getValue());
i.remove();
count++;
}
if (count == 0) {
return;
}
update(chunks);
}
}, 1);
chunksender = new SendChunk();
}
private final ChunkLoc lastLoc = null;
/**
* Set the block at the location
*
* @param world World in which the block should be set
* @param x X Coordinate
* @param y Y Coordinate
* @param z Z Coordinate
* @param id Block ID
* @param data Block Data Value
*/
@SuppressWarnings("deprecation")
@Override
public void set(final World world, final int x, final int y, final int z, final int id, final byte data)
{
if (id == -1)
{
world.getBlockAt(x, y, z).setData(data, false);
return;
}
// Start blockstate workaround //
switch (id)
{
case 54:
case 130:
case 142:
case 132:
case 27:
case 137:
case 52:
case 154:
case 84:
case 25:
case 144:
case 138:
case 176:
case 177:
case 119:
case 63:
case 68:
case 323:
case 117:
case 116:
case 28:
case 66:
case 157:
case 61:
case 62:
case 140:
case 146:
case 149:
case 150:
case 158:
case 23:
case 123:
case 124:
case 29:
case 33:
case 151:
case 178:
{
final Block block = world.getBlockAt(x, y, z);
if (block.getData() == data)
{
if (block.getTypeId() != id)
{
block.setTypeId(id, false);
}
}
else
{
if (block.getTypeId() == id)
{
block.setData(data, false);
}
else
{
block.setTypeIdAndData(id, data, false);
}
}
return;
}
}
// Start data value shortcut
final Block block = world.getBlockAt(x, y, z);
final int currentId = block.getTypeId();
if (currentId == id)
{
switch (id)
{
case 0:
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 24:
case 25:
case 30:
case 32:
case 37:
case 39:
case 40:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 51:
case 52:
case 54:
case 55:
case 56:
case 57:
case 58:
case 60:
case 61:
case 62:
case 7:
case 8:
case 9:
case 10:
case 11:
case 73:
case 74:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 84:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 117:
case 121:
case 122:
case 123:
case 124:
case 129:
case 133:
case 138:
case 137:
case 140:
case 165:
case 166:
case 169:
case 170:
case 172:
case 173:
case 174:
case 176:
case 177:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192:
{
return;
}
}
if (block.getData() == data) { return; }
block.setData(data);
return;
}
// blockstate
switch (currentId)
{
case 54:
case 130:
case 132:
case 142:
case 27:
case 137:
case 52:
case 154:
case 84:
case 25:
case 144:
case 138:
case 176:
case 177:
case 63:
case 68:
case 323:
case 117:
case 119:
case 116:
case 28:
case 66:
case 157:
case 61:
case 62:
case 140:
case 146:
case 149:
case 150:
case 158:
case 23:
case 123:
case 124:
case 29:
case 33:
case 151:
case 178:
{
if (block.getData() == data)
{
block.setTypeId(id, false);
}
else
{
block.setTypeIdAndData(id, data, false);
}
return;
}
}
// End blockstate workaround //
final int X = x >> 4;
final int Z = z >> 4;
final ChunkLoc loc = new ChunkLoc(X, Z);
if (!loc.equals(lastLoc))
{
Chunk chunk = toUpdate.get(loc);
if (chunk == null)
{
chunk = world.getChunkAt(X, Z);
toUpdate.put(loc, chunk);
}
chunk.load(false);
}
// check sign
final Object w = methodGetHandle.of(world).call();
final Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
final Object pos = constructorBlockPosition.create(x & 0x0f, y, z & 0x0f);
final Object combined = methodGetByCombinedId.of(null).call(id + (data << 12));
methodA.of(chunk).call(pos, combined);
}
@Override
public void update(final Collection<Chunk> chunks)
{
if (chunks.size() == 0) { return; }
if (!MainUtil.canSendChunk)
{
for (final Chunk chunk : chunks)
{
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try
{
chunksender.sendChunk(chunks);
}
catch (final Throwable e)
{
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}

View File

@ -6,29 +6,40 @@ import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
public class SetBlockSlow extends BukkitSetBlockManager {
public class SetBlockSlow extends BukkitSetBlockManager
{
@Override
public void set(final World world, final int x, final int y, final int z, final int id, final byte data) {
public void set(final World world, final int x, final int y, final int z, final int id, final byte data)
{
final Block block = world.getBlockAt(x, y, z);
if (id == -1) {
if (id == -1)
{
block.setData(data, false);
return;
}
if (block.getData() == data) {
if (block.getTypeId() != id) {
if (block.getData() == data)
{
if (block.getTypeId() != id)
{
block.setTypeId(id, false);
}
} else {
if (block.getTypeId() == id) {
}
else
{
if (block.getTypeId() == id)
{
block.setData(data, false);
} else {
}
else
{
block.setTypeIdAndData(id, data, false);
}
}
}
@Override
public void update(final Collection<Chunk> chunks) {
public void update(final Collection<Chunk> chunks)
{
// TODO nothing
}
}

View File

@ -14,29 +14,31 @@ import com.intellectualcrafters.plot.generator.PlotGenerator;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.plotsquared.bukkit.generator.AugmentedPopulator;
public class SetGenCB {
public static void setGenerator(World world) throws Exception {
public class SetGenCB
{
public static void setGenerator(final World world) throws Exception
{
SetupUtils.manager.updateGenerators();
PS.get().removePlotWorldAbs(world.getName());
ChunkGenerator gen = world.getGenerator();
if (gen == null) {
return;
}
String name = gen.getClass().getCanonicalName();
final ChunkGenerator gen = world.getGenerator();
if (gen == null) { return; }
final String name = gen.getClass().getCanonicalName();
boolean set = false;
for (PlotGenerator<?> wrapper : SetupUtils.generators.values()) {
ChunkGenerator newGen = (ChunkGenerator) wrapper.generator;
if (newGen.getClass().getCanonicalName().equals(name)) {
for (final PlotGenerator<?> wrapper : SetupUtils.generators.values())
{
final ChunkGenerator newGen = (ChunkGenerator) wrapper.generator;
if (newGen.getClass().getCanonicalName().equals(name))
{
// set generator
Field generator = world.getClass().getDeclaredField("generator");
Field populators = world.getClass().getDeclaredField("populators");
final Field generator = world.getClass().getDeclaredField("generator");
final Field populators = world.getClass().getDeclaredField("populators");
generator.setAccessible(true);
populators.setAccessible(true);
// Set populators (just in case)
populators.set(world, new ArrayList<>());
// Set generator
Constructor<? extends ChunkGenerator> constructor = newGen.getClass().getConstructor(String.class);
ChunkGenerator newNewGen = constructor.newInstance(world.getName());
final Constructor<? extends ChunkGenerator> constructor = newGen.getClass().getConstructor(String.class);
final ChunkGenerator newNewGen = constructor.newInstance(world.getName());
generator.set(world, newNewGen);
populators.set(world, newNewGen.getDefaultPopulators(world));
// end
@ -44,10 +46,13 @@ public class SetGenCB {
break;
}
}
if (!set) {
Iterator<BlockPopulator> iter = world.getPopulators().iterator();
while (iter.hasNext()) {
if (iter.next() instanceof AugmentedPopulator) {
if (!set)
{
final Iterator<BlockPopulator> iter = world.getPopulators().iterator();
while (iter.hasNext())
{
if (iter.next() instanceof AugmentedPopulator)
{
iter.remove();
}
}

View File

@ -13,21 +13,26 @@ import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitWorld;
public class WorldEditSchematic {
public void saveSchematic(String file, final String world, final PlotId id) {
Location bot = MainUtil.getPlotBottomLoc(world, id).add(1, 0, 1);
Location top = MainUtil.getPlotTopLoc(world, id);
Vector size = new Vector(top.getX() - bot.getX() + 1, top.getY() - bot.getY() - 1, top.getZ() - bot.getZ() + 1);
Vector origin = new Vector(bot.getX(), bot.getY(), bot.getZ());
CuboidClipboard clipboard = new CuboidClipboard(size, origin);
Vector pos1 = new Vector(bot.getX(), bot.getY(), bot.getZ());
Vector pos2 = new Vector(top.getX(), top.getY(), top.getZ());
EditSession session = BukkitMain.worldEdit.getWorldEdit().getEditSessionFactory().getEditSession(new BukkitWorld(Bukkit.getWorld(world)), 999999999);
public class WorldEditSchematic
{
public void saveSchematic(final String file, final String world, final PlotId id)
{
final Location bot = MainUtil.getPlotBottomLoc(world, id).add(1, 0, 1);
final Location top = MainUtil.getPlotTopLoc(world, id);
final Vector size = new Vector((top.getX() - bot.getX()) + 1, top.getY() - bot.getY() - 1, (top.getZ() - bot.getZ()) + 1);
final Vector origin = new Vector(bot.getX(), bot.getY(), bot.getZ());
final CuboidClipboard clipboard = new CuboidClipboard(size, origin);
new Vector(bot.getX(), bot.getY(), bot.getZ());
new Vector(top.getX(), top.getY(), top.getZ());
final EditSession session = BukkitMain.worldEdit.getWorldEdit().getEditSessionFactory().getEditSession(new BukkitWorld(Bukkit.getWorld(world)), 999999999);
clipboard.copy(session);
try {
try
{
clipboard.saveSchematic(new File(file));
MainUtil.sendMessage(null, "&7 - &a success: " + id);
} catch (Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
MainUtil.sendMessage(null, "&7 - Failed to save &c" + id);
}

View File

@ -11,32 +11,39 @@ import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
import com.plotsquared.bukkit.object.BukkitPlayer;
public class DefaultUUIDWrapper extends UUIDWrapper {
public class DefaultUUIDWrapper extends UUIDWrapper
{
@Override
public UUID getUUID(final PlotPlayer player) {
public UUID getUUID(final PlotPlayer player)
{
return ((BukkitPlayer) player).player.getUniqueId();
}
@Override
public UUID getUUID(final OfflinePlotPlayer player) {
public UUID getUUID(final OfflinePlotPlayer player)
{
return player.getUUID();
}
@Override
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid) {
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid)
{
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid));
}
@Override
public UUID getUUID(final String name) {
public UUID getUUID(final String name)
{
return Bukkit.getOfflinePlayer(name).getUniqueId();
}
@Override
public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length] ;
for (int i = 0; i < ops.length; i++) {
public OfflinePlotPlayer[] getOfflinePlayers()
{
final OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
final BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++)
{
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;

View File

@ -31,104 +31,134 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
public class FileUUIDHandler extends UUIDHandlerImplementation {
public class FileUUIDHandler extends UUIDHandlerImplementation
{
public FileUUIDHandler(UUIDWrapper wrapper) {
public FileUUIDHandler(final UUIDWrapper wrapper)
{
super(wrapper);
}
@Override
public boolean startCaching(Runnable whenDone) {
if (!super.startCaching(whenDone)) {
return false;
}
public boolean startCaching(final Runnable whenDone)
{
if (!super.startCaching(whenDone)) { return false; }
return cache(whenDone);
}
public boolean cache(final Runnable whenDone) {
public boolean cache(final Runnable whenDone)
{
final File container = Bukkit.getWorldContainer();
List<World> worlds = Bukkit.getWorlds();
final List<World> worlds = Bukkit.getWorlds();
final String world;
if (worlds.size() == 0) {
if (worlds.size() == 0)
{
world = "world";
}
else {
else
{
world = worlds.get(0).getName();
}
TaskManager.runTaskAsync(new Runnable() {
TaskManager.runTaskAsync(new Runnable()
{
@Override
public void run() {
public void run()
{
PS.debug(C.PREFIX.s() + "&6Starting player data caching for: " + world);
File uuidfile = new File(PS.get().IMP.getDirectory(), "uuids.txt");
if (uuidfile.exists()) {
try {
List<String> lines = Files.readAllLines(uuidfile.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
try {
final File uuidfile = new File(PS.get().IMP.getDirectory(), "uuids.txt");
if (uuidfile.exists())
{
try
{
final List<String> lines = Files.readAllLines(uuidfile.toPath(), StandardCharsets.UTF_8);
for (String line : lines)
{
try
{
line = line.trim();
if (line.length() == 0) {
if (line.length() == 0)
{
continue;
}
line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", "");
String[] split = line.split("\\|");
String name = split[0];
if (name.length() == 0 || name.length() > 16 || !StringMan.isAlphanumericUnd(name)) {
final String[] split = line.split("\\|");
final String name = split[0];
if ((name.length() == 0) || (name.length() > 16) || !StringMan.isAlphanumericUnd(name))
{
continue;
}
UUID uuid = uuidWrapper.getUUID(name);
if (uuid == null) {
final UUID uuid = uuidWrapper.getUUID(name);
if (uuid == null)
{
continue;
}
UUIDHandler.add(new StringWrapper(name), uuid);
}
catch (Exception e2) {
catch (final Exception e2)
{
e2.printStackTrace();
}
}
} catch (IOException e) {
}
catch (final IOException e)
{
e.printStackTrace();
}
}
if (Settings.TWIN_MODE_UUID) {
if (Settings.TWIN_MODE_UUID)
{
final HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
toAdd.put(new StringWrapper("*"), DBFunc.everyone);
HashSet<UUID> all = UUIDHandler.getAllUUIDS();
final HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PS.debug("&aFast mode UUID caching enabled!");
final File playerdataFolder = new File(container, world + File.separator + "playerdata");
String[] dat = playerdataFolder.list(new FilenameFilter() {
final String[] dat = playerdataFolder.list(new FilenameFilter()
{
@Override
public boolean accept(final File f, final String s) {
public boolean accept(final File f, final String s)
{
return s.endsWith(".dat");
}
});
boolean check = all.size() == 0;
if (dat != null) {
for (final String current : dat) {
final boolean check = all.size() == 0;
if (dat != null)
{
for (final String current : dat)
{
final String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
if (check || all.remove(uuid)) {
File file = new File(playerdataFolder + File.separator + current);
InputSupplier<FileInputStream> is = com.google.common.io.Files.newInputStreamSupplier(file);
NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION);
NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
long last = (long) bukkit.get("lastPlayed");
try
{
final UUID uuid = UUID.fromString(s);
if (check || all.remove(uuid))
{
final File file = new File(playerdataFolder + File.separator + current);
final InputSupplier<FileInputStream> is = com.google.common.io.Files.newInputStreamSupplier(file);
final NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION);
final NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
final String name = (String) bukkit.get("lastKnownName");
final long last = (long) bukkit.get("lastPlayed");
ExpireManager.dates.put(uuid, last);
toAdd.put(new StringWrapper(name), uuid);
}
} catch (final Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
PS.debug(C.PREFIX.s() + "Invalid playerdata: " + current);
}
}
}
add(toAdd);
if (all.size() == 0) {
if (whenDone != null) whenDone.run();
if (all.size() == 0)
{
if (whenDone != null)
{
whenDone.run();
}
return;
}
else {
else
{
PS.debug("Failed to cache: " + all.size() + " uuids - slowly processing all files");
}
}
@ -140,22 +170,30 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
final HashSet<UUID> uuids = new HashSet<>();
final HashSet<String> names = new HashSet<>();
File playerdataFolder = null;
for (final String worldname : worlds) {
for (final String worldname : worlds)
{
// Getting UUIDs
playerdataFolder = new File(container, worldname + File.separator + "playerdata");
String[] dat = playerdataFolder.list(new FilenameFilter() {
String[] dat = playerdataFolder.list(new FilenameFilter()
{
@Override
public boolean accept(final File f, final String s) {
public boolean accept(final File f, final String s)
{
return s.endsWith(".dat");
}
});
if (dat != null && dat.length != 0) {
for (final String current : dat) {
if ((dat != null) && (dat.length != 0))
{
for (final String current : dat)
{
final String s = current.replaceAll(".dat$", "");
try {
try
{
final UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (final Exception e) {
}
catch (final Exception e)
{
PS.debug(C.PREFIX.s() + "Invalid playerdata: " + current);
}
}
@ -163,72 +201,94 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
}
// Getting names
final File playersFolder = new File(worldname + File.separator + "players");
dat = playersFolder.list(new FilenameFilter() {
dat = playersFolder.list(new FilenameFilter()
{
@Override
public boolean accept(final File f, final String s) {
public boolean accept(final File f, final String s)
{
return s.endsWith(".dat");
}
});
if (dat != null && dat.length != 0) {
for (final String current : dat) {
if ((dat != null) && (dat.length != 0))
{
for (final String current : dat)
{
names.add(current.replaceAll(".dat$", ""));
}
break;
}
}
for (UUID uuid : uuids) {
try {
File file = new File(playerdataFolder + File.separator + uuid.toString() + ".dat");
InputSupplier<FileInputStream> is = com.google.common.io.Files.newInputStreamSupplier(file);
NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION);
NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
long last = (long) bukkit.get("lastPlayed");
if (Settings.OFFLINE_MODE) {
if (Settings.UUID_LOWERCASE && !name.toLowerCase().equals(name)) {
for (UUID uuid : uuids)
{
try
{
final File file = new File(playerdataFolder + File.separator + uuid.toString() + ".dat");
final InputSupplier<FileInputStream> is = com.google.common.io.Files.newInputStreamSupplier(file);
final NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION);
final NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
final String name = (String) bukkit.get("lastKnownName");
final long last = (long) bukkit.get("lastPlayed");
if (Settings.OFFLINE_MODE)
{
if (Settings.UUID_LOWERCASE && !name.toLowerCase().equals(name))
{
uuid = uuidWrapper.getUUID(name);
} else {
long most = (long) compound.get("UUIDMost");
long least = (long) compound.get("UUIDLeast");
}
else
{
final long most = (long) compound.get("UUIDMost");
final long least = (long) compound.get("UUIDLeast");
uuid = new UUID(most, least);
}
}
ExpireManager.dates.put(uuid, last);
toAdd.put(new StringWrapper(name), uuid);
} catch (final Throwable e) {
}
catch (final Throwable e)
{
PS.debug(C.PREFIX.s() + "&6Invalid playerdata: " + uuid.toString() + ".dat");
}
}
for (final String name : names) {
for (final String name : names)
{
final UUID uuid = uuidWrapper.getUUID(name);
final StringWrapper nameWrap = new StringWrapper(name);
toAdd.put(nameWrap, uuid);
}
if (getUUIDMap().size() == 0) {
for (OfflinePlotPlayer op : uuidWrapper.getOfflinePlayers()) {
long last = op.getLastPlayed();
if (last != 0) {
String name = op.getName();
StringWrapper wrap = new StringWrapper(name);
UUID uuid = uuidWrapper.getUUID(op);
if (getUUIDMap().size() == 0)
{
for (final OfflinePlotPlayer op : uuidWrapper.getOfflinePlayers())
{
final long last = op.getLastPlayed();
if (last != 0)
{
final String name = op.getName();
final StringWrapper wrap = new StringWrapper(name);
final UUID uuid = uuidWrapper.getUUID(op);
toAdd.put(wrap, uuid);
ExpireManager.dates.put(uuid, last);
}
}
}
add(toAdd);
if (whenDone != null) whenDone.run();
if (whenDone != null)
{
whenDone.run();
}
}
});
return true;
}
@Override
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(new Runnable() {
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch)
{
TaskManager.runTaskAsync(new Runnable()
{
@Override
public void run() {
public void run()
{
ifFetch.value = uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch);
}

View File

@ -18,87 +18,109 @@ import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper {
public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper
{
private Method getOnline = null;
private final Object[] arg = new Object[0];
public LowerOfflineUUIDWrapper() {
try {
this.getOnline = Server.class.getMethod("getOnlinePlayers", new Class[0]);
} catch (final NoSuchMethodException e) {
public LowerOfflineUUIDWrapper()
{
try
{
getOnline = Server.class.getMethod("getOnlinePlayers", new Class[0]);
}
catch (final NoSuchMethodException e)
{
e.printStackTrace();
} catch (final SecurityException e) {
}
catch (final SecurityException e)
{
e.printStackTrace();
}
}
@Override
public UUID getUUID(final PlotPlayer player) {
public UUID getUUID(final PlotPlayer player)
{
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(final OfflinePlotPlayer player) {
public UUID getUUID(final OfflinePlotPlayer player)
{
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
public UUID getUUID(final OfflinePlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase() ).getBytes(Charsets.UTF_8));
@Override
public UUID getUUID(final OfflinePlayer player)
{
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid) {
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid)
{
final BiMap<UUID, StringWrapper> map = UUIDHandler.getUuidMap().inverse();
String name;
try {
try
{
name = map.get(uuid).value;
} catch (final NullPointerException e) {
}
catch (final NullPointerException e)
{
name = null;
}
if (name != null) {
if (name != null)
{
final OfflinePlayer op = Bukkit.getOfflinePlayer(name);
if (op.hasPlayedBefore()) {
return new BukkitOfflinePlayer(op);
}
if (op.hasPlayedBefore()) { return new BukkitOfflinePlayer(op); }
}
for (final OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (getUUID(player).equals(uuid)) {
return new BukkitOfflinePlayer(player);
}
for (final OfflinePlayer player : Bukkit.getOfflinePlayers())
{
if (getUUID(player).equals(uuid)) { return new BukkitOfflinePlayer(player); }
}
return null;
}
public Player[] getOnlinePlayers() {
if (this.getOnline == null) {
return Bukkit.getOnlinePlayers().toArray(new Player[0]);
}
try {
final Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg);
if (players instanceof Player[]) {
@Override
public Player[] getOnlinePlayers()
{
if (getOnline == null) { return Bukkit.getOnlinePlayers().toArray(new Player[0]); }
try
{
final Object players = getOnline.invoke(Bukkit.getServer(), arg);
if (players instanceof Player[])
{
return (Player[]) players;
} else {
}
else
{
@SuppressWarnings("unchecked")
final Collection<? extends Player> p = (Collection<? extends Player>) players;
return p.toArray(new Player[0]);
}
} catch (final Exception e) {
}
catch (final Exception e)
{
PS.debug("Failed to resolve online players");
this.getOnline = null;
getOnline = null;
return Bukkit.getOnlinePlayers().toArray(new Player[0]);
}
}
@Override
public UUID getUUID(final String name) {
public UUID getUUID(final String name)
{
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length] ;
for (int i = 0; i < ops.length; i++) {
public OfflinePlotPlayer[] getOfflinePlayers()
{
final OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
final BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++)
{
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;

View File

@ -19,87 +19,107 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
public class OfflineUUIDWrapper extends UUIDWrapper {
public class OfflineUUIDWrapper extends UUIDWrapper
{
private Method getOnline = null;
private final Object[] arg = new Object[0];
public OfflineUUIDWrapper() {
try {
this.getOnline = Server.class.getMethod("getOnlinePlayers", new Class[0]);
} catch (final NoSuchMethodException e) {
public OfflineUUIDWrapper()
{
try
{
getOnline = Server.class.getMethod("getOnlinePlayers", new Class[0]);
}
catch (final NoSuchMethodException e)
{
e.printStackTrace();
} catch (final SecurityException e) {
}
catch (final SecurityException e)
{
e.printStackTrace();
}
}
@Override
public UUID getUUID(final PlotPlayer player) {
public UUID getUUID(final PlotPlayer player)
{
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(final OfflinePlotPlayer player) {
public UUID getUUID(final OfflinePlotPlayer player)
{
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
}
public UUID getUUID(final OfflinePlayer player) {
public UUID getUUID(final OfflinePlayer player)
{
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
}
@Override
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid) {
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid)
{
final BiMap<UUID, StringWrapper> map = UUIDHandler.getUuidMap().inverse();
String name;
try {
try
{
name = map.get(uuid).value;
} catch (final NullPointerException e) {
}
catch (final NullPointerException e)
{
name = null;
}
if (name != null) {
if (name != null)
{
final OfflinePlayer op = Bukkit.getOfflinePlayer(name);
if (op.hasPlayedBefore()) {
return new BukkitOfflinePlayer(op);
}
if (op.hasPlayedBefore()) { return new BukkitOfflinePlayer(op); }
}
for (final OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (getUUID(player).equals(uuid)) {
return new BukkitOfflinePlayer(player);
}
for (final OfflinePlayer player : Bukkit.getOfflinePlayers())
{
if (getUUID(player).equals(uuid)) { return new BukkitOfflinePlayer(player); }
}
return null;
}
public Player[] getOnlinePlayers() {
if (this.getOnline == null) {
return Bukkit.getOnlinePlayers().toArray(new Player[0]);
}
try {
final Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg);
if (players instanceof Player[]) {
public Player[] getOnlinePlayers()
{
if (getOnline == null) { return Bukkit.getOnlinePlayers().toArray(new Player[0]); }
try
{
final Object players = getOnline.invoke(Bukkit.getServer(), arg);
if (players instanceof Player[])
{
return (Player[]) players;
} else {
}
else
{
@SuppressWarnings("unchecked")
final Collection<? extends Player> p = (Collection<? extends Player>) players;
return p.toArray(new Player[0]);
}
} catch (final Exception e) {
}
catch (final Exception e)
{
PS.debug("Failed to resolve online players");
this.getOnline = null;
getOnline = null;
return Bukkit.getOnlinePlayers().toArray(new Player[0]);
}
}
@Override
public UUID getUUID(final String name) {
public UUID getUUID(final String name)
{
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8));
}
@Override
public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length] ;
for (int i = 0; i < ops.length; i++) {
public OfflinePlotPlayer[] getOfflinePlayers()
{
final OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
final BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++)
{
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;

View File

@ -29,60 +29,72 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
public class SQLUUIDHandler extends UUIDHandlerImplementation {
public SQLUUIDHandler(UUIDWrapper wrapper) {
public class SQLUUIDHandler extends UUIDHandlerImplementation
{
public SQLUUIDHandler(final UUIDWrapper wrapper)
{
super(wrapper);
_sqLite = new SQLite("./plugins/PlotSquared/usercache.db");
try {
try
{
_sqLite.openConnection();
} catch (final Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
}
try {
PreparedStatement stmt = getConnection().prepareStatement("CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username))");
try
{
final PreparedStatement stmt = getConnection()
.prepareStatement("CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username))");
stmt.execute();
stmt.close();
} catch (SQLException e) {
}
catch (final SQLException e)
{
e.printStackTrace();
}
startCaching(null);
}
private class SQLUUIDHandlerException extends RuntimeException {
SQLUUIDHandlerException(String s, Throwable c) {
private class SQLUUIDHandlerException extends RuntimeException
{
SQLUUIDHandlerException(final String s, final Throwable c)
{
super("SQLUUIDHandler caused an exception: " + s, c);
}
@SuppressWarnings("unused")
SQLUUIDHandlerException(String s) {
super("SQLUUIDHandler caused an exception: " + s);
}
}
private final SQLite _sqLite;
private Connection getConnection() {
synchronized (_sqLite) {
private Connection getConnection()
{
synchronized (_sqLite)
{
return _sqLite.getConnection();
}
}
@Override
public boolean startCaching(final Runnable whenDone) {
if (!super.startCaching(whenDone)) {
return false;
}
TaskManager.runTaskAsync(new Runnable() {
public boolean startCaching(final Runnable whenDone)
{
if (!super.startCaching(whenDone)) { return false; }
TaskManager.runTaskAsync(new Runnable()
{
@Override
public void run() {
try {
public void run()
{
try
{
final HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery();
final PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
final ResultSet resultSet = statement.executeQuery();
StringWrapper username;
UUID uuid;
while (resultSet.next()) {
while (resultSet.next())
{
username = new StringWrapper(resultSet.getString("username"));
uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid);
@ -90,131 +102,176 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
statement.close();
add(toAdd);
add(new StringWrapper("*"), DBFunc.everyone);
// This should be called as long as there are some unknown plots
final List<UUID> toFetch = new ArrayList<>();
for (UUID u : UUIDHandler.getAllUUIDS()) {
if (!uuidExists(u)) {
for (final UUID u : UUIDHandler.getAllUUIDS())
{
if (!uuidExists(u))
{
toFetch.add(u);
}
}
if (toFetch.isEmpty()) {
if (whenDone != null) whenDone.run();
if (toFetch.isEmpty())
{
if (whenDone != null)
{
whenDone.run();
}
return;
}
FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable() {
final FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable()
{
@Override
public void run() {
public void run()
{
// If the file based UUID handler didn't cache it, then we can't cache offline mode
// Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does
if (Settings.OFFLINE_MODE) {
if (whenDone != null) whenDone.run();
if (Settings.OFFLINE_MODE)
{
if (whenDone != null)
{
whenDone.run();
}
return;
}
if (!Settings.OFFLINE_MODE) {
if (!Settings.OFFLINE_MODE)
{
PS.debug(C.PREFIX.s() + "&cWill fetch &6" + toFetch.size() + "&c from mojang!");
int i = 0;
Iterator<UUID> iterator = toFetch.iterator();
while (iterator.hasNext()) {
StringBuilder url = new StringBuilder("http://api.intellectualsites.com/uuid/?user=");
List<UUID> currentIteration = new ArrayList<>();
while (i++ <= 15 && iterator.hasNext()) {
UUID _uuid = iterator.next();
final Iterator<UUID> iterator = toFetch.iterator();
while (iterator.hasNext())
{
final StringBuilder url = new StringBuilder("http://api.intellectualsites.com/uuid/?user=");
final List<UUID> currentIteration = new ArrayList<>();
while ((i++ <= 15) && iterator.hasNext())
{
final UUID _uuid = iterator.next();
url.append(_uuid.toString());
if (iterator.hasNext()) {
if (iterator.hasNext())
{
url.append(",");
}
currentIteration.add(_uuid);
}
PS.debug(C.PREFIX.s() + "&cWill attempt to fetch &6" + currentIteration.size() + "&c uuids from: &6" + url.toString());
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url.toString()).openConnection();
try
{
final HttpURLConnection connection = (HttpURLConnection) new URL(url.toString()).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null) {
final StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null)
{
rawJSON.append(line);
}
reader.close();
JSONObject object = new JSONObject(rawJSON.toString());
for (UUID _u : currentIteration) {
Object o = object.getJSONObject(_u.toString().replace("-", "")).get("username");
if (o == null || !(o instanceof String)) {
final JSONObject object = new JSONObject(rawJSON.toString());
for (final UUID _u : currentIteration)
{
final Object o = object.getJSONObject(_u.toString().replace("-", "")).get("username");
if ((o == null) || !(o instanceof String))
{
continue;
}
add(new StringWrapper(o.toString()), _u);
}
} catch (final Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
}
i = 0;
}
}
if (whenDone != null) whenDone.run();
if (whenDone != null)
{
whenDone.run();
}
}
});
} catch (SQLException e) {
}
catch (final SQLException e)
{
throw new SQLUUIDHandlerException("Couldn't select :s", e);
}
}
});
return true;
}
@Override
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch)
{
PS.debug(C.PREFIX.s() + "UUID for '" + name + "' was null. We'll cache this from the mojang servers!");
TaskManager.runTaskAsync(new Runnable() {
TaskManager.runTaskAsync(new Runnable()
{
@Override
public void run() {
String url = "http://api.intellectualsites.com/uuid/?user=" + name;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
public void run()
{
final String url = "http://api.intellectualsites.com/uuid/?user=" + name;
try
{
final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null) {
final StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null)
{
rawJSON.append(line);
}
reader.close();
JSONObject object = new JSONObject(rawJSON.toString());
final JSONObject object = new JSONObject(rawJSON.toString());
ifFetch.value = UUID.fromString(object.getJSONObject(name).getString("dashed"));
add(new StringWrapper(name), ifFetch.value);
} catch (IOException e) {
}
catch (final IOException e)
{
e.printStackTrace();
}
TaskManager.runTask(ifFetch);
}
});
}
@Override
public void handleShutdown() {
public void handleShutdown()
{
super.handleShutdown();
try {
try
{
getConnection().close();
} catch (SQLException e) {
}
catch (final SQLException e)
{
throw new SQLUUIDHandlerException("Couldn't close database connection", e);
}
}
@Override
public boolean add(final StringWrapper name, final UUID uuid) {
public boolean add(final StringWrapper name, final UUID uuid)
{
// Ignoring duplicates
if (super.add(name, uuid)) {
TaskManager.runTaskAsync(new Runnable() {
if (super.add(name, uuid))
{
TaskManager.runTaskAsync(new Runnable()
{
@Override
public void run() {
try {
PreparedStatement statement = getConnection().prepareStatement("INSERT INTO usercache (`uuid`, `username`) VALUES(?, ?)");
public void run()
{
try
{
final PreparedStatement statement = getConnection().prepareStatement("INSERT INTO usercache (`uuid`, `username`) VALUES(?, ?)");
statement.setString(1, uuid.toString());
statement.setString(2, name.toString());
statement.execute();
PS.debug(C.PREFIX.s() + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'");
} catch (SQLException e) {
}
catch (final SQLException e)
{
e.printStackTrace();
}
}
@ -223,33 +280,40 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
}
return false;
}
/**
* This isn't used as any UUID that is unknown is bulk cached (in lots of 16)
* @param uuid
* @return
*/
@Deprecated
public String getName__unused__(final UUID uuid) {
public String getName__unused__(final UUID uuid)
{
PS.debug(C.PREFIX.s() + "Name for '" + uuid + "' was null. We'll cache this from the mojang servers!");
TaskManager.runTaskAsync(new Runnable() {
TaskManager.runTaskAsync(new Runnable()
{
@Override
public void run() {
String url = "http://api.intellectualsites.com/uuid/?user=" + uuid;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
public void run()
{
final String url = "http://api.intellectualsites.com/uuid/?user=" + uuid;
try
{
final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null) {
final StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null)
{
rawJSON.append(line);
}
reader.close();
JSONObject object = new JSONObject(rawJSON.toString());
String username = object.getJSONObject(uuid.toString().replace("-", "")).getString("username");
final JSONObject object = new JSONObject(rawJSON.toString());
final String username = object.getJSONObject(uuid.toString().replace("-", "")).getString("username");
add(new StringWrapper(username), uuid);
} catch (IOException e) {
}
catch (final IOException e)
{
e.printStackTrace();
}
}
@ -258,18 +322,24 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
}
@Override
public void rename(final UUID uuid, final StringWrapper name) {
public void rename(final UUID uuid, final StringWrapper name)
{
super.rename(uuid, name);
TaskManager.runTaskAsync(new Runnable() {
TaskManager.runTaskAsync(new Runnable()
{
@Override
public void run() {
try {
PreparedStatement statement = getConnection().prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?");
public void run()
{
try
{
final PreparedStatement statement = getConnection().prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?");
statement.setString(1, name.value);
statement.setString(2, uuid.toString());
statement.execute();
PS.debug(C.PREFIX.s() + "Name change for '" + uuid + "' to '" + name.value + "'");
} catch (SQLException e) {
}
catch (final SQLException e)
{
e.printStackTrace();
}
}

View File

@ -5,79 +5,102 @@ import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.util.MainUtil;
public abstract class Argument<T> {
public abstract class Argument<T>
{
private final String name;
private final T example;
public Argument(String name, T example) {
public Argument(final String name, final T example)
{
this.name = name;
this.example = example;
}
public abstract T parse(String in);
public abstract T parse(final String in);
@Override
public final String toString() {
public final String toString()
{
return this.getName();
}
public final String getName() {
public final String getName()
{
return this.name;
}
public final T getExample() {
public final T getExample()
{
return this.example;
}
public static final Argument<Integer> Integer = new Argument<Integer>("int", 16) {
public static final Argument<Integer> Integer = new Argument<Integer>("int", 16)
{
@Override
public Integer parse(String in) {
public Integer parse(final String in)
{
Integer value = null;
try {
try
{
value = java.lang.Integer.parseInt(in);
} catch(final Exception ignored) {}
}
catch (final Exception ignored)
{}
return value;
}
};
public static final Argument<Boolean> Boolean = new Argument<Boolean>("boolean", true) {
public static final Argument<Boolean> Boolean = new Argument<Boolean>("boolean", true)
{
@Override
public Boolean parse(String in) {
public Boolean parse(final String in)
{
Boolean value = null;
if (in.equalsIgnoreCase("true") || in.equalsIgnoreCase("Yes") || in.equalsIgnoreCase("1")) {
if (in.equalsIgnoreCase("true") || in.equalsIgnoreCase("Yes") || in.equalsIgnoreCase("1"))
{
value = true;
} else if (in.equalsIgnoreCase("false") || in.equalsIgnoreCase("No") || in.equalsIgnoreCase("0")) {
}
else if (in.equalsIgnoreCase("false") || in.equalsIgnoreCase("No") || in.equalsIgnoreCase("0"))
{
value = false;
}
return value;
}
};
public static final Argument<String> String = new Argument<String>("String", "Example") {
public static final Argument<String> String = new Argument<String>("String", "Example")
{
@Override
public String parse(String in) {
public String parse(final String in)
{
return in;
}
};
public static Argument<String> PlayerName = new Argument<String>("PlayerName", "Dinnerbone") {
public static Argument<String> PlayerName = new Argument<String>("PlayerName", "Dinnerbone")
{
@Override
public String parse(String in) {
public String parse(final String in)
{
return in.length() <= 16 ? in : null;
}
};
public static Argument<PlotId> PlotID = new Argument<PlotId>("PlotID", new PlotId(-6, 3)) {
public static Argument<PlotId> PlotID = new Argument<PlotId>("PlotID", new PlotId(-6, 3))
{
@Override
public PlotId parse(String in) {
public PlotId parse(final String in)
{
return PlotId.fromString(in);
}
};
public static Argument<Plot> Plot = new Argument<Plot>("Plot", new Plot("plotworld", new PlotId(3, -6), null)) {
public static Argument<Plot> Plot = new Argument<Plot>("Plot", new Plot("plotworld", new PlotId(3, -6), null))
{
@Override
public Plot parse(String in) {
public Plot parse(final String in)
{
return MainUtil.getPlotFromString(ConsolePlayer.getConsole(), in, false);
}
};

View File

@ -9,7 +9,8 @@ import java.util.Set;
import com.intellectualcrafters.plot.commands.CommandCategory;
import com.intellectualcrafters.plot.commands.RequiredType;
public abstract class Command<E extends CommandCaller> extends CommandManager {
public abstract class Command<E extends CommandCaller> extends CommandManager
{
private RequiredType requiredType = RequiredType.NONE;
private String command, usage = "", description = "", permission = "";
@ -17,29 +18,34 @@ public abstract class Command<E extends CommandCaller> extends CommandManager {
private CommandCategory category;
protected Argument<?>[] requiredArguments;
public Command() {
public Command()
{
super(null, new ArrayList<Command>());
}
public Command(String command) {
public Command(final String command)
{
super(null, new ArrayList<Command>());
this.command = command;
}
public Command(String command, String usage) {
public Command(final String command, final String usage)
{
super(null, new ArrayList<Command>());
this.command = command;
this.usage = usage;
}
public Command(String command, String usage, String description) {
public Command(final String command, final String usage, final String description)
{
super(null, new ArrayList<Command>());
this.command = command;
this.usage = usage;
this.description = description;
}
public Command(String command, String usage, String description, String permission) {
public Command(final String command, final String usage, final String description, final String permission)
{
super(null, new ArrayList<Command>());
this.command = command;
this.usage = usage;
@ -47,20 +53,23 @@ public abstract class Command<E extends CommandCaller> extends CommandManager {
this.permission = permission;
}
public Command(String command, String[] aliases, String usage) {
public Command(final String command, final String[] aliases, final String usage)
{
super(null, new ArrayList<Command>());
this.command = command;
this.aliases = new HashSet<>(Arrays.asList(aliases));
this.usage = usage;
}
public Command(String command, String[] aliases) {
public Command(final String command, final String[] aliases)
{
super(null, new ArrayList<Command>());
this.command = command;
this.aliases = new HashSet<>(Arrays.asList(aliases));
}
public Command(String command, String usage, String description, String permission, String[] aliases, RequiredType requiredType) {
public Command(final String command, final String usage, final String description, final String permission, final String[] aliases, final RequiredType requiredType)
{
super(null, new ArrayList<Command>());
this.command = command;
this.usage = usage;
@ -70,16 +79,16 @@ public abstract class Command<E extends CommandCaller> extends CommandManager {
this.requiredType = requiredType;
}
final public RequiredType getRequiredType() {
final public RequiredType getRequiredType()
{
return this.requiredType;
}
final protected void create() {
Annotation annotation = getClass().getAnnotation(CommandDeclaration.class);
if (annotation == null) {
throw new RuntimeException("Command does not have a CommandDeclaration");
}
CommandDeclaration declaration = (CommandDeclaration) annotation;
final protected void create()
{
final Annotation annotation = getClass().getAnnotation(CommandDeclaration.class);
if (annotation == null) { throw new RuntimeException("Command does not have a CommandDeclaration"); }
final CommandDeclaration declaration = (CommandDeclaration) annotation;
this.command = declaration.command();
this.usage = declaration.usage();
this.description = declaration.description();
@ -91,87 +100,85 @@ public abstract class Command<E extends CommandCaller> extends CommandManager {
}
@Override
final public String toString() {
final public String toString()
{
return this.command;
}
public abstract boolean onCommand(E plr, String[] arguments);
public abstract boolean onCommand(final E plr, final String[] arguments);
final public int handle(E plr, String[] args) {
if (args.length == 0) {
return super.handle(plr, "");
}
StringBuilder builder = new StringBuilder();
for (String s : args) {
final public int handle(final E plr, final String[] args)
{
if (args.length == 0) { return super.handle(plr, ""); }
final StringBuilder builder = new StringBuilder();
for (final String s : args)
{
builder.append(s).append(" ");
}
String s = builder.substring(0, builder.length() - 1);
final String s = builder.substring(0, builder.length() - 1);
return super.handle(plr, s);
}
final public String getCommand() {
final public String getCommand()
{
return this.command;
}
public String getUsage() {
if (this.usage.length() == 0) {
return "/{label} " + command;
}
public String getUsage()
{
if (this.usage.length() == 0) { return "/{label} " + command; }
return this.usage;
}
final public String getPermission() {
if (this.permission == null || this.permission.length() == 0) {
final public String getPermission()
{
if ((this.permission == null) || (this.permission.length() == 0))
{
this.permission = "plots." + command.toLowerCase();
}
return this.permission;
}
public String getDescription() {
public String getDescription()
{
return this.description;
}
final public Set<String> getAliases() {
final public Set<String> getAliases()
{
return this.aliases;
}
final public Argument<?>[] getRequiredArguments() {
if (this.requiredArguments == null) {
return new Argument<?>[0];
}
final public Argument<?>[] getRequiredArguments()
{
if (this.requiredArguments == null) { return new Argument<?>[0]; }
return this.requiredArguments;
}
final public CommandCategory getCategory() {
if (category == null) {
return CommandCategory.DEBUG;
}
final public CommandCategory getCategory()
{
if (category == null) { return CommandCategory.DEBUG; }
return this.category;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
public boolean equals(final Object obj)
{
if (this == obj) { return true; }
if (obj == null) { return false; }
if (getClass() != obj.getClass()) { return false; }
final Command<?> other = (Command<?>) obj;
if (this.hashCode() != other.hashCode()) {
return false;
}
if (this.hashCode() != other.hashCode()) { return false; }
return this.command.equals(other.command);
}
private int hash;
@Override
public int hashCode() {
if (hash == 0) {
public int hashCode()
{
if (hash == 0)
{
hash = getCommand().hashCode();
}
return hash;

View File

@ -3,12 +3,13 @@ package com.plotsquared.general.commands;
import com.intellectualcrafters.plot.commands.RequiredType;
import com.intellectualcrafters.plot.config.C;
public interface CommandCaller {
public interface CommandCaller
{
void sendMessage(final String message);
void sendMessage(C c, String ... args);
void sendMessage(final C c, final String... args);
boolean hasPermission(final String perm);
RequiredType getSuperCaller();
}

View File

@ -10,7 +10,8 @@ import com.intellectualcrafters.plot.commands.RequiredType;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CommandDeclaration {
public @interface CommandDeclaration
{
String command();

View File

@ -2,7 +2,8 @@ package com.plotsquared.general.commands;
import java.lang.reflect.Field;
public class CommandHandlingOutput {
public class CommandHandlingOutput
{
public static int CALLER_OF_WRONG_TYPE = -6;
public static int NOT_COMMAND = -5;
@ -13,15 +14,19 @@ public class CommandHandlingOutput {
public static int SUCCESS = 1;
public static String nameField(int code) {
Field[] fields = CommandHandlingOutput.class.getDeclaredFields();
for (final Field field : fields) {
if (field.getGenericType() == Integer.TYPE) {
try {
if ((Integer) field.get(CommandHandlingOutput.class) == code) {
return field.getName();
}
} catch (IllegalAccessException e) {
public static String nameField(final int code)
{
final Field[] fields = CommandHandlingOutput.class.getDeclaredFields();
for (final Field field : fields)
{
if (field.getGenericType() == Integer.TYPE)
{
try
{
if ((Integer) field.get(CommandHandlingOutput.class) == code) { return field.getName(); }
}
catch (final IllegalAccessException e)
{
e.printStackTrace();
}
}

View File

@ -11,141 +11,168 @@ import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.util.Permissions;
@SuppressWarnings("unused")
public class CommandManager<T extends CommandCaller> {
public class CommandManager<T extends CommandCaller>
{
protected final ConcurrentHashMap<String, Command<T>> commands;
protected final Character initialCharacter;
public CommandManager() {
public CommandManager()
{
this('/', new ArrayList<Command<T>>());
}
public CommandManager(Character initialCharacter, List<Command<T>> commands) {
public CommandManager(final Character initialCharacter, final List<Command<T>> commands)
{
this.commands = new ConcurrentHashMap<>();
for (Command<T> command : commands) {
for (final Command<T> command : commands)
{
addCommand(command);
}
this.initialCharacter = initialCharacter;
}
final public void addCommand(final Command<T> command) {
if (command.getCommand() == null) {
final public void addCommand(final Command<T> command)
{
if (command.getCommand() == null)
{
command.create();
}
this.commands.put(command.getCommand().toLowerCase(), command);
for (String alias : command.getAliases()) {
for (final String alias : command.getAliases())
{
this.commands.put(alias.toLowerCase(), command);
}
}
final public Command<T> getCommand(String command) {
final public Command<T> getCommand(final String command)
{
return commands.get(command);
}
final public boolean createCommand(final Command<T> command) {
try {
final public boolean createCommand(final Command<T> command)
{
try
{
command.create();
} catch(final Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
return false;
}
if (command.getCommand() != null) {
if (command.getCommand() != null)
{
addCommand(command);
return true;
}
return false;
}
final public ArrayList<Command<T>> getCommands() {
HashSet<Command<T>> set = new HashSet<>(this.commands.values());
ArrayList<Command<T>> result = new ArrayList<>(set);
Collections.sort(result, new Comparator<Command<T>>() {
final public ArrayList<Command<T>> getCommands()
{
final HashSet<Command<T>> set = new HashSet<>(this.commands.values());
final ArrayList<Command<T>> result = new ArrayList<>(set);
Collections.sort(result, new Comparator<Command<T>>()
{
@Override
public int compare(Command<T> a, Command<T> b) {
public int compare(final Command<T> a, final Command<T> b)
{
if (a == b) {
return 0;
return 0;
}
if (a == null) {
return -1;
return -1;
}
if (b == null) {
return 1;
return 1;
}
return a.getCommand().compareTo(b.getCommand());
}
});
return result;
}
final public ArrayList<String> getCommandLabels(ArrayList<Command<T>> cmds) {
ArrayList<String> labels = new ArrayList<>(cmds.size());
for (Command<T> cmd : cmds) {
final public ArrayList<String> getCommandLabels(final ArrayList<Command<T>> cmds)
{
final ArrayList<String> labels = new ArrayList<>(cmds.size());
for (final Command<T> cmd : cmds)
{
labels.add(cmd.getCommand());
}
return labels;
}
public int handle(T plr, String input) {
if (initialCharacter != null && !input.startsWith(initialCharacter + "")) {
return CommandHandlingOutput.NOT_COMMAND;
}
public int handle(final T plr, String input)
{
if ((initialCharacter != null) && !input.startsWith(initialCharacter + "")) { return CommandHandlingOutput.NOT_COMMAND; }
input = initialCharacter == null ? input : input.substring(1);
String[] parts = input.split(" ");
final String[] parts = input.split(" ");
String[] args;
String command = parts[0].toLowerCase();
if (parts.length == 1) {
final String command = parts[0].toLowerCase();
if (parts.length == 1)
{
args = new String[0];
} else {
}
else
{
args = new String[parts.length - 1];
System.arraycopy(parts, 1, args, 0, args.length);
}
Command<T> cmd = null;
cmd = commands.get(command);
if (cmd == null) {
return CommandHandlingOutput.NOT_FOUND;
}
if (!cmd.getRequiredType().allows(plr)) {
return CommandHandlingOutput.CALLER_OF_WRONG_TYPE;
}
if (!Permissions.hasPermission(plr, cmd.getPermission())) {
return CommandHandlingOutput.NOT_PERMITTED;
}
Argument<?>[] requiredArguments = cmd.getRequiredArguments();
if (requiredArguments != null && requiredArguments.length > 0) {
if (cmd == null) { return CommandHandlingOutput.NOT_FOUND; }
if (!cmd.getRequiredType().allows(plr)) { return CommandHandlingOutput.CALLER_OF_WRONG_TYPE; }
if (!Permissions.hasPermission(plr, cmd.getPermission())) { return CommandHandlingOutput.NOT_PERMITTED; }
final Argument<?>[] requiredArguments = cmd.getRequiredArguments();
if ((requiredArguments != null) && (requiredArguments.length > 0))
{
boolean success = true;
if (args.length < requiredArguments.length) {
if (args.length < requiredArguments.length)
{
success = false;
} else {
for (int i = 0; i < requiredArguments.length; i++) {
if (requiredArguments[i].parse(args[i]) == null) {
}
else
{
for (int i = 0; i < requiredArguments.length; i++)
{
if (requiredArguments[i].parse(args[i]) == null)
{
success = false;
break;
}
}
}
if (!success) {
String usage = cmd.getUsage().replaceAll("\\{label\\}", parts[0]);
if (!success)
{
cmd.getUsage().replaceAll("\\{label\\}", parts[0]);
C.COMMAND_SYNTAX.send(plr, cmd.getUsage());
return CommandHandlingOutput.WRONG_USAGE;
}
}
try {
boolean a = cmd.onCommand(plr, args);
if (!a) {
String usage = cmd.getUsage();
if (usage != null && !usage.isEmpty()) {
try
{
final boolean a = cmd.onCommand(plr, args);
if (!a)
{
final String usage = cmd.getUsage();
if ((usage != null) && !usage.isEmpty())
{
plr.sendMessage(usage);
}
return CommandHandlingOutput.WRONG_USAGE;
}
} catch(final Throwable t) {
}
catch (final Throwable t)
{
t.printStackTrace();
return CommandHandlingOutput.ERROR;
}
return CommandHandlingOutput.SUCCESS;
}
final public char getInitialCharacter() {
final public char getInitialCharacter()
{
return this.initialCharacter;
}
}

View File

@ -3,10 +3,12 @@ package com.plotsquared.listener;
import com.sk89q.worldedit.extent.AbstractDelegateExtent;
import com.sk89q.worldedit.extent.Extent;
public class ExtentWrapper extends AbstractDelegateExtent {
public class ExtentWrapper extends AbstractDelegateExtent
{
protected ExtentWrapper(Extent extent) {
protected ExtentWrapper(final Extent extent)
{
super(extent);
}
}

View File

@ -6,26 +6,25 @@ import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.extent.AbstractDelegateExtent;
import com.sk89q.worldedit.extent.Extent;
public class HeightLimitExtent extends AbstractDelegateExtent {
public class HeightLimitExtent extends AbstractDelegateExtent
{
private int max;
private int min;
private final int max;
private final int min;
public HeightLimitExtent(int min, int max, Extent child) {
public HeightLimitExtent(final int min, final int max, final Extent child)
{
super(child);
this.min = min;
this.max = max;
}
@Override
public boolean setBlock(Vector location, BaseBlock block) throws WorldEditException {
int y = location.getBlockY();
if (y < min || y > max) {
return false;
}
public boolean setBlock(final Vector location, final BaseBlock block) throws WorldEditException
{
final int y = location.getBlockY();
if ((y < min) || (y > max)) { return false; }
return super.setBlock(location, block);
}
}

View File

@ -15,61 +15,73 @@ import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BaseBiome;
public class NullExtent implements Extent {
public class NullExtent implements Extent
{
@Override
public BaseBiome getBiome(Vector2D arg0) {
public BaseBiome getBiome(final Vector2D arg0)
{
return null;
}
@Override
public BaseBlock getBlock(Vector arg0) {
public BaseBlock getBlock(final Vector arg0)
{
return null;
}
@Override
public BaseBlock getLazyBlock(Vector arg0) {
public BaseBlock getLazyBlock(final Vector arg0)
{
return null;
}
@Override
public Operation commit() {
public Operation commit()
{
return null;
}
@Override
public boolean setBiome(Vector2D arg0, BaseBiome arg1) {
public boolean setBiome(final Vector2D arg0, final BaseBiome arg1)
{
return false;
}
@Override
public boolean setBlock(Vector arg0, BaseBlock arg1) throws WorldEditException {
public boolean setBlock(final Vector arg0, final BaseBlock arg1) throws WorldEditException
{
return false;
}
@Override
public Entity createEntity(Location arg0, BaseEntity arg1) {
public Entity createEntity(final Location arg0, final BaseEntity arg1)
{
return null;
}
@Override
public List<? extends Entity> getEntities() {
public List<? extends Entity> getEntities()
{
return new ArrayList<>();
}
@Override
public List<? extends Entity> getEntities(Region arg0) {
public List<? extends Entity> getEntities(final Region arg0)
{
return new ArrayList<>();
}
@Override
public Vector getMaximumPoint() {
public Vector getMaximumPoint()
{
return new Vector(0, 0, 0);
}
@Override
public Vector getMinimumPoint() {
public Vector getMinimumPoint()
{
return new Vector(0, 0, 0);
}
}

View File

@ -1,251 +1,299 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.listener;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotHandler;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.intellectualcrafters.plot.util.CommentManager;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.PlotGamemode;
import com.intellectualcrafters.plot.util.PlotWeather;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.util.BukkitUtil;
/**
* @author Citymonstret
* @author Empire92
*/
public class PlotListener {
public static boolean plotEntry(final PlotPlayer pp, final Plot plot) {
if (plot.isDenied(pp.getUUID()) && !Permissions.hasPermission(pp, "plots.admin.entry.denied")) {
return false;
}
Plot last = (Plot) pp.getMeta("lastplot");
if (last != null && !last.id.equals(plot.id)) {
plotExit(pp, last);
}
pp.setMeta("lastplot", plot);
EventUtil.manager.callEntry(pp, plot);
if (plot.hasOwner()) {
HashMap<String, Flag> flags = FlagManager.getPlotFlags(plot);
int size = flags.size();
boolean titles = Settings.TITLES;
final String greeting;
if (size != 0) {
Flag titleFlag = flags.get("titles");
if (titleFlag != null) {
titles = (Boolean) titleFlag.getValue();
}
Flag greetingFlag = flags.get("greeting");
if (greetingFlag != null) {
greeting = (String) greetingFlag.getValue();
pp.sendMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX_GREETING.s().replaceAll("%id%", plot.id + "") + greeting));
}
else {
greeting = "";
}
if (greeting != null) {
}
Flag enter = flags.get("notify-enter");
if (enter != null && ((Boolean) enter.getValue())) {
if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass")) {
for (UUID uuid : PlotHandler.getOwners(plot)) {
final PlotPlayer owner = UUIDHandler.getPlayer(uuid);
if (owner != null && !owner.getUUID().equals(pp.getUUID())) {
MainUtil.sendMessage(pp, C.NOTIFY_ENTER.s().replace("%player", pp.getName()).replace("%plot", plot.getId().toString()));
}
}
}
}
final Flag gamemodeFlag = flags.get("gamemode");
if (gamemodeFlag != null) {
if (pp.getGamemode() != gamemodeFlag.getValue()) {
if (!Permissions.hasPermission(pp, "plots.gamemode.bypass")) {
pp.setGamemode((PlotGamemode) gamemodeFlag.getValue());
}
else {
MainUtil.sendMessage(pp, StringMan.replaceAll(C.GAMEMODE_WAS_BYPASSED.s(), "{plot}", plot.id, "{gamemode}", gamemodeFlag.getValue()));
}
}
}
final Flag flyFlag = flags.get("fly");
if (flyFlag != null) {
pp.setFlight((boolean) flyFlag.getValue());
}
final Flag timeFlag = flags.get("time");
if (timeFlag != null) {
try {
final long time = (long) timeFlag.getValue();
pp.setTime(time);
} catch (final Exception e) {
FlagManager.removePlotFlag(plot, "time");
}
}
final Flag weatherFlag = flags.get("weather");
if (weatherFlag != null) {
pp.setWeather((PlotWeather) weatherFlag.getValue());
}
Flag musicFlag = flags.get("music");
if (musicFlag != null) {
final Integer id = (Integer) musicFlag.getValue();
if ((id >= 2256 && id <= 2267) || id == 0) {
Location loc = pp.getLocation();
Location lastLoc = (Location) pp.getMeta("music");
if (lastLoc != null) {
pp.playMusic(lastLoc, 0);
if (id == 0) {
pp.deleteMeta("music");
}
}
if (id != 0) {
try {
pp.setMeta("music", loc);
pp.playMusic(loc, id);
}
catch (Exception e) {}
}
}
}
else {
Location lastLoc = (Location) pp.getMeta("music");
if (lastLoc != null) {
pp.deleteMeta("music");
pp.playMusic(lastLoc, 0);
}
}
CommentManager.sendTitle(pp, plot);
}
else if (titles) {
greeting = "";
}
else {
return true;
}
if (titles) {
if (C.TITLE_ENTERED_PLOT.s().length() != 0 || C.TITLE_ENTERED_PLOT_SUB.s().length() != 0) {
TaskManager.runTaskLaterAsync(new Runnable() {
@Override
public void run() {
Plot lastPlot = (Plot) pp.getMeta("lastplot");
if (lastPlot != null && plot.id.equals(lastPlot.id)) {
Map<String, String> replacements = new HashMap<>();
replacements.put("%x%", lastPlot.id.x + "");
replacements.put("%z%", lastPlot.id.y + "");
replacements.put("%world%", plot.world);
replacements.put("%greeting%", greeting);
replacements.put("%alias", plot.toString());
replacements.put("%s", MainUtil.getName(plot.owner));
String main = StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT.s(), replacements);
String sub = StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT_SUB.s(), replacements);
AbstractTitle.sendTitle(pp, main, sub);
}
}
}, 20);
}
}
return true;
}
return true;
}
public static boolean plotExit(final PlotPlayer pp, final Plot plot) {
pp.deleteMeta("lastplot");
EventUtil.manager.callLeave(pp, plot);
if (plot.hasOwner()) {
PlotWorld pw = PS.get().getPlotWorld(pp.getLocation().getWorld());
if (pw == null) {
return true;
}
if (FlagManager.getPlotFlag(plot, "gamemode") != null) {
if (pp.getGamemode() != pw.GAMEMODE) {
if (!Permissions.hasPermission(pp, "plots.gamemode.bypass")) {
pp.setGamemode(pw.GAMEMODE);
}
else {
MainUtil.sendMessage(pp, StringMan.replaceAll(C.GAMEMODE_WAS_BYPASSED.s(), "{plot}", plot.world, "{gamemode}", pw.GAMEMODE.name().toLowerCase()));
}
}
}
Flag farewell = FlagManager.getPlotFlag(plot, "farewell");
if (farewell != null) {
pp.sendMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX_FAREWELL.s().replaceAll("%id%", plot.id + "") + farewell.getValueString()));
}
Flag leave = FlagManager.getPlotFlag(plot, "notify-leave");
if (leave != null && ((Boolean) leave.getValue())) {
if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass")) {
for (UUID uuid : PlotHandler.getOwners(plot)) {
final PlotPlayer owner = UUIDHandler.getPlayer(uuid);
if (owner != null && !owner.getUUID().equals(pp.getUUID())) {
MainUtil.sendMessage(pp, C.NOTIFY_LEAVE.s().replace("%player", pp.getName()).replace("%plot", plot.getId().toString()));
}
}
}
}
if (FlagManager.getPlotFlag(plot, "fly") != null) {
PlotGamemode gamemode = pp.getGamemode();
if (gamemode == PlotGamemode.SURVIVAL || gamemode == PlotGamemode.ADVENTURE) {
pp.setFlight(false);
}
}
if (FlagManager.getPlotFlag(plot, "time") != null) {
pp.setTime(Long.MAX_VALUE);
}
if (FlagManager.getPlotFlag(plot, "weather") != null) {
pp.setWeather(PlotWeather.RESET);
}
Location lastLoc = (Location) pp.getMeta("music");
if (lastLoc != null) {
pp.deleteMeta("music");
pp.playMusic(lastLoc, 0);
}
}
return true;
}
public boolean getFlagValue(final String value) {
return Arrays.asList("true", "on", "enabled", "yes").contains(value.toLowerCase());
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.listener;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.ChatColor;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotHandler;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.intellectualcrafters.plot.util.CommentManager;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.PlotGamemode;
import com.intellectualcrafters.plot.util.PlotWeather;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
/**
*/
public class PlotListener
{
public static boolean plotEntry(final PlotPlayer pp, final Plot plot)
{
if (plot.isDenied(pp.getUUID()) && !Permissions.hasPermission(pp, "plots.admin.entry.denied")) { return false; }
final Plot last = (Plot) pp.getMeta("lastplot");
if ((last != null) && !last.id.equals(plot.id))
{
plotExit(pp, last);
}
pp.setMeta("lastplot", plot);
EventUtil.manager.callEntry(pp, plot);
if (plot.hasOwner())
{
final HashMap<String, Flag> flags = FlagManager.getPlotFlags(plot);
final int size = flags.size();
boolean titles = Settings.TITLES;
final String greeting;
if (size != 0)
{
final Flag titleFlag = flags.get("titles");
if (titleFlag != null)
{
titles = (Boolean) titleFlag.getValue();
}
final Flag greetingFlag = flags.get("greeting");
if (greetingFlag != null)
{
greeting = (String) greetingFlag.getValue();
pp.sendMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX_GREETING.s().replaceAll("%id%", plot.id + "") + greeting));
}
else
{
greeting = "";
}
if (greeting != null)
{
}
final Flag enter = flags.get("notify-enter");
if ((enter != null) && ((Boolean) enter.getValue()))
{
if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass"))
{
for (final UUID uuid : PlotHandler.getOwners(plot))
{
final PlotPlayer owner = UUIDHandler.getPlayer(uuid);
if ((owner != null) && !owner.getUUID().equals(pp.getUUID()))
{
MainUtil.sendMessage(pp, C.NOTIFY_ENTER.s().replace("%player", pp.getName()).replace("%plot", plot.getId().toString()));
}
}
}
}
final Flag gamemodeFlag = flags.get("gamemode");
if (gamemodeFlag != null)
{
if (pp.getGamemode() != gamemodeFlag.getValue())
{
if (!Permissions.hasPermission(pp, "plots.gamemode.bypass"))
{
pp.setGamemode((PlotGamemode) gamemodeFlag.getValue());
}
else
{
MainUtil.sendMessage(pp, StringMan.replaceAll(C.GAMEMODE_WAS_BYPASSED.s(), "{plot}", plot.id, "{gamemode}", gamemodeFlag.getValue()));
}
}
}
final Flag flyFlag = flags.get("fly");
if (flyFlag != null)
{
pp.setFlight((boolean) flyFlag.getValue());
}
final Flag timeFlag = flags.get("time");
if (timeFlag != null)
{
try
{
final long time = (long) timeFlag.getValue();
pp.setTime(time);
}
catch (final Exception e)
{
FlagManager.removePlotFlag(plot, "time");
}
}
final Flag weatherFlag = flags.get("weather");
if (weatherFlag != null)
{
pp.setWeather((PlotWeather) weatherFlag.getValue());
}
final Flag musicFlag = flags.get("music");
if (musicFlag != null)
{
final Integer id = (Integer) musicFlag.getValue();
if (((id >= 2256) && (id <= 2267)) || (id == 0))
{
final Location loc = pp.getLocation();
final Location lastLoc = (Location) pp.getMeta("music");
if (lastLoc != null)
{
pp.playMusic(lastLoc, 0);
if (id == 0)
{
pp.deleteMeta("music");
}
}
if (id != 0)
{
try
{
pp.setMeta("music", loc);
pp.playMusic(loc, id);
}
catch (final Exception e)
{}
}
}
}
else
{
final Location lastLoc = (Location) pp.getMeta("music");
if (lastLoc != null)
{
pp.deleteMeta("music");
pp.playMusic(lastLoc, 0);
}
}
CommentManager.sendTitle(pp, plot);
}
else if (titles)
{
greeting = "";
}
else
{
return true;
}
if (titles)
{
if ((C.TITLE_ENTERED_PLOT.s().length() != 0) || (C.TITLE_ENTERED_PLOT_SUB.s().length() != 0))
{
TaskManager.runTaskLaterAsync(new Runnable()
{
@Override
public void run()
{
final Plot lastPlot = (Plot) pp.getMeta("lastplot");
if ((lastPlot != null) && plot.id.equals(lastPlot.id))
{
final Map<String, String> replacements = new HashMap<>();
replacements.put("%x%", lastPlot.id.x + "");
replacements.put("%z%", lastPlot.id.y + "");
replacements.put("%world%", plot.world);
replacements.put("%greeting%", greeting);
replacements.put("%alias", plot.toString());
replacements.put("%s", MainUtil.getName(plot.owner));
final String main = StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT.s(), replacements);
final String sub = StringMan.replaceFromMap(C.TITLE_ENTERED_PLOT_SUB.s(), replacements);
AbstractTitle.sendTitle(pp, main, sub);
}
}
}, 20);
}
}
return true;
}
return true;
}
public static boolean plotExit(final PlotPlayer pp, final Plot plot)
{
pp.deleteMeta("lastplot");
EventUtil.manager.callLeave(pp, plot);
if (plot.hasOwner())
{
final PlotWorld pw = PS.get().getPlotWorld(pp.getLocation().getWorld());
if (pw == null) { return true; }
if (FlagManager.getPlotFlag(plot, "gamemode") != null)
{
if (pp.getGamemode() != pw.GAMEMODE)
{
if (!Permissions.hasPermission(pp, "plots.gamemode.bypass"))
{
pp.setGamemode(pw.GAMEMODE);
}
else
{
MainUtil.sendMessage(pp, StringMan.replaceAll(C.GAMEMODE_WAS_BYPASSED.s(), "{plot}", plot.world, "{gamemode}", pw.GAMEMODE.name().toLowerCase()));
}
}
}
final Flag farewell = FlagManager.getPlotFlag(plot, "farewell");
if (farewell != null)
{
pp.sendMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX_FAREWELL.s().replaceAll("%id%", plot.id + "") + farewell.getValueString()));
}
final Flag leave = FlagManager.getPlotFlag(plot, "notify-leave");
if ((leave != null) && ((Boolean) leave.getValue()))
{
if (!Permissions.hasPermission(pp, "plots.flag.notify-enter.bypass"))
{
for (final UUID uuid : PlotHandler.getOwners(plot))
{
final PlotPlayer owner = UUIDHandler.getPlayer(uuid);
if ((owner != null) && !owner.getUUID().equals(pp.getUUID()))
{
MainUtil.sendMessage(pp, C.NOTIFY_LEAVE.s().replace("%player", pp.getName()).replace("%plot", plot.getId().toString()));
}
}
}
}
if (FlagManager.getPlotFlag(plot, "fly") != null)
{
final PlotGamemode gamemode = pp.getGamemode();
if ((gamemode == PlotGamemode.SURVIVAL) || (gamemode == PlotGamemode.ADVENTURE))
{
pp.setFlight(false);
}
}
if (FlagManager.getPlotFlag(plot, "time") != null)
{
pp.setTime(Long.MAX_VALUE);
}
if (FlagManager.getPlotFlag(plot, "weather") != null)
{
pp.setWeather(PlotWeather.RESET);
}
final Location lastLoc = (Location) pp.getMeta("music");
if (lastLoc != null)
{
pp.deleteMeta("music");
pp.playMusic(lastLoc, 0);
}
}
return true;
}
public boolean getFlagValue(final String value)
{
return Arrays.asList("true", "on", "enabled", "yes").contains(value.toLowerCase());

View File

@ -19,33 +19,38 @@ import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BaseBiome;
public class ProcessedWEExtent extends AbstractDelegateExtent {
public class ProcessedWEExtent extends AbstractDelegateExtent
{
private final HashSet<RegionWrapper> mask;
int BScount = 0;
int Ecount = 0;
boolean BSblocked = false;
boolean Eblocked = false;
private String world;
private int max;
private final String world;
private final int max;
private int count;
private Extent parent;
public ProcessedWEExtent(String world, HashSet<RegionWrapper> mask, int max, Extent child, Extent parent) {
public ProcessedWEExtent(final String world, final HashSet<RegionWrapper> mask, int max, final Extent child, final Extent parent)
{
super(child);
this.mask = mask;
this.world = world;
if (max == -1) {
if (max == -1)
{
max = Integer.MAX_VALUE;
}
this.max = max;
this.count = 0;
count = 0;
this.parent = parent;
}
@Override
public boolean setBlock(Vector location, BaseBlock block) throws WorldEditException {
int id = block.getType();
switch (id) {
public boolean setBlock(final Vector location, final BaseBlock block) throws WorldEditException
{
final int id = block.getType();
switch (id)
{
case 54:
case 130:
case 142:
@ -80,23 +85,29 @@ public class ProcessedWEExtent extends AbstractDelegateExtent {
case 29:
case 33:
case 151:
case 178: {
if (BSblocked) {
return false;
}
case 178:
{
if (BSblocked) { return false; }
BScount++;
if (BScount > Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES) {
if (BScount > Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES)
{
BSblocked = true;
PS.debug("&cPlotSquared detected unsafe WorldEdit: " + (location.getBlockX()) + "," + (location.getBlockZ()));
}
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
if (count++ > max) {
if (parent != null) {
try {
Field field = AbstractDelegateExtent.class.getDeclaredField("extent");
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ()))
{
if (count++ > max)
{
if (parent != null)
{
try
{
final Field field = AbstractDelegateExtent.class.getDeclaredField("extent");
field.setAccessible(true);
field.set(parent, new NullExtent());
} catch (Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
}
parent = null;
@ -107,25 +118,33 @@ public class ProcessedWEExtent extends AbstractDelegateExtent {
}
break;
}
default: {
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
if (count++ > max) {
if (parent != null) {
try {
Field field = AbstractDelegateExtent.class.getDeclaredField("extent");
default:
{
final int x = location.getBlockX();
final int y = location.getBlockY();
final int z = location.getBlockZ();
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ()))
{
if (count++ > max)
{
if (parent != null)
{
try
{
final Field field = AbstractDelegateExtent.class.getDeclaredField("extent");
field.setAccessible(true);
field.set(parent, new NullExtent());
} catch (Exception e) {
}
catch (final Exception e)
{
e.printStackTrace();
}
parent = null;
}
return false;
}
switch(id) {
switch (id)
{
case 0:
case 2:
case 4:
@ -210,56 +229,59 @@ public class ProcessedWEExtent extends AbstractDelegateExtent {
case 189:
case 190:
case 191:
case 192: {
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) {
case 192:
{
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT)
{
SetBlockQueue.setBlock(world, x, y, z, id);
}
else {
else
{
super.setBlock(location, block);
}
break;
}
default: {
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) {
default:
{
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT)
{
SetBlockQueue.setBlock(world, x, y, z, new PlotBlock((short) id, (byte) block.getData()));
}
else {
else
{
super.setBlock(location, block);
}
break;
}
}
return true;
// BlockManager.manager.functionSetBlock(world, x, y, z, id, data);
// return super.setBlock(location, block);
// BlockManager.manager.functionSetBlock(world, x, y, z, id, data);
// return super.setBlock(location, block);
}
}
}
return false;
}
@Override
public Entity createEntity(Location location, BaseEntity entity) {
if (Eblocked) {
return null;
}
public Entity createEntity(final Location location, final BaseEntity entity)
{
if (Eblocked) { return null; }
Ecount++;
if (Ecount > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
if (Ecount > Settings.CHUNK_PROCESSOR_MAX_ENTITIES)
{
Eblocked = true;
PS.debug("&cPlotSquared detected unsafe WorldEdit: " + (location.getBlockX()) + "," + (location.getBlockZ()));
}
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
return super.createEntity(location, entity);
}
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) { return super.createEntity(location, entity); }
return null;
}
@Override
public boolean setBiome(Vector2D position, BaseBiome biome) {
if (WEManager.maskContains(mask, position.getBlockX(), position.getBlockZ())) {
return super.setBiome(position, biome);
}
public boolean setBiome(final Vector2D position, final BaseBiome biome)
{
if (WEManager.maskContains(mask, position.getBlockX(), position.getBlockZ())) { return super.setBiome(position, biome); }
return false;
}
}
}

View File

@ -14,35 +14,34 @@ import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BaseBiome;
public class WEExtent extends AbstractDelegateExtent {
public class WEExtent extends AbstractDelegateExtent
{
private final HashSet<RegionWrapper> mask;
public WEExtent(HashSet<RegionWrapper> mask, Extent extent) {
public WEExtent(final HashSet<RegionWrapper> mask, final Extent extent)
{
super(extent);
this.mask = mask;
}
@Override
public boolean setBlock(Vector location, BaseBlock block) throws WorldEditException {
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
return super.setBlock(location, block);
}
public boolean setBlock(final Vector location, final BaseBlock block) throws WorldEditException
{
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) { return super.setBlock(location, block); }
return false;
}
@Override
public Entity createEntity(Location location, BaseEntity entity) {
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) {
return super.createEntity(location, entity);
}
public Entity createEntity(final Location location, final BaseEntity entity)
{
if (WEManager.maskContains(mask, location.getBlockX(), location.getBlockY(), location.getBlockZ())) { return super.createEntity(location, entity); }
return null;
}
@Override
public boolean setBiome(Vector2D position, BaseBiome biome) {
if (WEManager.maskContains(mask, position.getBlockX(), position.getBlockZ())) {
return super.setBiome(position, biome);
}
public boolean setBiome(final Vector2D position, final BaseBiome biome)
{
if (WEManager.maskContains(mask, position.getBlockX(), position.getBlockZ())) { return super.setBiome(position, biome); }
return false;
}
}
}

View File

@ -12,58 +12,65 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
public class WEManager {
// public static HashSet<String> bypass = new HashSet<>();
public static boolean maskContains(HashSet<RegionWrapper> mask, int x, int y, int z) {
for (RegionWrapper region : mask) {
if (region.isIn(x, y, z)) {
return true;
}
public class WEManager
{
// public static HashSet<String> bypass = new HashSet<>();
public static boolean maskContains(final HashSet<RegionWrapper> mask, final int x, final int y, final int z)
{
for (final RegionWrapper region : mask)
{
if (region.isIn(x, y, z)) { return true; }
}
return false;
}
public static boolean maskContains(HashSet<RegionWrapper> mask, int x, int z) {
for (RegionWrapper region : mask) {
if (region.isIn(x, z)) {
return true;
}
public static boolean maskContains(final HashSet<RegionWrapper> mask, final int x, final int z)
{
for (final RegionWrapper region : mask)
{
if (region.isIn(x, z)) { return true; }
}
return false;
}
public static HashSet<RegionWrapper> getMask(PlotPlayer player) {
HashSet<RegionWrapper> regions = new HashSet<>();
UUID uuid = player.getUUID();
Location location = player.getLocation();
String world = location.getWorld();
if (!PS.get().isPlotWorld(world)) {
public static HashSet<RegionWrapper> getMask(final PlotPlayer player)
{
final HashSet<RegionWrapper> regions = new HashSet<>();
final UUID uuid = player.getUUID();
final Location location = player.getLocation();
final String world = location.getWorld();
if (!PS.get().isPlotWorld(world))
{
regions.add(new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE));
return regions;
}
for (Plot plot : PS.get().getPlotsInWorld(player.getLocation().getWorld())) {
if (!plot.isBasePlot() || (Settings.DONE_RESTRICTS_BUILDING && FlagManager.getPlotFlag(plot, "done") != null)) {
for (final Plot plot : PS.get().getPlotsInWorld(player.getLocation().getWorld()))
{
if (!plot.isBasePlot() || (Settings.DONE_RESTRICTS_BUILDING && (FlagManager.getPlotFlag(plot, "done") != null)))
{
continue;
}
if (Settings.WE_ALLOW_HELPER ? plot.isAdded(uuid) : (plot.isOwner(uuid) || plot.getTrusted().contains(uuid))) {
Location pos1 = MainUtil.getPlotBottomLoc(plot.world, plot.id).add(1, 0, 1);
Location pos2 = MainUtil.getPlotTopLoc(plot.world, plot.id);
if (Settings.WE_ALLOW_HELPER ? plot.isAdded(uuid) : (plot.isOwner(uuid) || plot.getTrusted().contains(uuid)))
{
final Location pos1 = MainUtil.getPlotBottomLoc(plot.world, plot.id).add(1, 0, 1);
final Location pos2 = MainUtil.getPlotTopLoc(plot.world, plot.id);
regions.add(new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getY(), pos2.getY(), pos1.getZ(), pos2.getZ()));
}
}
return regions;
}
public static boolean intersects(RegionWrapper region1, RegionWrapper region2) {
public static boolean intersects(final RegionWrapper region1, final RegionWrapper region2)
{
return (region1.minX <= region2.maxX) && (region1.maxX >= region2.minX) && (region1.minZ <= region2.maxZ) && (region1.maxZ >= region2.minZ);
}
public static boolean regionContains(RegionWrapper selection, HashSet<RegionWrapper> mask) {
for (RegionWrapper region : mask) {
if (intersects(region, selection)) {
return true;
}
public static boolean regionContains(final RegionWrapper selection, final HashSet<RegionWrapper> mask)
{
for (final RegionWrapper region : mask)
{
if (intersects(region, selection)) { return true; }
}
return false;
}

View File

@ -27,94 +27,118 @@ import com.sk89q.worldedit.util.eventbus.EventHandler.Priority;
import com.sk89q.worldedit.util.eventbus.Subscribe;
import com.sk89q.worldedit.world.World;
public class WESubscriber {
@Subscribe(priority=Priority.VERY_EARLY)
public void onEditSession(EditSessionEvent event) {
WorldEdit worldedit = PS.get().worldedit;
if (worldedit == null) {
public class WESubscriber
{
@Subscribe(priority = Priority.VERY_EARLY)
public void onEditSession(final EditSessionEvent event)
{
final WorldEdit worldedit = PS.get().worldedit;
if (worldedit == null)
{
worldedit.getEventBus().unregister(this);
return;
}
World worldObj = event.getWorld();
String world = worldObj.getName();
Actor actor = event.getActor();
if (actor != null && actor.isPlayer()) {
String name = actor.getName();
PlotPlayer pp = PlotPlayer.wrap(name);
if (pp != null && pp.getAttribute("worldedit")) {
return;
}
HashSet<RegionWrapper> mask = WEManager.getMask(pp);
PlotWorld plotworld = PS.get().getPlotWorld(world);
if (mask.size() == 0) {
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
final World worldObj = event.getWorld();
final String world = worldObj.getName();
final Actor actor = event.getActor();
if ((actor != null) && actor.isPlayer())
{
final String name = actor.getName();
final PlotPlayer pp = PlotPlayer.wrap(name);
if ((pp != null) && pp.getAttribute("worldedit")) { return; }
final HashSet<RegionWrapper> mask = WEManager.getMask(pp);
final PlotWorld plotworld = PS.get().getPlotWorld(world);
if (mask.size() == 0)
{
if (Permissions.hasPermission(pp, "plots.worldedit.bypass"))
{
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
if (plotworld != null) {
if (plotworld != null)
{
event.setExtent(new NullExtent());
}
return;
}
if (Settings.CHUNK_PROCESSOR) {
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) {
try {
LocalSession session = worldedit.getSession(name);
if (Settings.CHUNK_PROCESSOR)
{
if (Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT)
{
try
{
final LocalSession session = worldedit.getSession(name);
boolean hasMask = session.getMask() != null;
Player objPlayer = (Player) actor;
int item = objPlayer.getItemInHand();
if (!hasMask) {
try {
Tool tool = session.getTool(item);
if (tool != null && tool instanceof BrushTool) {
final Player objPlayer = (Player) actor;
final int item = objPlayer.getItemInHand();
if (!hasMask)
{
try
{
final Tool tool = session.getTool(item);
if ((tool != null) && (tool instanceof BrushTool))
{
hasMask = ((BrushTool) tool).getMask() != null;
}
}
catch (Exception e) {}
catch (final Exception e)
{}
}
AbstractDelegateExtent extent = (AbstractDelegateExtent) event.getExtent();
ChangeSetExtent history = null;
MultiStageReorder reorder = null;
MaskingExtent maskextent = null;
boolean fast = session.hasFastMode();
while (extent.getExtent() != null && extent.getExtent() instanceof AbstractDelegateExtent) {
AbstractDelegateExtent tmp = (AbstractDelegateExtent) extent.getExtent();
if (tmp.getExtent() != null && tmp.getExtent() instanceof AbstractDelegateExtent) {
if (tmp instanceof ChangeSetExtent) {
final boolean fast = session.hasFastMode();
while ((extent.getExtent() != null) && (extent.getExtent() instanceof AbstractDelegateExtent))
{
final AbstractDelegateExtent tmp = (AbstractDelegateExtent) extent.getExtent();
if ((tmp.getExtent() != null) && (tmp.getExtent() instanceof AbstractDelegateExtent))
{
if (tmp instanceof ChangeSetExtent)
{
history = (ChangeSetExtent) tmp;
}
if (tmp instanceof MultiStageReorder) {
if (tmp instanceof MultiStageReorder)
{
reorder = (MultiStageReorder) tmp;
}
if (hasMask && tmp instanceof MaskingExtent) {
if (hasMask && (tmp instanceof MaskingExtent))
{
maskextent = (MaskingExtent) tmp;
}
extent = tmp;
}
else {
else
{
break;
}
}
int max = event.getMaxBlocks();
Field field = AbstractDelegateExtent.class.getDeclaredField("extent");
final int max = event.getMaxBlocks();
final Field field = AbstractDelegateExtent.class.getDeclaredField("extent");
field.setAccessible(true);
if (history == null) {
ExtentWrapper wrapper = new ExtentWrapper(event.getExtent());
if (history == null)
{
final ExtentWrapper wrapper = new ExtentWrapper(event.getExtent());
event.setExtent(wrapper);
field.set(extent, new ProcessedWEExtent(world, mask, max, new FastModeExtent(worldObj, true), wrapper));
}
else {
if (fast) {
else
{
if (fast)
{
event.setExtent(new ExtentWrapper(extent));
}
else {
else
{
ExtentWrapper wrapper;
if (maskextent != null) {
if (maskextent != null)
{
wrapper = new ExtentWrapper(maskextent);
field.set(maskextent, history);
event.setExtent(wrapper);
}
else {
else
{
wrapper = new ExtentWrapper(history);
event.setExtent(wrapper);
}
@ -124,15 +148,18 @@ public class WESubscriber {
}
return;
}
catch (Exception e) {
catch (final Exception e)
{
e.printStackTrace();
}
}
if (PS.get().isPlotWorld(world)) {
if (PS.get().isPlotWorld(world))
{
event.setExtent(new ProcessedWEExtent(world, mask, event.getMaxBlocks(), event.getExtent(), event.getExtent()));
}
}
else if (plotworld != null) {
else if (plotworld != null)
{
event.setExtent(new WEExtent(mask, event.getExtent()));
}
}

View File

@ -21,34 +21,38 @@ import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
public class StateWrapper {
public class StateWrapper
{
public BlockState state = null;
public CompoundTag tag = null;
public StateWrapper(BlockState state) {
public StateWrapper(final BlockState state)
{
this.state = state;
}
public StateWrapper(CompoundTag tag) {
public StateWrapper(final CompoundTag tag)
{
this.tag = tag;
}
public boolean restoreTag(short x, short y, short z, Schematic schematic) {
if (this.tag == null) {
return false;
}
List<Tag> itemsTag = this.tag.getListTag("Items").getValue();
int length = itemsTag.size();
short[] ids = new short[length];
byte[] datas = new byte[length];
byte[] amounts = new byte[length];
for (int i = 0; i < length; i++) {
Tag itemTag = itemsTag.get(i);
CompoundTag itemComp = (CompoundTag) itemTag;
public boolean restoreTag(final short x, final short y, final short z, final Schematic schematic)
{
if (tag == null) { return false; }
final List<Tag> itemsTag = tag.getListTag("Items").getValue();
final int length = itemsTag.size();
final short[] ids = new short[length];
final byte[] datas = new byte[length];
final byte[] amounts = new byte[length];
for (int i = 0; i < length; i++)
{
final Tag itemTag = itemsTag.get(i);
final CompoundTag itemComp = (CompoundTag) itemTag;
short id = itemComp.getShort("id");
String idStr = itemComp.getString("id");
if (idStr != null && !MathMan.isInteger(idStr)) {
if ((idStr != null) && !MathMan.isInteger(idStr))
{
idStr = idStr.split(":")[1].toLowerCase();
id = (short) ItemType.getId(idStr);
}
@ -56,64 +60,73 @@ public class StateWrapper {
datas[i] = (byte) itemComp.getShort("Damage");
amounts[i] = itemComp.getByte("Count");
}
if (length != 0) {
if (length != 0)
{
schematic.addItem(new PlotItem(x, y, z, ids, datas, amounts));
}
return true;
}
public CompoundTag getTag() {
if (this.tag != null) {
return this.tag;
}
if (state instanceof InventoryHolder) {
InventoryHolder inv = (InventoryHolder) state;
ItemStack[] contents = inv.getInventory().getContents();
Map<String, Tag> values = new HashMap<String, Tag>();
public CompoundTag getTag()
{
if (tag != null) { return tag; }
if (state instanceof InventoryHolder)
{
final InventoryHolder inv = (InventoryHolder) state;
final ItemStack[] contents = inv.getInventory().getContents();
final Map<String, Tag> values = new HashMap<String, Tag>();
values.put("Items", new ListTag("Items", CompoundTag.class, serializeInventory(contents)));
return new CompoundTag(values);
}
return null;
}
public String getId() {
public String getId()
{
return "Chest";
}
public List<CompoundTag> serializeInventory(ItemStack[] items) {
List<CompoundTag> tags = new ArrayList<CompoundTag>();
for (int i = 0; i < items.length; ++i) {
if (items[i] != null) {
Map<String, Tag> tagData = serializeItem(items[i]);
public List<CompoundTag> serializeInventory(final ItemStack[] items)
{
final List<CompoundTag> tags = new ArrayList<CompoundTag>();
for (int i = 0; i < items.length; ++i)
{
if (items[i] != null)
{
final Map<String, Tag> tagData = serializeItem(items[i]);
tagData.put("Slot", new ByteTag("Slot", (byte) i));
tags.add(new CompoundTag(tagData));
}
}
return tags;
}
public Map<String, Tag> serializeItem(org.spongepowered.api.item.inventory.ItemStack item) {
Map<String, Tag> data = new HashMap<String, Tag>();
public Map<String, Tag> serializeItem(final org.spongepowered.api.item.inventory.ItemStack item)
{
final Map<String, Tag> data = new HashMap<String, Tag>();
// FIXME serialize sponge item
return data;
}
public Map<String, Tag> serializeItem(ItemStack item) {
Map<String, Tag> data = new HashMap<String, Tag>();
public Map<String, Tag> serializeItem(final ItemStack item)
{
final Map<String, Tag> data = new HashMap<String, Tag>();
data.put("id", new ShortTag("id", (short) item.getTypeId()));
data.put("Damage", new ShortTag("Damage", item.getDurability()));
data.put("Count", new ByteTag("Count", (byte) item.getAmount()));
if (!item.getEnchantments().isEmpty()) {
List<CompoundTag> enchantmentList = new ArrayList<CompoundTag>();
for(Entry<Enchantment, Integer> entry : item.getEnchantments().entrySet()) {
Map<String, Tag> enchantment = new HashMap<String, Tag>();
if (!item.getEnchantments().isEmpty())
{
final List<CompoundTag> enchantmentList = new ArrayList<CompoundTag>();
for (final Entry<Enchantment, Integer> entry : item.getEnchantments().entrySet())
{
final Map<String, Tag> enchantment = new HashMap<String, Tag>();
enchantment.put("id", new ShortTag("id", (short) entry.getKey().getId()));
enchantment.put("lvl", new ShortTag("lvl", entry.getValue().shortValue()));
enchantmentList.add(new CompoundTag(enchantment));
}
Map<String, Tag> auxData = new HashMap<String, Tag>();
final Map<String, Tag> auxData = new HashMap<String, Tag>();
auxData.put("ench", new ListTag("ench", CompoundTag.class, enchantmentList));
data.put("tag", new CompoundTag("tag", auxData));
}

View File

@ -12,35 +12,45 @@ import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.plotsquared.sponge.util.SpongeUtil;
public class SpongeHybridUtils extends HybridUtils {
public class SpongeHybridUtils extends HybridUtils
{
@Override
public void analyzePlot(Plot plot, RunnableVal<PlotAnalysis> whenDone) {
public void analyzePlot(final Plot plot, final RunnableVal<PlotAnalysis> whenDone)
{
// TODO Auto-generated method stub
PS.debug("analyzePlot is not implemented");
if (whenDone != null) {
if (whenDone != null)
{
whenDone.run();
}
}
@Override
public int checkModified(String worldname, int x1, int x2, int y1, int y2, int z1, int z2, PlotBlock[] blocks) {
public int checkModified(final String worldname, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, final PlotBlock[] blocks)
{
PS.debug("checkModified is not implemented");
final World world = SpongeUtil.getWorld(worldname);
int count = 0;
for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) {
for (int z = z1; z <= z2; z++) {
BlockState state = world.getBlock(x, y, z);
PlotBlock block = SpongeMain.THIS.getPlotBlock(state);
for (int y = y1; y <= y2; y++)
{
for (int x = x1; x <= x2; x++)
{
for (int z = z1; z <= z2; z++)
{
final BlockState state = world.getBlock(x, y, z);
final PlotBlock block = SpongeMain.THIS.getPlotBlock(state);
boolean same = false;
for (final PlotBlock p : blocks) {
if (block.id == p.id) {
for (final PlotBlock p : blocks)
{
if (block.id == p.id)
{
same = true;
break;
}
}
if (!same) {
if (!same)
{
count++;
}
}
@ -48,17 +58,23 @@ public class SpongeHybridUtils extends HybridUtils {
}
return count;
}
@Override
public int get_ey(String worldname, int sx, int ex, int sz, int ez, int sy) {
public int get_ey(final String worldname, final int sx, final int ex, final int sz, final int ez, final int sy)
{
final World world = SpongeUtil.getWorld(worldname);
int ey = sy;
for (int x = sx; x <= ex; x++) {
for (int z = sz; z <= ez; z++) {
for (int y = sy; y < 256; y++) {
if (y > ey) {
BlockState state = world.getBlock(x, y, z);
if (state != null && state.getType() != BlockTypes.AIR) {
for (int x = sx; x <= ex; x++)
{
for (int z = sz; z <= ez; z++)
{
for (int y = sy; y < 256; y++)
{
if (y > ey)
{
final BlockState state = world.getBlock(x, y, z);
if ((state != null) && (state.getType() != BlockTypes.AIR))
{
ey = y;
}
}
@ -67,5 +83,5 @@ public class SpongeHybridUtils extends HybridUtils {
}
return ey;
}
}

Some files were not shown because too many files have changed in this diff Show More