From 3a11ffc77a75688d8e22faee43c558519154a0c1 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Sat, 11 Jul 2020 19:03:55 +0100 Subject: [PATCH 01/49] Clean up bukkit listeners by splitting them up --- .../com/plotsquared/bukkit/BukkitMain.java | 13 +- .../bukkit/listener/BlockEventListener.java | 1050 ++++++ .../bukkit/listener/EntityEventListener.java | 317 ++ .../bukkit/listener/EntitySpawnListener.java | 3 +- .../bukkit/listener/PlayerEventListener.java | 1518 ++++++++ .../bukkit/listener/PlayerEvents.java | 3221 ----------------- .../listener/ProjectileEventListener.java | 156 + .../bukkit/util/BukkitEntityUtil.java | 363 ++ .../java/com/plotsquared/core/IPlotMain.java | 2 +- .../com/plotsquared/core/util/EntityUtil.java | 2 +- 10 files changed, 3417 insertions(+), 3228 deletions(-) create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java delete mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/listener/ProjectileEventListener.java create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java index 39b2a3c9d..b40b6a904 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java @@ -27,10 +27,13 @@ package com.plotsquared.bukkit; import com.plotsquared.bukkit.generator.BukkitHybridUtils; import com.plotsquared.bukkit.generator.BukkitPlotGenerator; +import com.plotsquared.bukkit.listener.BlockEventListener; import com.plotsquared.bukkit.listener.ChunkListener; +import com.plotsquared.bukkit.listener.EntityEventListener; import com.plotsquared.bukkit.listener.EntitySpawnListener; import com.plotsquared.bukkit.listener.PaperListener; -import com.plotsquared.bukkit.listener.PlayerEvents; +import com.plotsquared.bukkit.listener.PlayerEventListener; +import com.plotsquared.bukkit.listener.ProjectileEventListener; import com.plotsquared.bukkit.listener.SingleWorldListener; import com.plotsquared.bukkit.listener.WorldEvents; import com.plotsquared.bukkit.managers.BukkitWorldManager; @@ -891,9 +894,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain< return (ChunkGenerator) result.specify(worldName); } - @Override public void registerPlayerEvents() { - final PlayerEvents main = new PlayerEvents(); - getServer().getPluginManager().registerEvents(main, this); + @Override public void registerEvents() { + getServer().getPluginManager().registerEvents(new PlayerEventListener(), this); + getServer().getPluginManager().registerEvents(new BlockEventListener(), this); + getServer().getPluginManager().registerEvents(new EntityEventListener(), this); + getServer().getPluginManager().registerEvents(new ProjectileEventListener(), this); getServer().getPluginManager().registerEvents(new EntitySpawnListener(), this); if (PaperLib.isPaper() && Settings.Paper_Components.PAPER_LISTENERS) { getServer().getPluginManager().registerEvents(new PaperListener(), this); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java new file mode 100644 index 000000000..220e8d073 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java @@ -0,0 +1,1050 @@ +package com.plotsquared.bukkit.listener; + +import com.plotsquared.bukkit.player.BukkitPlayer; +import com.plotsquared.bukkit.util.BukkitUtil; +import com.plotsquared.core.PlotSquared; +import com.plotsquared.core.configuration.Captions; +import com.plotsquared.core.configuration.Settings; +import com.plotsquared.core.database.DBFunc; +import com.plotsquared.core.location.Location; +import com.plotsquared.core.player.PlotPlayer; +import com.plotsquared.core.plot.Plot; +import com.plotsquared.core.plot.PlotArea; +import com.plotsquared.core.plot.flag.implementations.BlockBurnFlag; +import com.plotsquared.core.plot.flag.implementations.BlockIgnitionFlag; +import com.plotsquared.core.plot.flag.implementations.BreakFlag; +import com.plotsquared.core.plot.flag.implementations.CoralDryFlag; +import com.plotsquared.core.plot.flag.implementations.DisablePhysicsFlag; +import com.plotsquared.core.plot.flag.implementations.DoneFlag; +import com.plotsquared.core.plot.flag.implementations.ExplosionFlag; +import com.plotsquared.core.plot.flag.implementations.GrassGrowFlag; +import com.plotsquared.core.plot.flag.implementations.IceFormFlag; +import com.plotsquared.core.plot.flag.implementations.IceMeltFlag; +import com.plotsquared.core.plot.flag.implementations.InstabreakFlag; +import com.plotsquared.core.plot.flag.implementations.KelpGrowFlag; +import com.plotsquared.core.plot.flag.implementations.LiquidFlowFlag; +import com.plotsquared.core.plot.flag.implementations.MycelGrowFlag; +import com.plotsquared.core.plot.flag.implementations.PlaceFlag; +import com.plotsquared.core.plot.flag.implementations.RedstoneFlag; +import com.plotsquared.core.plot.flag.implementations.SnowFormFlag; +import com.plotsquared.core.plot.flag.implementations.SnowMeltFlag; +import com.plotsquared.core.plot.flag.implementations.SoilDryFlag; +import com.plotsquared.core.plot.flag.implementations.VineGrowFlag; +import com.plotsquared.core.plot.flag.types.BlockTypeWrapper; +import com.plotsquared.core.util.MainUtil; +import com.plotsquared.core.util.Permissions; +import com.plotsquared.core.util.task.TaskManager; +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.block.BlockType; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.BlockData; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Fireball; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockBurnEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockDispenseEvent; +import org.bukkit.event.block.BlockExplodeEvent; +import org.bukkit.event.block.BlockFadeEvent; +import org.bukkit.event.block.BlockFormEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockGrowEvent; +import org.bukkit.event.block.BlockIgniteEvent; +import org.bukkit.event.block.BlockPhysicsEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.block.BlockRedstoneEvent; +import org.bukkit.event.block.BlockSpreadEvent; +import org.bukkit.event.block.EntityBlockFormEvent; +import org.bukkit.event.world.StructureGrowEvent; +import org.bukkit.material.Directional; +import org.bukkit.projectiles.BlockProjectileSource; +import org.bukkit.util.Vector; + +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +@SuppressWarnings("unused") +public class BlockEventListener implements Listener { + + public static void sendBlockChange(final org.bukkit.Location bloc, final BlockData data) { + TaskManager.runTaskLater(() -> { + String world = bloc.getWorld().getName(); + int x = bloc.getBlockX(); + int z = bloc.getBlockZ(); + int distance = Bukkit.getViewDistance() * 16; + + for (final PlotPlayer player : PlotSquared.imp().getPlayerManager().getPlayers()) { + Location location = player.getLocation(); + if (location.getWorld().equals(world)) { + if (16 * Math.abs(location.getX() - x) / 16 > distance + || 16 * Math.abs(location.getZ() - z) / 16 > distance) { + continue; + } + ((BukkitPlayer) player).player.sendBlockChange(bloc, data); + } + } + }, 3); + } + + @EventHandler public void onRedstoneEvent(BlockRedstoneEvent event) { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = location.getOwnedPlot(); + if (plot == null) { + if (area.isRoadFlags() && area.getRoadFlag(RedstoneFlag.class)) { + event.setNewCurrent(0); + } + return; + } + if (!plot.getFlag(RedstoneFlag.class)) { + event.setNewCurrent(0); + plot.debug("Redstone event was cancelled because redstone = false"); + return; + } + if (Settings.Redstone.DISABLE_OFFLINE) { + boolean disable = false; + if (!plot.getOwner().equals(DBFunc.SERVER)) { + if (plot.isMerged()) { + disable = true; + for (UUID owner : plot.getOwners()) { + if (PlotSquared.imp().getPlayerManager().getPlayerIfExists(owner) != null) { + disable = false; + break; + } + } + } else { + disable = + PlotSquared.imp().getPlayerManager().getPlayerIfExists(plot.getOwnerAbs()) + == null; + } + } + if (disable) { + for (UUID trusted : plot.getTrusted()) { + if (PlotSquared.imp().getPlayerManager().getPlayerIfExists(trusted) != null) { + disable = false; + break; + } + } + if (disable) { + event.setNewCurrent(0); + plot.debug( + "Redstone event was cancelled because no trusted player was in the plot"); + return; + } + } + } + if (Settings.Redstone.DISABLE_UNOCCUPIED) { + for (final PlotPlayer player : PlotSquared.imp().getPlayerManager().getPlayers()) { + if (plot.equals(player.getCurrentPlot())) { + return; + } + } + event.setNewCurrent(0); + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onPhysicsEvent(BlockPhysicsEvent event) { + switch (event.getChangedType()) { + case COMPARATOR: { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + if (location.isPlotArea()) { + return; + } + Plot plot = location.getOwnedPlotAbs(); + if (plot == null) { + return; + } + if (!plot.getFlag(RedstoneFlag.class)) { + event.setCancelled(true); + plot.debug("Prevented comparator update because redstone = false"); + } + return; + } + case ANVIL: + case DRAGON_EGG: + case GRAVEL: + case SAND: + case TURTLE_EGG: + case TURTLE_HELMET: + case TURTLE_SPAWN_EGG: { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlotAbs(location); + if (plot == null) { + return; + } + if (plot.getFlag(DisablePhysicsFlag.class)) { + event.setCancelled(true); + plot.debug("Prevented block physics because disable-physics = true"); + } + return; + } + default: + if (Settings.Redstone.DETECT_INVALID_EDGE_PISTONS) { + Block block = event.getBlock(); + switch (block.getType()) { + case PISTON: + case STICKY_PISTON: + org.bukkit.block.data.Directional piston = + (org.bukkit.block.data.Directional) block.getBlockData(); + Location location = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlotAbs(location); + if (plot == null) { + return; + } + switch (piston.getFacing()) { + case EAST: + location.setX(location.getX() + 1); + break; + case SOUTH: + location.setX(location.getX() - 1); + break; + case WEST: + location.setZ(location.getZ() + 1); + break; + case NORTH: + location.setZ(location.getZ() - 1); + break; + } + Plot newPlot = area.getOwnedPlotAbs(location); + if (!plot.equals(newPlot)) { + event.setCancelled(true); + plot.debug( + "Prevented piston update because of invalid edge piston detection"); + return; + } + } + } + break; + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void blockCreate(BlockPlaceEvent event) { + Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Player player = event.getPlayer(); + BukkitPlayer pp = BukkitUtil.getPlayer(player); + Plot plot = area.getPlot(location); + if (plot != null) { + if ((location.getY() > area.getMaxBuildHeight() || location.getY() < area + .getMinBuildHeight()) && !Permissions + .hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_HEIGHT_LIMIT)) { + event.setCancelled(true); + MainUtil.sendMessage(pp, Captions.HEIGHT_LIMIT.getTranslated() + .replace("{limit}", String.valueOf(area.getMaxBuildHeight()))); + } + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_UNOWNED); + event.setCancelled(true); + return; + } + } else if (!plot.isAdded(pp.getUUID())) { + List place = plot.getFlag(PlaceFlag.class); + if (place != null) { + Block block = event.getBlock(); + if (place.contains( + BlockTypeWrapper.get(BukkitAdapter.asBlockType(block.getType())))) { + return; + } + } + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + plot.debug(player.getName() + " could not place " + event.getBlock().getType() + + " because of the place flag"); + return; + } + } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + return; + } + } + if (plot.getFlag(DisablePhysicsFlag.class)) { + Block block = event.getBlockPlaced(); + if (block.getType().hasGravity()) { + sendBlockChange(block.getLocation(), block.getBlockData()); + plot.debug(event.getBlock().getType() + + " did not fall because of disable-physics = true"); + } + } + } else if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_ROAD); + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOWEST) public void blockDestroy(BlockBreakEvent event) { + Player player = event.getPlayer(); + Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getPlot(location); + if (plot != null) { + BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + if (event.getBlock().getY() == 0) { + if (!Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL); + event.setCancelled(true); + return; + } + } else if ((location.getY() > area.getMaxBuildHeight() || location.getY() < area + .getMinBuildHeight()) && !Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_HEIGHT_LIMIT)) { + event.setCancelled(true); + MainUtil.sendMessage(plotPlayer, Captions.HEIGHT_LIMIT.getTranslated() + .replace("{limit}", String.valueOf(area.getMaxBuildHeight()))); + } + if (!plot.hasOwner()) { + if (!Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED, true)) { + event.setCancelled(true); + } + return; + } + if (!plot.isAdded(plotPlayer.getUUID())) { + List destroy = plot.getFlag(BreakFlag.class); + Block block = event.getBlock(); + final BlockType blockType = BukkitAdapter.asBlockType(block.getType()); + for (final BlockTypeWrapper blockTypeWrapper : destroy) { + if (blockTypeWrapper.accepts(blockType)) { + return; + } + } + if (Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { + return; + } + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_OTHER); + event.setCancelled(true); + } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { + if (!Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + return; + } + } + return; + } + BukkitPlayer pp = BukkitUtil.getPlayer(player); + if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { + return; + } + if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) { + if (player.getInventory().getItemInMainHand().getType() == Material + .getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) { + return; + } + } + MainUtil + .sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_ROAD); + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockSpread(BlockSpreadEvent event) { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + if (location.isPlotRoad()) { + event.setCancelled(true); + return; + } + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlot(location); + if (plot == null) { + return; + } + switch (event.getSource().getType()) { + case GRASS_BLOCK: + if (!plot.getFlag(GrassGrowFlag.class)) { + plot.debug("Grass could not grow because grass-grow = false"); + event.setCancelled(true); + } + break; + case MYCELIUM: + if (!plot.getFlag(MycelGrowFlag.class)) { + plot.debug("Mycelium could not grow because mycel-grow = false"); + event.setCancelled(true); + } + break; + case VINE: + if (!plot.getFlag(VineGrowFlag.class)) { + plot.debug("Vine could not grow because vine-grow = false"); + event.setCancelled(true); + } + break; + case KELP: + if (!plot.getFlag(KelpGrowFlag.class)) { + plot.debug("Kelp could not grow because kelp-grow = false"); + event.setCancelled(true); + } + break; + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockForm(BlockFormEvent event) { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + if (location.isPlotRoad()) { + event.setCancelled(true); + return; + } + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlot(location); + if (plot == null) { + return; + } + switch (event.getNewState().getType()) { + case SNOW: + case SNOW_BLOCK: + if (!plot.getFlag(SnowFormFlag.class)) { + plot.debug("Snow could not form because snow-form = false"); + event.setCancelled(true); + } + return; + case ICE: + case FROSTED_ICE: + case PACKED_ICE: + if (!plot.getFlag(IceFormFlag.class)) { + plot.debug("Ice could not form because ice-form = false"); + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityBlockForm(EntityBlockFormEvent event) { + String world = event.getBlock().getWorld().getName(); + if (!PlotSquared.get().hasPlotArea(world)) { + return; + } + Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlot(location); + if (plot == null) { + event.setCancelled(true); + return; + } + Entity entity = event.getEntity(); + if (entity instanceof Player) { + Player player = (Player) entity; + if (!plot.hasOwner()) { + BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + if (plot.getFlag(IceFormFlag.class)) { + plot.debug("Ice could not be formed because ice-form = false"); + return; + } + event.setCancelled(true); + return; + } + BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + if (!plot.isAdded(plotPlayer.getUUID())) { + if (plot.getFlag(IceFormFlag.class)) { + plot.debug("Ice could not be formed because ice-form = false"); + return; + } + event.setCancelled(true); + return; + } + return; + } + if (!plot.getFlag(IceFormFlag.class)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockDamage(BlockDamageEvent event) { + Player player = event.getPlayer(); + Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + if (player.getGameMode() != GameMode.SURVIVAL) { + return; + } + Plot plot = area.getPlot(location); + if (plot != null) { + if (plot.getFlag(InstabreakFlag.class)) { + Block block = event.getBlock(); + BlockBreakEvent call = new BlockBreakEvent(block, player); + Bukkit.getServer().getPluginManager().callEvent(call); + if (!call.isCancelled()) { + event.getBlock().breakNaturally(); + } + } + if (location.getY() == 0) { + event.setCancelled(true); + return; + } + if (!plot.hasOwner()) { + BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + if (Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + return; + } + event.setCancelled(true); + return; + } + BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + if (!plot.isAdded(plotPlayer.getUUID())) { + List destroy = plot.getFlag(BreakFlag.class); + Block block = event.getBlock(); + if (destroy + .contains(BlockTypeWrapper.get(BukkitAdapter.asBlockType(block.getType()))) + || Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { + return; + } + plot.debug(player.getName() + " could not break " + block.getType() + + " because it was not in the break flag"); + event.setCancelled(true); + return; + } + return; + } + BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { + return; + } + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onFade(BlockFadeEvent event) { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlot(location); + if (plot == null) { + event.setCancelled(true); + return; + } + switch (block.getType()) { + case ICE: + if (!plot.getFlag(IceMeltFlag.class)) { + plot.debug("Ice could not melt because ice-melt = false"); + event.setCancelled(true); + } + break; + case SNOW: + if (!plot.getFlag(SnowMeltFlag.class)) { + plot.debug("Snow could not melt because snow-melt = false"); + event.setCancelled(true); + } + break; + case FARMLAND: + if (!plot.getFlag(SoilDryFlag.class)) { + plot.debug("Soil could not dry because soil-dry = false"); + event.setCancelled(true); + } + break; + case TUBE_CORAL_BLOCK: + case BRAIN_CORAL_BLOCK: + case BUBBLE_CORAL_BLOCK: + case FIRE_CORAL_BLOCK: + case HORN_CORAL_BLOCK: + case TUBE_CORAL: + case BRAIN_CORAL: + case BUBBLE_CORAL: + case FIRE_CORAL: + case HORN_CORAL: + case TUBE_CORAL_FAN: + case BRAIN_CORAL_FAN: + case BUBBLE_CORAL_FAN: + case FIRE_CORAL_FAN: + case HORN_CORAL_FAN: + case BRAIN_CORAL_WALL_FAN: + case BUBBLE_CORAL_WALL_FAN: + case FIRE_CORAL_WALL_FAN: + case HORN_CORAL_WALL_FAN: + case TUBE_CORAL_WALL_FAN: + if (!plot.getFlag(CoralDryFlag.class)) { + plot.debug("Coral could not dry because coral-dry = false"); + event.setCancelled(true); + } + break; + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onChange(BlockFromToEvent event) { + Block from = event.getBlock(); + + // Check liquid flow flag inside of origin plot too + final Location fLocation = BukkitUtil.getLocation(from.getLocation()); + final PlotArea fromArea = fLocation.getPlotArea(); + if (fromArea != null) { + final Plot plot = fromArea.getOwnedPlot(fLocation); + if (plot != null + && plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.DISABLED && event + .getBlock().isLiquid()) { + plot.debug("Liquid could now flow because liquid-flow = disabled"); + event.setCancelled(true); + return; + } + } + + Block to = event.getToBlock(); + Location tLocation = BukkitUtil.getLocation(to.getLocation()); + PlotArea area = tLocation.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlot(tLocation); + if (plot != null) { + if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects + .equals(plot, area.getOwnedPlot(fLocation))) { + event.setCancelled(true); + return; + } + if (plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.ENABLED && event + .getBlock().isLiquid()) { + return; + } + if (plot.getFlag(DisablePhysicsFlag.class)) { + plot.debug(event.getBlock().getType() + + " could not update because disable-physics = true"); + event.setCancelled(true); + return; + } + if (plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.DISABLED && event + .getBlock().isLiquid()) { + plot.debug("Liquid could not flow because liquid-flow = disabled"); + event.setCancelled(true); + } + } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects + .equals(null, area.getOwnedPlot(fLocation))) { + event.setCancelled(true); + } else if (event.getBlock().isLiquid()) { + final org.bukkit.Location location = event.getBlock().getLocation(); + + /* + X = block location + A-H = potential plot locations + + Z + ^ + | A B C + o D X E + | F G H + v + <-----O-----> x + */ + if (BukkitUtil.getPlot(location.clone().add(-1, 0, 1) /* A */) != null + || BukkitUtil.getPlot(location.clone().add(1, 0, 0) /* B */) != null + || BukkitUtil.getPlot(location.clone().add(1, 0, 1) /* C */) != null + || BukkitUtil.getPlot(location.clone().add(-1, 0, 0) /* D */) != null + || BukkitUtil.getPlot(location.clone().add(1, 0, 0) /* E */) != null + || BukkitUtil.getPlot(location.clone().add(-1, 0, -1) /* F */) != null + || BukkitUtil.getPlot(location.clone().add(0, 0, -1) /* G */) != null + || BukkitUtil.getPlot(location.clone().add(1, 0, 1) /* H */) != null) { + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onGrow(BlockGrowEvent event) { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + if (location.isUnownedPlotArea()) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPistonExtend(BlockPistonExtendEvent event) { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + BlockFace face = event.getDirection(); + Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ()); + PlotArea area = location.getPlotArea(); + if (area == null) { + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + return; + } + for (Block block1 : event.getBlocks()) { + Location bloc = BukkitUtil.getLocation(block1.getLocation()); + if (bloc.isPlotArea() || bloc + .add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()) + .isPlotArea()) { + event.setCancelled(true); + return; + } + } + if (location.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()) + .isPlotArea()) { + // Prevent pistons from extending if they are: bordering a plot + // area, facing inside plot area, and not pushing any blocks + event.setCancelled(true); + } + return; + } + Plot plot = area.getOwnedPlot(location); + if (plot == null) { + event.setCancelled(true); + return; + } + for (Block block1 : event.getBlocks()) { + Location bloc = BukkitUtil.getLocation(block1.getLocation()); + if (!area.contains(bloc.getX(), bloc.getZ()) || !area + .contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { + event.setCancelled(true); + return; + } + if (!plot.equals(area.getOwnedPlot(bloc)) || !plot.equals(area.getOwnedPlot( + bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { + event.setCancelled(true); + return; + } + } + if (!plot.equals(area.getOwnedPlot( + location.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { + // This branch is only necessary to prevent pistons from extending + // if they are: on a plot edge, facing outside the plot, and not + // pushing any blocks + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPistonRetract(BlockPistonRetractEvent event) { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + BlockFace face = event.getDirection(); + Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ()); + PlotArea area = location.getPlotArea(); + if (area == null) { + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + return; + } + for (Block block1 : event.getBlocks()) { + Location bloc = BukkitUtil.getLocation(block1.getLocation()); + if (bloc.isPlotArea() || bloc + .add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()) + .isPlotArea()) { + event.setCancelled(true); + return; + } + } + return; + } + Plot plot = area.getOwnedPlot(location); + if (plot == null) { + event.setCancelled(true); + return; + } + for (Block block1 : event.getBlocks()) { + Location bloc = BukkitUtil.getLocation(block1.getLocation()); + if (!area.contains(bloc.getX(), bloc.getZ()) || !area + .contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { + event.setCancelled(true); + return; + } + if (!plot.equals(area.getOwnedPlot(bloc)) || !plot.equals(area.getOwnedPlot( + bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { + event.setCancelled(true); + return; + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockDispense(BlockDispenseEvent event) { + Material type = event.getItem().getType(); + switch (type) { + case SHULKER_BOX: + case WHITE_SHULKER_BOX: + case ORANGE_SHULKER_BOX: + case MAGENTA_SHULKER_BOX: + case LIGHT_BLUE_SHULKER_BOX: + case YELLOW_SHULKER_BOX: + case LIME_SHULKER_BOX: + case PINK_SHULKER_BOX: + case GRAY_SHULKER_BOX: + case LIGHT_GRAY_SHULKER_BOX: + case CYAN_SHULKER_BOX: + case PURPLE_SHULKER_BOX: + case BLUE_SHULKER_BOX: + case BROWN_SHULKER_BOX: + case GREEN_SHULKER_BOX: + case RED_SHULKER_BOX: + case BLACK_SHULKER_BOX: + case CARVED_PUMPKIN: + case WITHER_SKELETON_SKULL: + case FLINT_AND_STEEL: + case BONE_MEAL: + case SHEARS: + case GLASS_BOTTLE: + case GLOWSTONE: + case COD_BUCKET: + case PUFFERFISH_BUCKET: + case SALMON_BUCKET: + case TROPICAL_FISH_BUCKET: + case BUCKET: + case WATER_BUCKET: + case LAVA_BUCKET: { + if (event.getBlock().getType() == Material.DROPPER) { + return; + } + BlockFace targetFace = + ((Directional) event.getBlock().getState().getData()).getFacing(); + Location location = + BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation()); + if (location.isPlotRoad()) { + event.setCancelled(true); + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onStructureGrow(StructureGrowEvent event) { + if (!PlotSquared.get().hasPlotArea(event.getWorld().getName())) { + return; + } + List blocks = event.getBlocks(); + if (blocks.isEmpty()) { + return; + } + Location location = BukkitUtil.getLocation(blocks.get(0).getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + for (int i = blocks.size() - 1; i >= 0; i--) { + location = BukkitUtil.getLocation(blocks.get(i).getLocation()); + if (location.isPlotArea()) { + blocks.remove(i); + } + } + return; + } else { + Plot origin = area.getOwnedPlot(location); + if (origin == null) { + event.setCancelled(true); + return; + } + for (int i = blocks.size() - 1; i >= 0; i--) { + location = BukkitUtil.getLocation(blocks.get(i).getLocation()); + if (!area.contains(location.getX(), location.getZ())) { + blocks.remove(i); + continue; + } + Plot plot = area.getOwnedPlot(location); + if (!Objects.equals(plot, origin)) { + event.getBlocks().remove(i); + } + } + } + Plot origin = area.getPlot(location); + if (origin == null) { + event.setCancelled(true); + return; + } + for (int i = blocks.size() - 1; i >= 0; i--) { + location = BukkitUtil.getLocation(blocks.get(i).getLocation()); + Plot plot = area.getOwnedPlot(location); + /* + * plot → the base plot of the merged area + * origin → the plot where the event gets called + */ + + // Are plot and origin different AND are both plots merged + if (plot != null && !Objects.equals(plot, origin) && (!plot.isMerged() && !origin + .isMerged())) { + event.getBlocks().remove(i); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBigBoom(BlockExplodeEvent event) { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + String world = location.getWorld(); + if (!PlotSquared.get().hasPlotArea(world)) { + return; + } + PlotArea area = location.getPlotArea(); + if (area == null) { + Iterator iterator = event.blockList().iterator(); + while (iterator.hasNext()) { + location = BukkitUtil.getLocation(iterator.next().getLocation()); + if (location.isPlotArea()) { + iterator.remove(); + } + } + return; + } + Plot plot = area.getOwnedPlot(location); + if (plot == null || !plot.getFlag(ExplosionFlag.class)) { + event.setCancelled(true); + if (plot != null) { + plot.debug("Explosion was cancelled because explosion = false"); + } + } + event.blockList().removeIf(blox -> plot != null && !plot + .equals(area.getOwnedPlot(BukkitUtil.getLocation(blox.getLocation())))); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBurn(BlockBurnEvent event) { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + + Plot plot = location.getOwnedPlot(); + if (plot == null || !plot.getFlag(BlockBurnFlag.class)) { + if (plot != null) { + plot.debug("Block burning was cancelled because block-burn = false"); + } + event.setCancelled(true); + } + + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockIgnite(BlockIgniteEvent event) { + Player player = event.getPlayer(); + Entity ignitingEntity = event.getIgnitingEntity(); + Block block = event.getBlock(); + BlockIgniteEvent.IgniteCause igniteCause = event.getCause(); + Location location1 = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location1.getPlotArea(); + if (area == null) { + return; + } + if (igniteCause == BlockIgniteEvent.IgniteCause.LIGHTNING) { + event.setCancelled(true); + return; + } + + Plot plot = area.getOwnedPlot(location1); + if (player != null) { + BukkitPlayer pp = BukkitUtil.getPlayer(player); + if (plot == null) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_ROAD); + event.setCancelled(true); + } + } else if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_UNOWNED); + event.setCancelled(true); + } + } else if (!plot.isAdded(pp.getUUID())) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + } + } else if (!plot.getFlag(BlockIgnitionFlag.class)) { + event.setCancelled(true); + } + } else { + if (plot == null) { + event.setCancelled(true); + return; + } + if (ignitingEntity != null) { + if (!plot.getFlag(BlockIgnitionFlag.class)) { + event.setCancelled(true); + plot.debug("Block ignition was cancelled because block-ignition = false"); + return; + } + if (igniteCause == BlockIgniteEvent.IgniteCause.FIREBALL) { + if (ignitingEntity instanceof Fireball) { + Projectile fireball = (Projectile) ignitingEntity; + Location location = null; + if (fireball.getShooter() instanceof Entity) { + Entity shooter = (Entity) fireball.getShooter(); + location = BukkitUtil.getLocation(shooter.getLocation()); + } else if (fireball.getShooter() instanceof BlockProjectileSource) { + Block shooter = + ((BlockProjectileSource) fireball.getShooter()).getBlock(); + location = BukkitUtil.getLocation(shooter.getLocation()); + } + if (location != null && !plot.equals(location.getPlot())) { + event.setCancelled(true); + } + } + } + + } else if (event.getIgnitingBlock() != null) { + Block ignitingBlock = event.getIgnitingBlock(); + Plot plotIgnited = BukkitUtil.getLocation(ignitingBlock.getLocation()).getPlot(); + if (igniteCause == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL && ( + !plot.getFlag(BlockIgnitionFlag.class) || plotIgnited == null || !plotIgnited + .equals(plot)) || (igniteCause == BlockIgniteEvent.IgniteCause.SPREAD + || igniteCause == BlockIgniteEvent.IgniteCause.LAVA) && ( + !plot.getFlag(BlockIgnitionFlag.class) || plotIgnited == null || !plotIgnited + .equals(plot))) { + event.setCancelled(true); + } + } + } + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java new file mode 100644 index 000000000..8de57cdaf --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java @@ -0,0 +1,317 @@ +package com.plotsquared.bukkit.listener; + +import com.plotsquared.bukkit.util.BukkitEntityUtil; +import com.plotsquared.bukkit.util.BukkitUtil; +import com.plotsquared.core.PlotSquared; +import com.plotsquared.core.configuration.Settings; +import com.plotsquared.core.location.Location; +import com.plotsquared.core.plot.Plot; +import com.plotsquared.core.plot.PlotArea; +import com.plotsquared.core.plot.flag.implementations.DisablePhysicsFlag; +import com.plotsquared.core.plot.flag.implementations.ExplosionFlag; +import com.plotsquared.core.plot.flag.implementations.InvincibleFlag; +import com.plotsquared.core.plot.flag.implementations.MobPlaceFlag; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Ageable; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.FallingBlock; +import org.bukkit.entity.TNTPrimed; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityCombustByEntityEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.entity.ExplosionPrimeEvent; +import org.bukkit.event.vehicle.VehicleCreateEvent; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; + +import java.util.Iterator; +import java.util.List; + +@SuppressWarnings("unused") +public class EntityEventListener implements Listener { + + private float lastRadius; + + @EventHandler(priority = EventPriority.HIGHEST) + public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { + EntityDamageByEntityEvent eventChange = + new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), + EntityDamageEvent.DamageCause.FIRE_TICK, event.getDuration()); + onEntityDamageByEntityEvent(eventChange); + if (eventChange.isCancelled()) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { + Entity damager = event.getDamager(); + Location location = BukkitUtil.getLocation(damager); + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + return; + } + Entity victim = event.getEntity(); +/* + if (victim.getType().equals(EntityType.ITEM_FRAME)) { + Plot plot = BukkitUtil.getLocation(victim).getPlot(); + if (plot != null && !plot.isAdded(damager.getUniqueId())) { + event.setCancelled(true); + return; + } + } +*/ + if (!BukkitEntityUtil.entityDamage(damager, victim, event.getCause())) { + if (event.isCancelled()) { + if (victim instanceof Ageable) { + Ageable ageable = (Ageable) victim; + if (ageable.getAge() == -24000) { + ageable.setAge(0); + ageable.setAdult(); + } + } + } + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void creatureSpawnEvent(CreatureSpawnEvent event) { + Entity entity = event.getEntity(); + Location location = BukkitUtil.getLocation(entity.getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + CreatureSpawnEvent.SpawnReason reason = event.getSpawnReason(); + switch (reason.toString()) { + case "DISPENSE_EGG": + case "EGG": + case "OCELOT_BABY": + case "SPAWNER_EGG": + if (!area.isSpawnEggs()) { + event.setCancelled(true); + return; + } + break; + case "REINFORCEMENTS": + case "NATURAL": + case "MOUNT": + case "PATROL": + case "RAID": + case "SHEARED": + case "SHOULDER_ENTITY": + case "SILVERFISH_BLOCK": + case "TRAP": + case "VILLAGE_DEFENSE": + case "VILLAGE_INVASION": + case "BEEHIVE": + case "CHUNK_GEN": + if (!area.isMobSpawning()) { + event.setCancelled(true); + return; + } + case "BREEDING": + if (!area.isSpawnBreeding()) { + event.setCancelled(true); + return; + } + break; + case "BUILD_IRONGOLEM": + case "BUILD_SNOWMAN": + case "BUILD_WITHER": + case "CUSTOM": + if (!area.isSpawnCustom() && entity.getType() != EntityType.ARMOR_STAND) { + event.setCancelled(true); + return; + } + break; + case "SPAWNER": + if (!area.isMobSpawnerSpawning()) { + event.setCancelled(true); + return; + } + break; + } + Plot plot = area.getOwnedPlotAbs(location); + if (plot == null) { + if (!area.isMobSpawning()) { + event.setCancelled(true); + } + return; + } + if (BukkitEntityUtil.checkEntity(entity, plot)) { + event.setCancelled(true); + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onEntityFall(EntityChangeBlockEvent event) { + if (event.getEntityType() != EntityType.FALLING_BLOCK) { + return; + } + Block block = event.getBlock(); + World world = block.getWorld(); + String worldName = world.getName(); + if (!PlotSquared.get().hasPlotArea(worldName)) { + return; + } + Location location = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlotAbs(location); + if (plot == null || plot.getFlag(DisablePhysicsFlag.class)) { + event.setCancelled(true); + if (plot != null) { + plot.debug("Fallin block event was cancelled because disable-physics = true"); + } + return; + } + if (event.getTo().hasGravity()) { + Entity entity = event.getEntity(); + List meta = entity.getMetadata("plot"); + if (meta.isEmpty()) { + return; + } + Plot origin = (Plot) meta.get(0).value(); + if (origin != null && !origin.equals(plot)) { + event.setCancelled(true); + entity.remove(); + } + } else if (event.getTo() == Material.AIR) { + event.getEntity() + .setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); + } + } + + @EventHandler(priority = EventPriority.HIGH) public void onDamage(EntityDamageEvent event) { + if (event.getEntityType() != EntityType.PLAYER) { + return; + } + Location location = BukkitUtil.getLocation(event.getEntity()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = location.getOwnedPlot(); + if (plot == null) { + if (area.isRoadFlags() && area.getRoadFlag(InvincibleFlag.class)) { + event.setCancelled(true); + } + return; + } + if (plot.getFlag(InvincibleFlag.class)) { + plot.debug( + event.getEntity().getName() + " could not take damage because invincible = true"); + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBigBoom(EntityExplodeEvent event) { + Location location = BukkitUtil.getLocation(event.getLocation()); + PlotArea area = location.getPlotArea(); + boolean plotArea = location.isPlotArea(); + if (!plotArea) { + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + return; + } + return; + } + Plot plot = area.getOwnedPlot(location); + if (plot != null) { + if (plot.getFlag(ExplosionFlag.class)) { + List meta = event.getEntity().getMetadata("plot"); + Plot origin; + if (meta.isEmpty()) { + origin = plot; + } else { + origin = (Plot) meta.get(0).value(); + } + if (this.lastRadius != 0) { + List nearby = event.getEntity() + .getNearbyEntities(this.lastRadius, this.lastRadius, this.lastRadius); + for (Entity near : nearby) { + if (near instanceof TNTPrimed || near.getType() + .equals(EntityType.MINECART_TNT)) { + if (!near.hasMetadata("plot")) { + near.setMetadata("plot", + new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); + } + } + } + this.lastRadius = 0; + } + Iterator iterator = event.blockList().iterator(); + while (iterator.hasNext()) { + Block block = iterator.next(); + location = BukkitUtil.getLocation(block.getLocation()); + if (!area.contains(location.getX(), location.getZ()) || (origin != null + && !origin.equals(area.getOwnedPlot(location)))) { + iterator.remove(); + } + } + return; + } else { + plot.debug("Explosion was cancelled because explosion = false"); + } + } + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPeskyMobsChangeTheWorldLikeWTFEvent(EntityChangeBlockEvent event) { + Entity e = event.getEntity(); + if (!(e instanceof FallingBlock)) { + Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); + PlotArea area = location.getPlotArea(); + if (area != null) { + Plot plot = area.getOwnedPlot(location); + if (plot != null && plot.getFlag(MobPlaceFlag.class)) { + System.out.println("bb"); + return; + } + if (plot != null) { + plot.debug(e.getType() + " could not change block because mob-place = false"); + } + System.out.println("aa"); + event.setCancelled(true); + } + } + } + + @EventHandler public void onPrime(ExplosionPrimeEvent event) { + this.lastRadius = event.getRadius() + 1; + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onVehicleCreate(VehicleCreateEvent event) { + Vehicle entity = event.getVehicle(); + Location location = BukkitUtil.getLocation(entity); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlotAbs(location); + if (plot == null || BukkitEntityUtil.checkEntity(entity, plot)) { + entity.remove(); + return; + } + if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { + entity + .setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); + } + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java index 0bf5e75e8..4b80909e7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java @@ -25,6 +25,7 @@ */ package com.plotsquared.bukkit.listener; +import com.plotsquared.bukkit.util.BukkitEntityUtil; import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.core.PlotSquared; import com.plotsquared.core.configuration.Settings; @@ -155,7 +156,7 @@ public class EntitySpawnListener implements Listener { } switch (entity.getType()) { case ENDER_CRYSTAL: - if (PlayerEvents.checkEntity(entity, plot)) { + if (BukkitEntityUtil.checkEntity(entity, plot)) { event.setCancelled(true); } case SHULKER: diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java new file mode 100644 index 000000000..e2bb3cb36 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java @@ -0,0 +1,1518 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.bukkit.listener; + +import com.destroystokyo.paper.MaterialTags; +import com.google.common.base.Charsets; +import com.plotsquared.bukkit.player.BukkitPlayer; +import com.plotsquared.bukkit.util.BukkitEntityUtil; +import com.plotsquared.bukkit.util.BukkitUtil; +import com.plotsquared.bukkit.util.UpdateUtility; +import com.plotsquared.core.PlotSquared; +import com.plotsquared.core.configuration.Captions; +import com.plotsquared.core.configuration.Settings; +import com.plotsquared.core.listener.PlayerBlockEventType; +import com.plotsquared.core.listener.PlotListener; +import com.plotsquared.core.location.Location; +import com.plotsquared.core.player.PlotPlayer; +import com.plotsquared.core.plot.Plot; +import com.plotsquared.core.plot.PlotArea; +import com.plotsquared.core.plot.PlotId; +import com.plotsquared.core.plot.PlotInventory; +import com.plotsquared.core.plot.flag.FlagContainer; +import com.plotsquared.core.plot.flag.implementations.AnimalInteractFlag; +import com.plotsquared.core.plot.flag.implementations.BlockedCmdsFlag; +import com.plotsquared.core.plot.flag.implementations.ChatFlag; +import com.plotsquared.core.plot.flag.implementations.DenyTeleportFlag; +import com.plotsquared.core.plot.flag.implementations.DoneFlag; +import com.plotsquared.core.plot.flag.implementations.DropProtectionFlag; +import com.plotsquared.core.plot.flag.implementations.HangingBreakFlag; +import com.plotsquared.core.plot.flag.implementations.HangingPlaceFlag; +import com.plotsquared.core.plot.flag.implementations.HostileInteractFlag; +import com.plotsquared.core.plot.flag.implementations.ItemDropFlag; +import com.plotsquared.core.plot.flag.implementations.KeepInventoryFlag; +import com.plotsquared.core.plot.flag.implementations.MiscInteractFlag; +import com.plotsquared.core.plot.flag.implementations.PlayerInteractFlag; +import com.plotsquared.core.plot.flag.implementations.PreventCreativeCopyFlag; +import com.plotsquared.core.plot.flag.implementations.TamedInteractFlag; +import com.plotsquared.core.plot.flag.implementations.UntrustedVisitFlag; +import com.plotsquared.core.plot.flag.implementations.UseFlag; +import com.plotsquared.core.plot.flag.implementations.VehicleBreakFlag; +import com.plotsquared.core.plot.flag.implementations.VehicleUseFlag; +import com.plotsquared.core.plot.flag.implementations.VillagerInteractFlag; +import com.plotsquared.core.plot.flag.types.BlockTypeWrapper; +import com.plotsquared.core.plot.message.PlotMessage; +import com.plotsquared.core.util.MainUtil; +import com.plotsquared.core.util.MathMan; +import com.plotsquared.core.util.Permissions; +import com.plotsquared.core.util.PremiumVerification; +import com.plotsquared.core.util.RegExUtil; +import com.plotsquared.core.util.entity.EntityCategories; +import com.plotsquared.core.util.task.TaskManager; +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.block.BlockType; +import io.papermc.lib.PaperLib; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.FluidCollisionMode; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.command.PluginCommand; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.ItemFrame; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.Tameable; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityPickupItemEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.hanging.HangingBreakByEntityEvent; +import org.bukkit.event.hanging.HangingPlaceEvent; +import org.bukkit.event.inventory.ClickType; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.AsyncPlayerPreLoginEvent; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.event.player.PlayerBucketFillEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerEggThrowEvent; +import org.bukkit.event.player.PlayerEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.vehicle.VehicleDestroyEvent; +import org.bukkit.event.vehicle.VehicleEntityCollisionEvent; +import org.bukkit.event.vehicle.VehicleMoveEvent; +import org.bukkit.help.HelpTopic; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; +import org.bukkit.util.Vector; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * Player Events involving plots. + */ +@SuppressWarnings("unused") +public class PlayerEventListener extends PlotListener implements Listener { + + // To prevent recursion + private boolean tmpTeleport = true; + private Field fieldPlayer; + private PlayerMoveEvent moveTmp; + private String internalVersion; + + { + try { + fieldPlayer = PlayerEvent.class.getDeclaredField("player"); + fieldPlayer.setAccessible(true); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + } + } + + @EventHandler public void onVehicleEntityCollision(VehicleEntityCollisionEvent e) { + if (e.getVehicle().getType() == EntityType.BOAT) { + Location location = BukkitUtil.getLocation(e.getEntity()); + if (location.isPlotArea()) { + if (e.getEntity() instanceof Player) { + PlotPlayer player = BukkitUtil.getPlayer((Player) e.getEntity()); + Plot plot = player.getCurrentPlot(); + if (plot != null) { + if (!plot.isAdded(player.getUUID())) { + //Here the event is only canceled if the player is not the owner + //of the property on which he is located. + e.setCancelled(true); + } + } else { + e.setCancelled(true); + } + } else { + //Here the event is cancelled too, otherwise you can move the + //boat with EchoPets or other mobs running around on the plot. + e.setCancelled(true); + } + } + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void playerCommand(PlayerCommandPreprocessEvent event) { + String msg = event.getMessage().toLowerCase().replaceAll("/", "").trim(); + if (msg.isEmpty()) { + return; + } + Player player = event.getPlayer(); + PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); + Location location = plotPlayer.getLocation(); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + String[] parts = msg.split(" "); + Plot plot = plotPlayer.getCurrentPlot(); + // Check WorldEdit + switch (parts[0].toLowerCase()) { + case "up": + case "/up": + case "worldedit:up": + case "worldedit:/up": + if (plot == null || (!plot.isAdded(plotPlayer.getUUID()) && !Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER, true))) { + event.setCancelled(true); + return; + } + } + if (plot == null && !area.isRoadFlags()) { + return; + } + + List blockedCommands = plot != null ? + plot.getFlag(BlockedCmdsFlag.class) : + area.getFlag(BlockedCmdsFlag.class); + if (!blockedCommands.isEmpty() && !Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { + String part = parts[0]; + if (parts[0].contains(":")) { + part = parts[0].split(":")[1]; + msg = msg.replace(parts[0].split(":")[0] + ':', ""); + } + String s1 = part; + List aliases = new ArrayList<>(); + for (HelpTopic cmdLabel : Bukkit.getServer().getHelpMap().getHelpTopics()) { + if (part.equals(cmdLabel.getName())) { + break; + } + String label = cmdLabel.getName().replaceFirst("/", ""); + if (aliases.contains(label)) { + continue; + } + PluginCommand p; + if ((p = Bukkit.getPluginCommand(label)) != null) { + for (String a : p.getAliases()) { + if (aliases.contains(a)) { + continue; + } + aliases.add(a); + a = a.replaceFirst("/", ""); + if (!a.equals(label) && a.equals(part)) { + part = label; + break; + } + } + } + } + if (!s1.equals(part)) { + msg = msg.replace(s1, part); + } + for (String s : blockedCommands) { + Pattern pattern; + if (!RegExUtil.compiledPatterns.containsKey(s)) { + RegExUtil.compiledPatterns.put(s, pattern = Pattern.compile(s)); + } else { + pattern = RegExUtil.compiledPatterns.get(s); + } + if (pattern.matcher(msg).matches()) { + String perm; + if (plot != null && plot.isAdded(plotPlayer.getUUID())) { + perm = "plots.admin.command.blocked-cmds.shared"; + } else { + perm = "plots.admin.command.blocked-cmds.road"; + } + if (!Permissions.hasPermission(plotPlayer, perm)) { + MainUtil.sendMessage(plotPlayer, Captions.COMMAND_BLOCKED); + event.setCancelled(true); + } + return; + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPreLoin(final AsyncPlayerPreLoginEvent event) { + final UUID uuid; + if (Settings.UUID.OFFLINE) { + if (Settings.UUID.FORCE_LOWERCASE) { + uuid = UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + event.getName().toLowerCase()).getBytes(Charsets.UTF_8)); + } else { + uuid = UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + event.getName()).getBytes(Charsets.UTF_8)); + } + } else { + uuid = event.getUniqueId(); + } + PlotSquared.get().getImpromptuUUIDPipeline().storeImmediately(event.getName(), uuid); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onConnect(PlayerJoinEvent event) { + final Player player = event.getPlayer(); + BukkitUtil.removePlayer(player.getUniqueId()); + final PlotPlayer pp = BukkitUtil.getPlayer(player); + + Location location = pp.getLocation(); + PlotArea area = location.getPlotArea(); + if (area != null) { + Plot plot = area.getPlot(location); + if (plot != null) { + plotEntry(pp, plot); + } + } + // Delayed + + // Async + TaskManager.runTaskLaterAsync(() -> { + if (!player.hasPlayedBefore() && player.isOnline()) { + player.saveData(); + } + PlotSquared.get().getEventDispatcher().doJoinTask(pp); + }, 20); + + if (pp.hasPermission(Captions.PERMISSION_ADMIN_UPDATE_NOTIFICATION.getTranslated()) + && Settings.Enabled_Components.UPDATE_NOTIFICATIONS && PremiumVerification.isPremium() + && UpdateUtility.hasUpdate) { + new PlotMessage("-----------------------------------").send(pp); + new PlotMessage(Captions.PREFIX + "There appears to be a PlotSquared update available!") + .color("$1").send(pp); + new PlotMessage( + Captions.PREFIX + "&6You are running version " + UpdateUtility.internalVersion + .versionString() + ", &6latest version is " + UpdateUtility.spigotVersion) + .color("$1").send(pp); + new PlotMessage(Captions.PREFIX + "Download at:").color("$1").send(pp); + player.sendMessage(" https://www.spigotmc.org/resources/77506/updates"); + new PlotMessage("-----------------------------------").send(pp); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void playerRespawn(PlayerRespawnEvent event) { + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotSquared.get().getEventDispatcher().doRespawnTask(pp); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + Player player = event.getPlayer(); + BukkitPlayer pp = BukkitUtil.getPlayer(player); + Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); + org.bukkit.Location to = event.getTo(); + //noinspection ConstantConditions + if (to != null) { + Location location = BukkitUtil.getLocation(to); + PlotArea area = location.getPlotArea(); + if (area == null) { + if (lastPlot != null) { + plotExit(pp, lastPlot); + pp.deleteMeta(PlotPlayer.META_LAST_PLOT); + } + pp.deleteMeta(PlotPlayer.META_LOCATION); + return; + } + Plot plot = area.getPlot(location); + if (plot != null) { + final boolean result = DenyTeleportFlag.allowsTeleport(pp, plot); + // there is one possibility to still allow teleportation: + // to is identical to the plot's home location, and untrusted-visit is true + // i.e. untrusted-visit can override deny-teleport + // this is acceptable, because otherwise it wouldn't make sense to have both flags set + if (!result && !(plot.getFlag(UntrustedVisitFlag.class) && plot.getHomeSynchronous() + .equals(BukkitUtil.getLocationFull(to)))) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_ENTRY_DENIED); + event.setCancelled(true); + } + } + } + playerMove(event); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException { + final org.bukkit.Location from = event.getFrom(); + final org.bukkit.Location to = event.getTo(); + + int toX, toZ; + if ((toX = MathMan.roundInt(to.getX())) != MathMan.roundInt(from.getX()) + | (toZ = MathMan.roundInt(to.getZ())) != MathMan.roundInt(from.getZ())) { + Vehicle vehicle = event.getVehicle(); + + // Check allowed + if (!vehicle.getPassengers().isEmpty()) { + Entity passenger = vehicle.getPassengers().get(0); + + if (passenger instanceof Player) { + final Player player = (Player) passenger; + // reset + if (moveTmp == null) { + moveTmp = new PlayerMoveEvent(null, from, to); + } + moveTmp.setFrom(from); + moveTmp.setTo(to); + moveTmp.setCancelled(false); + fieldPlayer.set(moveTmp, player); + + List passengers = vehicle.getPassengers(); + + this.playerMove(moveTmp); + org.bukkit.Location dest; + if (moveTmp.isCancelled()) { + dest = from; + } else if (MathMan.roundInt(moveTmp.getTo().getX()) != toX + || MathMan.roundInt(moveTmp.getTo().getZ()) != toZ) { + dest = to; + } else { + dest = null; + } + if (dest != null) { + vehicle.eject(); + vehicle.setVelocity(new Vector(0d, 0d, 0d)); + PaperLib.teleportAsync(vehicle, dest); + passengers.forEach(vehicle::addPassenger); + return; + } + } + if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { + final com.sk89q.worldedit.world.entity.EntityType entityType = + BukkitAdapter.adapt(vehicle.getType()); + // Horses etc are vehicles, but they're also animals + // so this filters out all living entities + if (EntityCategories.VEHICLE.contains(entityType) && !EntityCategories.ANIMAL + .contains(entityType)) { + List meta = vehicle.getMetadata("plot"); + Plot toPlot = BukkitUtil.getLocation(to).getPlot(); + if (!meta.isEmpty()) { + Plot origin = (Plot) meta.get(0).value(); + if (origin != null && !origin.getBasePlot(false).equals(toPlot)) { + vehicle.remove(); + } + } else if (toPlot != null) { + vehicle.setMetadata("plot", + new FixedMetadataValue((Plugin) PlotSquared.get().IMP, toPlot)); + } + } + } + } + + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void playerMove(PlayerMoveEvent event) { + org.bukkit.Location from = event.getFrom(); + org.bukkit.Location to = event.getTo(); + int x2; + if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) { + Player player = event.getPlayer(); + BukkitPlayer pp = BukkitUtil.getPlayer(player); + // Cancel teleport + if (TaskManager.TELEPORT_QUEUE.remove(pp.getName())) { + MainUtil.sendMessage(pp, Captions.TELEPORT_FAILED); + } + // Set last location + Location location = BukkitUtil.getLocation(to); + pp.setMeta(PlotPlayer.META_LOCATION, location); + PlotArea area = location.getPlotArea(); + if (area == null) { + pp.deleteMeta(PlotPlayer.META_LAST_PLOT); + return; + } + Plot now = area.getPlot(location); + Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); + if (now == null) { + if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp + .getMeta("kick", false)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_EXIT_DENIED); + this.tmpTeleport = false; + if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { + player.teleport(from); + } else { + player.teleport(player.getWorld().getSpawnLocation()); + } + this.tmpTeleport = true; + event.setCancelled(true); + return; + } + } else if (now.equals(lastPlot)) { + ForceFieldListener.handleForcefield(player, pp, now); + } else if (!plotEntry(pp, now) && this.tmpTeleport) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_ENTRY_DENIED); + this.tmpTeleport = false; + to.setX(from.getBlockX()); + to.setY(from.getBlockY()); + to.setZ(from.getBlockZ()); + player.teleport(event.getTo()); + this.tmpTeleport = true; + return; + } + int border = area.getBorder(); + if (x2 > border && this.tmpTeleport) { + to.setX(border - 1); + this.tmpTeleport = false; + player.teleport(event.getTo()); + this.tmpTeleport = true; + MainUtil.sendMessage(pp, Captions.BORDER); + } + if (x2 < -border && this.tmpTeleport) { + to.setX(-border + 1); + this.tmpTeleport = false; + player.teleport(event.getTo()); + this.tmpTeleport = true; + MainUtil.sendMessage(pp, Captions.BORDER); + } + } + int z2; + if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) { + Player player = event.getPlayer(); + BukkitPlayer pp = BukkitUtil.getPlayer(player); + // Cancel teleport + if (TaskManager.TELEPORT_QUEUE.remove(pp.getName())) { + MainUtil.sendMessage(pp, Captions.TELEPORT_FAILED); + } + // Set last location + Location location = BukkitUtil.getLocation(to); + pp.setMeta(PlotPlayer.META_LOCATION, location); + PlotArea area = location.getPlotArea(); + if (area == null) { + pp.deleteMeta(PlotPlayer.META_LAST_PLOT); + return; + } + Plot now = area.getPlot(location); + Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); + if (now == null) { + if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp + .getMeta("kick", false)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_EXIT_DENIED); + this.tmpTeleport = false; + if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { + player.teleport(from); + } else { + player.teleport(player.getWorld().getSpawnLocation()); + } + this.tmpTeleport = true; + event.setCancelled(true); + return; + } + } else if (now.equals(lastPlot)) { + ForceFieldListener.handleForcefield(player, pp, now); + } else if (!plotEntry(pp, now) && this.tmpTeleport) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_ENTRY_DENIED); + this.tmpTeleport = false; + player.teleport(from); + to.setX(from.getBlockX()); + to.setY(from.getBlockY()); + to.setZ(from.getBlockZ()); + player.teleport(event.getTo()); + this.tmpTeleport = true; + return; + } + int border = area.getBorder(); + if (z2 > border && this.tmpTeleport) { + to.setZ(border - 1); + this.tmpTeleport = false; + player.teleport(event.getTo()); + this.tmpTeleport = true; + MainUtil.sendMessage(pp, Captions.BORDER); + } else if (z2 < -border && this.tmpTeleport) { + to.setZ(-border + 1); + this.tmpTeleport = false; + player.teleport(event.getTo()); + this.tmpTeleport = true; + MainUtil.sendMessage(pp, Captions.BORDER); + } + } + } + + @EventHandler(priority = EventPriority.LOW) public void onChat(AsyncPlayerChatEvent event) { + if (event.isCancelled()) { + return; + } + + BukkitPlayer plotPlayer = BukkitUtil.getPlayer(event.getPlayer()); + Location location = plotPlayer.getLocation(); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getPlot(location); + if (plot == null) { + return; + } + if (!((plot.getFlag(ChatFlag.class) && area.isPlotChat() && plotPlayer.getAttribute("chat")) + || area.isForcingPlotChat())) { + return; + } + if (plot.isDenied(plotPlayer.getUUID()) && !Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_CHAT_BYPASS)) { + return; + } + event.setCancelled(true); + String message = event.getMessage(); + String format = Captions.PLOT_CHAT_FORMAT.getTranslated(); + String sender = event.getPlayer().getDisplayName(); + PlotId id = plot.getId(); + Set recipients = event.getRecipients(); + recipients.clear(); + Set spies = new HashSet<>(); + for (final PlotPlayer pp : PlotSquared.imp().getPlayerManager().getPlayers()) { + if (pp.getAttribute("chatspy")) { + spies.add(((BukkitPlayer) pp).player); + } else { + Plot current = pp.getCurrentPlot(); + if (current != null && current.getBasePlot(false).equals(plot)) { + recipients.add(((BukkitPlayer) pp).player); + } + } + } + String partial = ChatColor.translateAlternateColorCodes('&', + format.replace("%plot_id%", id.getX() + ";" + id.getY()).replace("%sender%", sender)); + if (plotPlayer.hasPermission("plots.chat.color")) { + message = Captions.color(message); + } + String full = partial.replace("%msg%", message); + for (Player receiver : recipients) { + receiver.sendMessage(full); + } + if (!spies.isEmpty()) { + String spyMessage = Captions.PLOT_CHAT_SPY_FORMAT.getTranslated() + .replace("%plot_id%", id.getX() + ";" + id.getY()).replace("%sender%", sender) + .replace("%msg%", message); + for (Player player : spies) { + player.sendMessage(spyMessage); + } + } + PlotSquared.debug(full); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onWorldChanged(PlayerChangedWorldEvent event) { + Player player = event.getPlayer(); + BukkitPlayer pp = BukkitUtil.getPlayer(player); + // Delete last location + Plot plot = (Plot) pp.deleteMeta(PlotPlayer.META_LAST_PLOT); + pp.deleteMeta(PlotPlayer.META_LOCATION); + if (plot != null) { + plotExit(pp, plot); + } + if (PlotSquared.get().worldedit != null) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_WORLDEDIT_BYPASS)) { + if (pp.getAttribute("worldedit")) { + pp.removeAttribute("worldedit"); + } + } + } + if (Settings.Enabled_Components.PERMISSION_CACHE) { + pp.deleteMeta("perm"); + } + Location location = pp.getLocation(); + PlotArea area = location.getPlotArea(); + if (location.isPlotArea()) { + plot = location.getPlot(); + if (plot != null) { + plotEntry(pp, plot); + } + } + } + + @SuppressWarnings("deprecation") + @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) || !PlotSquared.get() + .hasPlotArea(entity.getWorld().getName())) { + return; + } + + HumanEntity clicker = event.getWhoClicked(); + if (!(clicker instanceof Player)) { + return; + } + Player player = (Player) clicker; + BukkitPlayer pp = BukkitUtil.getPlayer(player); + final PlotInventory inventory = PlotInventory.getOpenPlotInventory(pp); + if (inventory != null && event.getRawSlot() == event.getSlot()) { + if (!inventory.onClick(event.getSlot())) { + event.setResult(Event.Result.DENY); + event.setCancelled(true); + inventory.close(); + } + } + PlayerInventory inv = player.getInventory(); + int slot = inv.getHeldItemSlot(); + if ((slot > 8) || !event.getEventName().equals("InventoryCreativeEvent")) { + return; + } + ItemStack current = inv.getItemInHand(); + ItemStack newItem = event.getCursor(); + if (newItem == null) { + return; + } + ItemMeta newMeta = newItem.getItemMeta(); + ItemMeta oldMeta = newItem.getItemMeta(); + + if (event.getClick() == ClickType.CREATIVE) { + final Plot plot = pp.getCurrentPlot(); + if (plot != null) { + if (plot.getFlag(PreventCreativeCopyFlag.class) && !plot + .isAdded(player.getUniqueId()) && !Permissions + .hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_OTHER)) { + final ItemStack newStack = + new ItemStack(newItem.getType(), newItem.getAmount()); + event.setCursor(newStack); + plot.debug(player.getName() + + " could not creative-copy an item because prevent-creative-copy = true"); + } + } else { + PlotArea area = pp.getPlotAreaAbs(); + if (area != null && area.isRoadFlags() && area + .getRoadFlag(PreventCreativeCopyFlag.class)) { + final ItemStack newStack = + new ItemStack(newItem.getType(), newItem.getAmount()); + event.setCursor(newStack); + } + } + return; + } + + String newLore = ""; + if (newMeta != null) { + List lore = newMeta.getLore(); + if (lore != null) { + newLore = lore.toString(); + } + } + String oldLore = ""; + if (oldMeta != null) { + List lore = oldMeta.getLore(); + if (lore != null) { + oldLore = lore.toString(); + } + } + if (!"[(+NBT)]".equals(newLore) || (current.equals(newItem) && newLore.equals(oldLore))) { + switch (newItem.getType()) { + case LEGACY_BANNER: + case PLAYER_HEAD: + if (newMeta != null) { + break; + } + default: + return; + } + } + Block block = player.getTargetBlock(null, 7); + org.bukkit.block.BlockState state = block.getState(); + Material stateType = state.getType(); + Material itemType = newItem.getType(); + if (stateType != itemType) { + switch (stateType) { + case LEGACY_STANDING_BANNER: + case LEGACY_WALL_BANNER: + if (itemType == Material.LEGACY_BANNER) { + break; + } + case LEGACY_SKULL: + if (itemType == Material.LEGACY_SKULL_ITEM) { + break; + } + default: + return; + } + } + Location location = BukkitUtil.getLocation(state.getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getPlotAbs(location); + boolean cancelled = false; + if (plot == null) { + if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.road"); + cancelled = true; + } + } else if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { + MainUtil + .sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); + cancelled = true; + } + } else { + UUID uuid = pp.getUUID(); + if (!plot.isAdded(uuid)) { + if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + "plots.admin.interact.other"); + cancelled = true; + } + } + } + if (cancelled) { + if ((current.getType() == newItem.getType()) && (current.getDurability() == newItem + .getDurability())) { + event.setCursor( + new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); + event.setCancelled(true); + return; + } + event.setCursor( + new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInteract(PlayerInteractAtEntityEvent e) { + Entity entity = e.getRightClicked(); + if (!(entity instanceof ArmorStand) && !(entity instanceof ItemFrame)) { + return; + } + Location location = BukkitUtil.getLocation(e.getRightClicked().getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + EntitySpawnListener.testNether(entity); + Plot plot = location.getPlotAbs(); + BukkitPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); + if (plot == null) { + if (!area.isRoadFlags() && !area.getRoadFlag(MiscInteractFlag.class) && !Permissions + .hasPermission(pp, "plots.admin.interact.road")) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.road"); + e.setCancelled(true); + } + } else { + if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); + e.setCancelled(true); + return; + } + } + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + "plots.admin.interact.unowned"); + e.setCancelled(true); + } + } else { + UUID uuid = pp.getUUID(); + if (plot.isAdded(uuid)) { + return; + } + if (plot.getFlag(MiscInteractFlag.class)) { + return; + } + if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + "plots.admin.interact.other"); + e.setCancelled(true); + plot.debug(pp.getName() + " could not interact with " + entity.getType() + + " bcause misc-interact = false"); + } + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onCancelledInteract(PlayerInteractEvent event) { + if (event.isCancelled() && event.getAction() == Action.RIGHT_CLICK_AIR) { + Player player = event.getPlayer(); + BukkitPlayer pp = BukkitUtil.getPlayer(player); + PlotArea area = pp.getPlotAreaAbs(); + if (area == null) { + return; + } + if (event.getAction() == Action.RIGHT_CLICK_AIR) { + Material item = event.getMaterial(); + if (item.toString().toLowerCase().endsWith("_egg")) { + event.setCancelled(true); + event.setUseItemInHand(Event.Result.DENY); + } + } + ItemStack hand = player.getInventory().getItemInMainHand(); + ItemStack offHand = player.getInventory().getItemInOffHand(); + Material type = hand.getType(); + Material offType = offHand.getType(); + if (type == Material.AIR) { + type = offType; + } + if (type.toString().toLowerCase().endsWith("_egg")) { + Block block = player.getTargetBlockExact(5, FluidCollisionMode.SOURCE_ONLY); + if (block != null && block.getType() != Material.AIR) { + Location location = BukkitUtil.getLocation(block.getLocation()); + if (!PlotSquared.get().getEventDispatcher() + .checkPlayerBlockEvent(pp, PlayerBlockEventType.SPAWN_MOB, location, null, + true)) { + event.setCancelled(true); + event.setUseItemInHand(Event.Result.DENY); + } + } + } + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onInteract(PlayerInteractEvent event) { + Player player = event.getPlayer(); + BukkitPlayer pp = BukkitUtil.getPlayer(player); + PlotArea area = pp.getPlotAreaAbs(); + if (area == null) { + return; + } + PlayerBlockEventType eventType = null; + BlockType blocktype1; + Block block = event.getClickedBlock(); + if (block == null) { + return; + } + Location location = BukkitUtil.getLocation(block.getLocation()); + Action action = event.getAction(); + outer: + switch (action) { + case PHYSICAL: { + eventType = PlayerBlockEventType.TRIGGER_PHYSICAL; + blocktype1 = BukkitAdapter.asBlockType(block.getType()); + System.out.println("cc"); + break; + } + //todo rearrange the right click code. it is all over the place. + case RIGHT_CLICK_BLOCK: { + Material blockType = block.getType(); + eventType = PlayerBlockEventType.INTERACT_BLOCK; + blocktype1 = BukkitAdapter.asBlockType(block.getType()); + + if (blockType.isInteractable()) { + if (!player.isSneaking()) { + break; + } + ItemStack hand = player.getInventory().getItemInMainHand(); + ItemStack offHand = player.getInventory().getItemInOffHand(); + + // sneaking players interact with blocks if both hands are empty + if (hand.getType() == Material.AIR && offHand.getType() == Material.AIR) { + break; + } + } + + Material type = event.getMaterial(); + + // in the following, lb needs to have the material of the item in hand i.e. type + switch (type) { + case REDSTONE: + case STRING: + case PUMPKIN_SEEDS: + case MELON_SEEDS: + case COCOA_BEANS: + case WHEAT_SEEDS: + case BEETROOT_SEEDS: + case SWEET_BERRIES: + return; + default: + //eventType = PlayerBlockEventType.PLACE_BLOCK; + if (type.isBlock()) { + return; + } + } + if (PaperLib.isPaper()) { + if (MaterialTags.SPAWN_EGGS.isTagged(type) || Material.EGG.equals(type)) { + eventType = PlayerBlockEventType.SPAWN_MOB; + break; + } + } else { + if (type.toString().toLowerCase().endsWith("egg")) { + eventType = PlayerBlockEventType.SPAWN_MOB; + break; + } + } + if (type.isEdible()) { + //Allow all players to eat while also allowing the block place event ot be fired + return; + } + switch (type) { + case ACACIA_BOAT: + case BIRCH_BOAT: + case CHEST_MINECART: + case COMMAND_BLOCK_MINECART: + case DARK_OAK_BOAT: + case FURNACE_MINECART: + case HOPPER_MINECART: + case JUNGLE_BOAT: + case MINECART: + case OAK_BOAT: + case SPRUCE_BOAT: + case TNT_MINECART: + eventType = PlayerBlockEventType.PLACE_VEHICLE; + break outer; + case FIREWORK_ROCKET: + case FIREWORK_STAR: + eventType = PlayerBlockEventType.SPAWN_MOB; + break outer; + case BOOK: + case KNOWLEDGE_BOOK: + case WRITABLE_BOOK: + case WRITTEN_BOOK: + eventType = PlayerBlockEventType.READ; + break outer; + case ARMOR_STAND: + location = BukkitUtil + .getLocation(block.getRelative(event.getBlockFace()).getLocation()); + eventType = PlayerBlockEventType.PLACE_MISC; + break outer; + } + break; + } + case LEFT_CLICK_BLOCK: { + location = BukkitUtil.getLocation(block.getLocation()); + //eventType = PlayerBlockEventType.BREAK_BLOCK; + blocktype1 = BukkitAdapter.asBlockType(block.getType()); + if (block.getType() == Material.DRAGON_EGG) { + eventType = PlayerBlockEventType.TELEPORT_OBJECT; + break; + } + + return; + } + default: + return; + } + if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) { + if (event.getMaterial() == Material + .getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) { + return; + } + } + if (!PlotSquared.get().getEventDispatcher() + .checkPlayerBlockEvent(pp, eventType, location, blocktype1, true)) { + System.out.println("dd"); + event.setCancelled(true); + event.setUseInteractedBlock(Event.Result.DENY); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBucketEmpty(PlayerBucketEmptyEvent event) { + BlockFace bf = event.getBlockFace(); + Block block = + event.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()) + .getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + BukkitPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); + Plot plot = area.getPlot(location); + if (plot == null) { + if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { + return; + } + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_ROAD); + event.setCancelled(true); + } else if (!plot.hasOwner()) { + if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { + return; + } + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_UNOWNED); + event.setCancelled(true); + } else if (!plot.isAdded(pp.getUUID())) { + List use = plot.getFlag(UseFlag.class); + final BlockType blockType = BukkitAdapter.asBlockType(block.getType()); + for (final BlockTypeWrapper blockTypeWrapper : use) { + if (blockTypeWrapper.accepts(blockType)) { + return; + } + } + if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + return; + } + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onInventoryClose(InventoryCloseEvent event) { + HumanEntity closer = event.getPlayer(); + if (!(closer instanceof Player)) { + return; + } + Player player = (Player) closer; + PlotInventory.removePlotInventoryOpen(BukkitUtil.getPlayer(player)); + } + + @EventHandler(priority = EventPriority.MONITOR) public void onLeave(PlayerQuitEvent event) { + TaskManager.TELEPORT_QUEUE.remove(event.getPlayer().getName()); + BukkitPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); + pp.unregister(); + PlotListener.logout(pp.getUUID()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBucketFill(PlayerBucketFillEvent event) { + Block blockClicked = event.getBlockClicked(); + Location location = BukkitUtil.getLocation(blockClicked.getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Player player = event.getPlayer(); + BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + Plot plot = area.getPlot(location); + if (plot == null) { + if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { + return; + } + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_ROAD); + event.setCancelled(true); + } else if (!plot.hasOwner()) { + if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { + return; + } + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_UNOWNED); + event.setCancelled(true); + } else if (!plot.isAdded(plotPlayer.getUUID())) { + List use = plot.getFlag(UseFlag.class); + Block block = event.getBlockClicked(); + final BlockType blockType = BukkitAdapter.asBlockType(block.getType()); + for (final BlockTypeWrapper blockTypeWrapper : use) { + if (blockTypeWrapper.accepts(blockType)) { + return; + } + } + if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + return; + } + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { + if (!Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onHangingPlace(HangingPlaceEvent event) { + Block block = event.getBlock().getRelative(event.getBlockFace()); + Location location = BukkitUtil.getLocation(block.getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Player p = event.getPlayer(); + if (p == null) { + PlotSquared.debug("PlotSquared does not support HangingPlaceEvent for non-players."); + event.setCancelled(true); + return; + } + BukkitPlayer pp = BukkitUtil.getPlayer(p); + Plot plot = area.getPlot(location); + if (plot == null) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_ROAD); + event.setCancelled(true); + } + } else { + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_UNOWNED); + event.setCancelled(true); + } + return; + } + if (!plot.isAdded(pp.getUUID())) { + if (!plot.getFlag(HangingPlaceFlag.class)) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); + event.setCancelled(true); + } + return; + } + } + if (BukkitEntityUtil.checkEntity(event.getEntity(), plot)) { + event.setCancelled(true); + } + + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onHangingBreakByEntity(HangingBreakByEntityEvent event) { + Entity remover = event.getRemover(); + if (remover instanceof Player) { + Player p = (Player) remover; + Location location = BukkitUtil.getLocation(event.getEntity()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + BukkitPlayer pp = BukkitUtil.getPlayer(p); + Plot plot = area.getPlot(location); + if (plot == null) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_ROAD); + event.setCancelled(true); + } + } else if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_UNOWNED); + event.setCancelled(true); + } + } else if (!plot.isAdded(pp.getUUID())) { + if (plot.getFlag(HangingBreakFlag.class)) { + return; + } + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_OTHER); + event.setCancelled(true); + plot.debug(p.getName() + + " could not break hanging entity because hanging-break = false"); + } + } + } else if (remover instanceof Projectile) { + Projectile p = (Projectile) remover; + if (p.getShooter() instanceof Player) { + Player shooter = (Player) p.getShooter(); + Location location = BukkitUtil.getLocation(event.getEntity()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + BukkitPlayer player = BukkitUtil.getPlayer(shooter); + Plot plot = area.getPlot(BukkitUtil.getLocation(event.getEntity())); + if (plot != null) { + if (!plot.hasOwner()) { + if (!Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_UNOWNED); + event.setCancelled(true); + } + } else if (!plot.isAdded(player.getUUID())) { + if (!plot.getFlag(HangingBreakFlag.class)) { + if (!Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_OTHER); + event.setCancelled(true); + plot.debug(player.getName() + + " could not break hanging entity because hanging-break = false"); + } + } + } + } + } + } else { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { + Location location = BukkitUtil.getLocation(event.getRightClicked().getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Player p = event.getPlayer(); + BukkitPlayer pp = BukkitUtil.getPlayer(p); + Plot plot = area.getPlot(location); + if (plot == null && !area.isRoadFlags()) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_ROAD)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_INTERACT_ROAD); + event.setCancelled(true); + } + } else if (plot != null && !plot.hasOwner()) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_INTERACT_UNOWNED); + event.setCancelled(true); + } + } else if ((plot != null && !plot.isAdded(pp.getUUID())) || (plot == null && area + .isRoadFlags())) { + final Entity entity = event.getRightClicked(); + final com.sk89q.worldedit.world.entity.EntityType entityType = + BukkitAdapter.adapt(entity.getType()); + + FlagContainer flagContainer; + if (plot == null) { + flagContainer = area.getRoadFlagContainer(); + } else { + flagContainer = plot.getFlagContainer(); + } + + if (EntityCategories.HOSTILE.contains(entityType) && flagContainer + .getFlag(HostileInteractFlag.class).getValue()) { + return; + } + + if (EntityCategories.ANIMAL.contains(entityType) && flagContainer + .getFlag(AnimalInteractFlag.class).getValue()) { + return; + } + + // This actually makes use of the interface, so we don't use the + // category + if (entity instanceof Tameable && ((Tameable) entity).isTamed() && flagContainer + .getFlag(TamedInteractFlag.class).getValue()) { + return; + } + + if (EntityCategories.VEHICLE.contains(entityType) && flagContainer + .getFlag(VehicleUseFlag.class).getValue()) { + return; + } + + if (EntityCategories.PLAYER.contains(entityType) && flagContainer + .getFlag(PlayerInteractFlag.class).getValue()) { + return; + } + + if (EntityCategories.VILLAGER.contains(entityType) && flagContainer + .getFlag(VillagerInteractFlag.class).getValue()) { + return; + } + + if ((EntityCategories.HANGING.contains(entityType) || EntityCategories.OTHER + .contains(entityType)) && flagContainer.getFlag(MiscInteractFlag.class) + .getValue()) { + return; + } + + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_INTERACT_OTHER); + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onVehicleDestroy(VehicleDestroyEvent event) { + Location location = BukkitUtil.getLocation(event.getVehicle()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Entity attacker = event.getAttacker(); + if (attacker instanceof Player) { + Player p = (Player) attacker; + BukkitPlayer pp = BukkitUtil.getPlayer(p); + Plot plot = area.getPlot(location); + if (plot == null) { + if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.road")) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + "plots.admin.vehicle.break.road"); + event.setCancelled(true); + } + } else { + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.unowned")) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + "plots.admin.vehicle.break.unowned"); + event.setCancelled(true); + return; + } + return; + } + if (!plot.isAdded(pp.getUUID())) { + if (plot.getFlag(VehicleBreakFlag.class)) { + return; + } + if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.other")) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + "plots.admin.vehicle.break.other"); + event.setCancelled(true); + plot.debug(pp.getName() + + " could not break vehicle because vehicle-break = false"); + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerEggThrow(PlayerEggThrowEvent event) { + Location location = BukkitUtil.getLocation(event.getEgg().getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Player player = event.getPlayer(); + BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + Plot plot = area.getPlot(location); + if (plot == null) { + if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.road")) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.projectile.road"); + event.setHatching(false); + } + } else if (!plot.hasOwner()) { + if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.unowned")) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.projectile.unowned"); + event.setHatching(false); + } + } else if (!plot.isAdded(plotPlayer.getUUID())) { + if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.other")) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.projectile.other"); + event.setHatching(false); + } + } + } + + @EventHandler public void onItemDrop(PlayerDropItemEvent event) { + Player player = event.getPlayer(); + BukkitPlayer pp = BukkitUtil.getPlayer(player); + Location location = pp.getLocation(); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = location.getOwnedPlot(); + if (plot == null) { + if (area.isRoadFlags() && !area.getRoadFlag(ItemDropFlag.class)) { + event.setCancelled(true); + } + return; + } + UUID uuid = pp.getUUID(); + if (!plot.isAdded(uuid)) { + if (!plot.getFlag(ItemDropFlag.class)) { + plot.debug(player.getName() + " could not drop item because of item-drop = false"); + event.setCancelled(true); + } + } + } + + @EventHandler public void onItemPickup(EntityPickupItemEvent event) { + LivingEntity ent = event.getEntity(); + if (ent instanceof Player) { + Player player = (Player) ent; + BukkitPlayer pp = BukkitUtil.getPlayer(player); + Location location = pp.getLocation(); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = location.getOwnedPlot(); + if (plot == null) { + if (area.isRoadFlags() && area.getRoadFlag(DropProtectionFlag.class)) { + event.setCancelled(true); + } + return; + } + UUID uuid = pp.getUUID(); + if (!plot.isAdded(uuid) && plot.getFlag(DropProtectionFlag.class)) { + plot.debug( + player.getName() + " could not pick up item because of drop-protection = true"); + event.setCancelled(true); + } + } + } + + @EventHandler public void onDeath(final PlayerDeathEvent event) { + Location location = BukkitUtil.getLocation(event.getEntity()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = location.getOwnedPlot(); + if (plot == null) { + if (area.isRoadFlags() && area.getRoadFlag(KeepInventoryFlag.class)) { + event.setCancelled(true); + } + return; + } + if (plot.getFlag(KeepInventoryFlag.class)) { + if (plot.getFlag(KeepInventoryFlag.class)) { + plot.debug(event.getEntity().getName() + + " kept their inventory because of keep-inventory = true"); + event.setKeepInventory(true); + } + } + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java deleted file mode 100644 index a9cb82336..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEvents.java +++ /dev/null @@ -1,3221 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2020 IntellectualSites - * - * 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, see . - */ -package com.plotsquared.bukkit.listener; - -import com.destroystokyo.paper.MaterialTags; -import com.google.common.base.Charsets; -import com.plotsquared.bukkit.player.BukkitPlayer; -import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.bukkit.util.UpdateUtility; -import com.plotsquared.core.PlotSquared; -import com.plotsquared.core.configuration.Captions; -import com.plotsquared.core.configuration.Settings; -import com.plotsquared.core.database.DBFunc; -import com.plotsquared.core.listener.PlayerBlockEventType; -import com.plotsquared.core.listener.PlotListener; -import com.plotsquared.core.location.Location; -import com.plotsquared.core.player.PlotPlayer; -import com.plotsquared.core.plot.Plot; -import com.plotsquared.core.plot.PlotArea; -import com.plotsquared.core.plot.PlotHandler; -import com.plotsquared.core.plot.PlotId; -import com.plotsquared.core.plot.PlotInventory; -import com.plotsquared.core.plot.flag.FlagContainer; -import com.plotsquared.core.plot.flag.implementations.AnimalAttackFlag; -import com.plotsquared.core.plot.flag.implementations.AnimalCapFlag; -import com.plotsquared.core.plot.flag.implementations.AnimalInteractFlag; -import com.plotsquared.core.plot.flag.implementations.BlockBurnFlag; -import com.plotsquared.core.plot.flag.implementations.BlockIgnitionFlag; -import com.plotsquared.core.plot.flag.implementations.BlockedCmdsFlag; -import com.plotsquared.core.plot.flag.implementations.BreakFlag; -import com.plotsquared.core.plot.flag.implementations.ChatFlag; -import com.plotsquared.core.plot.flag.implementations.CoralDryFlag; -import com.plotsquared.core.plot.flag.implementations.DenyTeleportFlag; -import com.plotsquared.core.plot.flag.implementations.DisablePhysicsFlag; -import com.plotsquared.core.plot.flag.implementations.DoneFlag; -import com.plotsquared.core.plot.flag.implementations.DropProtectionFlag; -import com.plotsquared.core.plot.flag.implementations.EntityCapFlag; -import com.plotsquared.core.plot.flag.implementations.ExplosionFlag; -import com.plotsquared.core.plot.flag.implementations.GrassGrowFlag; -import com.plotsquared.core.plot.flag.implementations.HangingBreakFlag; -import com.plotsquared.core.plot.flag.implementations.HangingPlaceFlag; -import com.plotsquared.core.plot.flag.implementations.HostileAttackFlag; -import com.plotsquared.core.plot.flag.implementations.HostileCapFlag; -import com.plotsquared.core.plot.flag.implementations.HostileInteractFlag; -import com.plotsquared.core.plot.flag.implementations.IceFormFlag; -import com.plotsquared.core.plot.flag.implementations.IceMeltFlag; -import com.plotsquared.core.plot.flag.implementations.InstabreakFlag; -import com.plotsquared.core.plot.flag.implementations.InvincibleFlag; -import com.plotsquared.core.plot.flag.implementations.ItemDropFlag; -import com.plotsquared.core.plot.flag.implementations.KeepInventoryFlag; -import com.plotsquared.core.plot.flag.implementations.KelpGrowFlag; -import com.plotsquared.core.plot.flag.implementations.LiquidFlowFlag; -import com.plotsquared.core.plot.flag.implementations.MiscBreakFlag; -import com.plotsquared.core.plot.flag.implementations.MiscCapFlag; -import com.plotsquared.core.plot.flag.implementations.MiscInteractFlag; -import com.plotsquared.core.plot.flag.implementations.MobCapFlag; -import com.plotsquared.core.plot.flag.implementations.MobPlaceFlag; -import com.plotsquared.core.plot.flag.implementations.MycelGrowFlag; -import com.plotsquared.core.plot.flag.implementations.PlaceFlag; -import com.plotsquared.core.plot.flag.implementations.PlayerInteractFlag; -import com.plotsquared.core.plot.flag.implementations.PreventCreativeCopyFlag; -import com.plotsquared.core.plot.flag.implementations.PveFlag; -import com.plotsquared.core.plot.flag.implementations.PvpFlag; -import com.plotsquared.core.plot.flag.implementations.RedstoneFlag; -import com.plotsquared.core.plot.flag.implementations.SnowFormFlag; -import com.plotsquared.core.plot.flag.implementations.SnowMeltFlag; -import com.plotsquared.core.plot.flag.implementations.SoilDryFlag; -import com.plotsquared.core.plot.flag.implementations.TamedAttackFlag; -import com.plotsquared.core.plot.flag.implementations.TamedInteractFlag; -import com.plotsquared.core.plot.flag.implementations.UntrustedVisitFlag; -import com.plotsquared.core.plot.flag.implementations.UseFlag; -import com.plotsquared.core.plot.flag.implementations.VehicleBreakFlag; -import com.plotsquared.core.plot.flag.implementations.VehicleCapFlag; -import com.plotsquared.core.plot.flag.implementations.VehicleUseFlag; -import com.plotsquared.core.plot.flag.implementations.VillagerInteractFlag; -import com.plotsquared.core.plot.flag.implementations.VineGrowFlag; -import com.plotsquared.core.plot.flag.types.BlockTypeWrapper; -import com.plotsquared.core.plot.message.PlotMessage; -import com.plotsquared.core.util.EntityUtil; -import com.plotsquared.core.util.MainUtil; -import com.plotsquared.core.util.MathMan; -import com.plotsquared.core.util.Permissions; -import com.plotsquared.core.util.PremiumVerification; -import com.plotsquared.core.util.RegExUtil; -import com.plotsquared.core.util.entity.EntityCategories; -import com.plotsquared.core.util.task.TaskManager; -import com.sk89q.worldedit.bukkit.BukkitAdapter; -import com.sk89q.worldedit.world.block.BlockType; -import io.papermc.lib.PaperLib; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.FluidCollisionMode; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.command.PluginCommand; -import org.bukkit.entity.Ageable; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Creature; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.FallingBlock; -import org.bukkit.entity.Fireball; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.entity.TNTPrimed; -import org.bukkit.entity.Tameable; -import org.bukkit.entity.ThrownPotion; -import org.bukkit.entity.Vehicle; -import org.bukkit.event.Event; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockBurnEvent; -import org.bukkit.event.block.BlockDamageEvent; -import org.bukkit.event.block.BlockDispenseEvent; -import org.bukkit.event.block.BlockExplodeEvent; -import org.bukkit.event.block.BlockFadeEvent; -import org.bukkit.event.block.BlockFormEvent; -import org.bukkit.event.block.BlockFromToEvent; -import org.bukkit.event.block.BlockGrowEvent; -import org.bukkit.event.block.BlockIgniteEvent; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.block.BlockPistonRetractEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.block.BlockSpreadEvent; -import org.bukkit.event.block.EntityBlockFormEvent; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityCombustByEntityEvent; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.entity.EntityPickupItemEvent; -import org.bukkit.event.entity.ExplosionPrimeEvent; -import org.bukkit.event.entity.LingeringPotionSplashEvent; -import org.bukkit.event.entity.PlayerDeathEvent; -import org.bukkit.event.entity.PotionSplashEvent; -import org.bukkit.event.entity.ProjectileHitEvent; -import org.bukkit.event.entity.ProjectileLaunchEvent; -import org.bukkit.event.hanging.HangingBreakByEntityEvent; -import org.bukkit.event.hanging.HangingPlaceEvent; -import org.bukkit.event.inventory.ClickType; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.AsyncPlayerPreLoginEvent; -import org.bukkit.event.player.PlayerBucketEmptyEvent; -import org.bukkit.event.player.PlayerBucketFillEvent; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.player.PlayerDropItemEvent; -import org.bukkit.event.player.PlayerEggThrowEvent; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.event.player.PlayerInteractAtEntityEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.vehicle.VehicleCreateEvent; -import org.bukkit.event.vehicle.VehicleDestroyEvent; -import org.bukkit.event.vehicle.VehicleEntityCollisionEvent; -import org.bukkit.event.vehicle.VehicleMoveEvent; -import org.bukkit.event.world.StructureGrowEvent; -import org.bukkit.help.HelpTopic; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.material.Directional; -import org.bukkit.metadata.FixedMetadataValue; -import org.bukkit.metadata.MetadataValue; -import org.bukkit.plugin.Plugin; -import org.bukkit.projectiles.BlockProjectileSource; -import org.bukkit.projectiles.ProjectileSource; -import org.bukkit.util.Vector; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.regex.Pattern; - -/** - * Player Events involving plots. - */ -@SuppressWarnings("unused") -public class PlayerEvents extends PlotListener implements Listener { - - public static final com.sk89q.worldedit.world.entity.EntityType FAKE_ENTITY_TYPE = - new com.sk89q.worldedit.world.entity.EntityType("plotsquared:fake"); - - private float lastRadius; - // To prevent recursion - private boolean tmpTeleport = true; - private Field fieldPlayer; - private PlayerMoveEvent moveTmp; - private String internalVersion; - - { - try { - fieldPlayer = PlayerEvent.class.getDeclaredField("player"); - fieldPlayer.setAccessible(true); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } - } - - public static void sendBlockChange(final org.bukkit.Location bloc, final BlockData data) { - TaskManager.runTaskLater(() -> { - String world = bloc.getWorld().getName(); - int x = bloc.getBlockX(); - int z = bloc.getBlockZ(); - int distance = Bukkit.getViewDistance() * 16; - - for (final PlotPlayer player : PlotSquared.imp().getPlayerManager().getPlayers()) { - Location location = player.getLocation(); - if (location.getWorld().equals(world)) { - if (16 * Math.abs(location.getX() - x) / 16 > distance - || 16 * Math.abs(location.getZ() - z) / 16 > distance) { - continue; - } - ((BukkitPlayer) player).player.sendBlockChange(bloc, data); - } - } - }, 3); - } - - public static boolean checkEntity(Entity entity, Plot plot) { - if (plot == null || !plot.hasOwner() || plot.getFlags().isEmpty() && plot.getArea() - .getFlagContainer().getFlagMap().isEmpty()) { - return false; - } - - final com.sk89q.worldedit.world.entity.EntityType entityType = - BukkitAdapter.adapt(entity.getType()); - - if (EntityCategories.PLAYER.contains(entityType)) { - return false; - } - - if (EntityCategories.PROJECTILE.contains(entityType) || EntityCategories.OTHER - .contains(entityType) || EntityCategories.HANGING.contains(entityType)) { - return EntityUtil.checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED, - MiscCapFlag.MISC_CAP_UNLIMITED); - } - - // Has to go go before vehicle as horses are both - // animals and vehicles - if (EntityCategories.ANIMAL.contains(entityType) || EntityCategories.VILLAGER - .contains(entityType) || EntityCategories.TAMEABLE.contains(entityType)) { - return EntityUtil - .checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED, MobCapFlag.MOB_CAP_UNLIMITED, - AnimalCapFlag.ANIMAL_CAP_UNLIMITED); - } - - if (EntityCategories.HOSTILE.contains(entityType)) { - return EntityUtil - .checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED, MobCapFlag.MOB_CAP_UNLIMITED, - HostileCapFlag.HOSTILE_CAP_UNLIMITED); - } - - if (EntityCategories.VEHICLE.contains(entityType)) { - return EntityUtil.checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED, - VehicleCapFlag.VEHICLE_CAP_UNLIMITED); - } - - return EntityUtil.checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED); - } - - @EventHandler public void onVehicleEntityCollision(VehicleEntityCollisionEvent e) { - if (e.getVehicle().getType() == EntityType.BOAT) { - Location location = BukkitUtil.getLocation(e.getEntity()); - if (location.isPlotArea()) { - if (e.getEntity() instanceof Player) { - PlotPlayer player = BukkitUtil.getPlayer((Player) e.getEntity()); - Plot plot = player.getCurrentPlot(); - if (plot != null) { - if (!plot.isAdded(player.getUUID())) { - //Here the event is only canceled if the player is not the owner - //of the property on which he is located. - e.setCancelled(true); - } - } else { - e.setCancelled(true); - } - } else { - //Here the event is cancelled too, otherwise you can move the - //boat with EchoPets or other mobs running around on the plot. - e.setCancelled(true); - } - } - } - } - - @EventHandler public void onRedstoneEvent(BlockRedstoneEvent event) { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = location.getOwnedPlot(); - if (plot == null) { - if (area.isRoadFlags() && area.getRoadFlag(RedstoneFlag.class)) { - event.setNewCurrent(0); - } - return; - } - if (!plot.getFlag(RedstoneFlag.class)) { - event.setNewCurrent(0); - plot.debug("Redstone event was cancelled because redstone = false"); - return; - } - if (Settings.Redstone.DISABLE_OFFLINE) { - boolean disable = false; - if (!plot.getOwner().equals(DBFunc.SERVER)) { - if (plot.isMerged()) { - disable = true; - for (UUID owner : plot.getOwners()) { - if (PlotSquared.imp().getPlayerManager().getPlayerIfExists(owner) != null) { - disable = false; - break; - } - } - } else { - disable = - PlotSquared.imp().getPlayerManager().getPlayerIfExists(plot.getOwnerAbs()) - == null; - } - } - if (disable) { - for (UUID trusted : plot.getTrusted()) { - if (PlotSquared.imp().getPlayerManager().getPlayerIfExists(trusted) != null) { - disable = false; - break; - } - } - if (disable) { - event.setNewCurrent(0); - plot.debug( - "Redstone event was cancelled because no trusted player was in the plot"); - return; - } - } - } - if (Settings.Redstone.DISABLE_UNOCCUPIED) { - for (final PlotPlayer player : PlotSquared.imp().getPlayerManager().getPlayers()) { - if (plot.equals(player.getCurrentPlot())) { - return; - } - } - event.setNewCurrent(0); - } - } - - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void onPhysicsEvent(BlockPhysicsEvent event) { - switch (event.getChangedType()) { - case COMPARATOR: { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - if (location.isPlotArea()) { - return; - } - Plot plot = location.getOwnedPlotAbs(); - if (plot == null) { - return; - } - if (!plot.getFlag(RedstoneFlag.class)) { - event.setCancelled(true); - plot.debug("Prevented comparator update because redstone = false"); - } - return; - } - case ANVIL: - case DRAGON_EGG: - case GRAVEL: - case SAND: - case TURTLE_EGG: - case TURTLE_HELMET: - case TURTLE_SPAWN_EGG: { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlotAbs(location); - if (plot == null) { - return; - } - if (plot.getFlag(DisablePhysicsFlag.class)) { - event.setCancelled(true); - plot.debug("Prevented block physics because disable-physics = true"); - } - return; - } - default: - if (Settings.Redstone.DETECT_INVALID_EDGE_PISTONS) { - Block block = event.getBlock(); - switch (block.getType()) { - case PISTON: - case STICKY_PISTON: - org.bukkit.block.data.Directional piston = - (org.bukkit.block.data.Directional) block.getBlockData(); - Location location = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlotAbs(location); - if (plot == null) { - return; - } - switch (piston.getFacing()) { - case EAST: - location.setX(location.getX() + 1); - break; - case SOUTH: - location.setX(location.getX() - 1); - break; - case WEST: - location.setZ(location.getZ() + 1); - break; - case NORTH: - location.setZ(location.getZ() - 1); - break; - } - Plot newPlot = area.getOwnedPlotAbs(location); - if (!plot.equals(newPlot)) { - event.setCancelled(true); - plot.debug( - "Prevented piston update because of invalid edge piston detection"); - return; - } - } - } - break; - } - } - - @EventHandler public void onProjectileLaunch(ProjectileLaunchEvent event) { - Projectile entity = event.getEntity(); - if (!(entity instanceof ThrownPotion)) { - return; - } - ProjectileSource shooter = entity.getShooter(); - if (!(shooter instanceof Player)) { - return; - } - Location location = BukkitUtil.getLocation(entity); - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { - return; - } - PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); - Plot plot = location.getOwnedPlot(); - if (plot != null && !plot.isAdded(pp.getUUID())) { - entity.remove(); - event.setCancelled(true); - } - } - - @EventHandler public boolean onProjectileHit(ProjectileHitEvent event) { - Projectile entity = event.getEntity(); - Location location = BukkitUtil.getLocation(entity); - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { - return true; - } - PlotArea area = location.getPlotArea(); - if (area == null) { - return true; - } - Plot plot = area.getPlot(location); - ProjectileSource shooter = entity.getShooter(); - if (shooter instanceof Player) { - PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); - if (plot == null) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_PROJECTILE_UNOWNED)) { - entity.remove(); - return false; - } - return true; - } - if (plot.isAdded(pp.getUUID()) || Permissions - .hasPermission(pp, Captions.PERMISSION_PROJECTILE_OTHER)) { - return true; - } - entity.remove(); - return false; - } - if (!(shooter instanceof Entity) && shooter != null) { - if (plot == null) { - entity.remove(); - return false; - } - Location sLoc = - BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); - if (!area.contains(sLoc.getX(), sLoc.getZ())) { - entity.remove(); - return false; - } - Plot sPlot = area.getOwnedPlotAbs(sLoc); - if (sPlot == null || !PlotHandler.sameOwners(plot, sPlot)) { - entity.remove(); - return false; - } - } - return true; - } - - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void playerCommand(PlayerCommandPreprocessEvent event) { - String msg = event.getMessage().toLowerCase().replaceAll("/", "").trim(); - if (msg.isEmpty()) { - return; - } - Player player = event.getPlayer(); - PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); - Location location = plotPlayer.getLocation(); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - String[] parts = msg.split(" "); - Plot plot = plotPlayer.getCurrentPlot(); - // Check WorldEdit - switch (parts[0].toLowerCase()) { - case "up": - case "/up": - case "worldedit:up": - case "worldedit:/up": - if (plot == null || (!plot.isAdded(plotPlayer.getUUID()) && !Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER, true))) { - event.setCancelled(true); - return; - } - } - if (plot == null && !area.isRoadFlags()) { - return; - } - - List blockedCommands = plot != null ? - plot.getFlag(BlockedCmdsFlag.class) : - area.getFlag(BlockedCmdsFlag.class); - if (!blockedCommands.isEmpty() && !Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { - String part = parts[0]; - if (parts[0].contains(":")) { - part = parts[0].split(":")[1]; - msg = msg.replace(parts[0].split(":")[0] + ':', ""); - } - String s1 = part; - List aliases = new ArrayList<>(); - for (HelpTopic cmdLabel : Bukkit.getServer().getHelpMap().getHelpTopics()) { - if (part.equals(cmdLabel.getName())) { - break; - } - String label = cmdLabel.getName().replaceFirst("/", ""); - if (aliases.contains(label)) { - continue; - } - PluginCommand p; - if ((p = Bukkit.getPluginCommand(label)) != null) { - for (String a : p.getAliases()) { - if (aliases.contains(a)) { - continue; - } - aliases.add(a); - a = a.replaceFirst("/", ""); - if (!a.equals(label) && a.equals(part)) { - part = label; - break; - } - } - } - } - if (!s1.equals(part)) { - msg = msg.replace(s1, part); - } - for (String s : blockedCommands) { - Pattern pattern; - if (!RegExUtil.compiledPatterns.containsKey(s)) { - RegExUtil.compiledPatterns.put(s, pattern = Pattern.compile(s)); - } else { - pattern = RegExUtil.compiledPatterns.get(s); - } - if (pattern.matcher(msg).matches()) { - String perm; - if (plot != null && plot.isAdded(plotPlayer.getUUID())) { - perm = "plots.admin.command.blocked-cmds.shared"; - } else { - perm = "plots.admin.command.blocked-cmds.road"; - } - if (!Permissions.hasPermission(plotPlayer, perm)) { - MainUtil.sendMessage(plotPlayer, Captions.COMMAND_BLOCKED); - event.setCancelled(true); - } - return; - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPreLoin(final AsyncPlayerPreLoginEvent event) { - final UUID uuid; - if (Settings.UUID.OFFLINE) { - if (Settings.UUID.FORCE_LOWERCASE) { - uuid = UUID.nameUUIDFromBytes( - ("OfflinePlayer:" + event.getName().toLowerCase()).getBytes(Charsets.UTF_8)); - } else { - uuid = UUID.nameUUIDFromBytes( - ("OfflinePlayer:" + event.getName()).getBytes(Charsets.UTF_8)); - } - } else { - uuid = event.getUniqueId(); - } - PlotSquared.get().getImpromptuUUIDPipeline().storeImmediately(event.getName(), uuid); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onConnect(PlayerJoinEvent event) { - final Player player = event.getPlayer(); - BukkitUtil.removePlayer(player.getUniqueId()); - final PlotPlayer pp = BukkitUtil.getPlayer(player); - - Location location = pp.getLocation(); - PlotArea area = location.getPlotArea(); - if (area != null) { - Plot plot = area.getPlot(location); - if (plot != null) { - plotEntry(pp, plot); - } - } - // Delayed - - // Async - TaskManager.runTaskLaterAsync(() -> { - if (!player.hasPlayedBefore() && player.isOnline()) { - player.saveData(); - } - PlotSquared.get().getEventDispatcher().doJoinTask(pp); - }, 20); - - if (pp.hasPermission(Captions.PERMISSION_ADMIN_UPDATE_NOTIFICATION.getTranslated()) - && Settings.Enabled_Components.UPDATE_NOTIFICATIONS && PremiumVerification.isPremium() - && UpdateUtility.hasUpdate) { - new PlotMessage("-----------------------------------").send(pp); - new PlotMessage(Captions.PREFIX + "There appears to be a PlotSquared update available!") - .color("$1").send(pp); - new PlotMessage( - Captions.PREFIX + "&6You are running version " + UpdateUtility.internalVersion - .versionString() + ", &6latest version is " + UpdateUtility.spigotVersion) - .color("$1").send(pp); - new PlotMessage(Captions.PREFIX + "Download at:").color("$1").send(pp); - player.sendMessage(" https://www.spigotmc.org/resources/77506/updates"); - new PlotMessage("-----------------------------------").send(pp); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void playerRespawn(PlayerRespawnEvent event) { - Player player = event.getPlayer(); - PlotPlayer pp = BukkitUtil.getPlayer(player); - PlotSquared.get().getEventDispatcher().doRespawnTask(pp); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); - Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); - org.bukkit.Location to = event.getTo(); - //noinspection ConstantConditions - if (to != null) { - Location location = BukkitUtil.getLocation(to); - PlotArea area = location.getPlotArea(); - if (area == null) { - if (lastPlot != null) { - plotExit(pp, lastPlot); - pp.deleteMeta(PlotPlayer.META_LAST_PLOT); - } - pp.deleteMeta(PlotPlayer.META_LOCATION); - return; - } - Plot plot = area.getPlot(location); - if (plot != null) { - final boolean result = DenyTeleportFlag.allowsTeleport(pp, plot); - // there is one possibility to still allow teleportation: - // to is identical to the plot's home location, and untrusted-visit is true - // i.e. untrusted-visit can override deny-teleport - // this is acceptable, because otherwise it wouldn't make sense to have both flags set - if (!result && !(plot.getFlag(UntrustedVisitFlag.class) && plot.getHomeSynchronous() - .equals(BukkitUtil.getLocationFull(to)))) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_ENTRY_DENIED); - event.setCancelled(true); - } - } - } - playerMove(event); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException { - final org.bukkit.Location from = event.getFrom(); - final org.bukkit.Location to = event.getTo(); - - int toX, toZ; - if ((toX = MathMan.roundInt(to.getX())) != MathMan.roundInt(from.getX()) - | (toZ = MathMan.roundInt(to.getZ())) != MathMan.roundInt(from.getZ())) { - Vehicle vehicle = event.getVehicle(); - - // Check allowed - if (!vehicle.getPassengers().isEmpty()) { - Entity passenger = vehicle.getPassengers().get(0); - - if (passenger instanceof Player) { - final Player player = (Player) passenger; - // reset - if (moveTmp == null) { - moveTmp = new PlayerMoveEvent(null, from, to); - } - moveTmp.setFrom(from); - moveTmp.setTo(to); - moveTmp.setCancelled(false); - fieldPlayer.set(moveTmp, player); - - List passengers = vehicle.getPassengers(); - - this.playerMove(moveTmp); - org.bukkit.Location dest; - if (moveTmp.isCancelled()) { - dest = from; - } else if (MathMan.roundInt(moveTmp.getTo().getX()) != toX - || MathMan.roundInt(moveTmp.getTo().getZ()) != toZ) { - dest = to; - } else { - dest = null; - } - if (dest != null) { - vehicle.eject(); - vehicle.setVelocity(new Vector(0d, 0d, 0d)); - PaperLib.teleportAsync(vehicle, dest); - passengers.forEach(vehicle::addPassenger); - return; - } - } - if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { - final com.sk89q.worldedit.world.entity.EntityType entityType = - BukkitAdapter.adapt(vehicle.getType()); - // Horses etc are vehicles, but they're also animals - // so this filters out all living entities - if (EntityCategories.VEHICLE.contains(entityType) && !EntityCategories.ANIMAL - .contains(entityType)) { - List meta = vehicle.getMetadata("plot"); - Plot toPlot = BukkitUtil.getLocation(to).getPlot(); - if (!meta.isEmpty()) { - Plot origin = (Plot) meta.get(0).value(); - if (origin != null && !origin.getBasePlot(false).equals(toPlot)) { - vehicle.remove(); - } - } else if (toPlot != null) { - vehicle.setMetadata("plot", - new FixedMetadataValue((Plugin) PlotSquared.get().IMP, toPlot)); - } - } - } - } - - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void playerMove(PlayerMoveEvent event) { - org.bukkit.Location from = event.getFrom(); - org.bukkit.Location to = event.getTo(); - int x2; - if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) { - Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); - // Cancel teleport - if (TaskManager.TELEPORT_QUEUE.remove(pp.getName())) { - MainUtil.sendMessage(pp, Captions.TELEPORT_FAILED); - } - // Set last location - Location location = BukkitUtil.getLocation(to); - pp.setMeta(PlotPlayer.META_LOCATION, location); - PlotArea area = location.getPlotArea(); - if (area == null) { - pp.deleteMeta(PlotPlayer.META_LAST_PLOT); - return; - } - Plot now = area.getPlot(location); - Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); - if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp - .getMeta("kick", false)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_EXIT_DENIED); - this.tmpTeleport = false; - if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { - player.teleport(from); - } else { - player.teleport(player.getWorld().getSpawnLocation()); - } - this.tmpTeleport = true; - event.setCancelled(true); - return; - } - } else if (now.equals(lastPlot)) { - ForceFieldListener.handleForcefield(player, pp, now); - } else if (!plotEntry(pp, now) && this.tmpTeleport) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_ENTRY_DENIED); - this.tmpTeleport = false; - to.setX(from.getBlockX()); - to.setY(from.getBlockY()); - to.setZ(from.getBlockZ()); - player.teleport(event.getTo()); - this.tmpTeleport = true; - return; - } - int border = area.getBorder(); - if (x2 > border && this.tmpTeleport) { - to.setX(border - 1); - this.tmpTeleport = false; - player.teleport(event.getTo()); - this.tmpTeleport = true; - MainUtil.sendMessage(pp, Captions.BORDER); - } - if (x2 < -border && this.tmpTeleport) { - to.setX(-border + 1); - this.tmpTeleport = false; - player.teleport(event.getTo()); - this.tmpTeleport = true; - MainUtil.sendMessage(pp, Captions.BORDER); - } - } - int z2; - if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) { - Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); - // Cancel teleport - if (TaskManager.TELEPORT_QUEUE.remove(pp.getName())) { - MainUtil.sendMessage(pp, Captions.TELEPORT_FAILED); - } - // Set last location - Location location = BukkitUtil.getLocation(to); - pp.setMeta(PlotPlayer.META_LOCATION, location); - PlotArea area = location.getPlotArea(); - if (area == null) { - pp.deleteMeta(PlotPlayer.META_LAST_PLOT); - return; - } - Plot now = area.getPlot(location); - Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); - if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp - .getMeta("kick", false)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_EXIT_DENIED); - this.tmpTeleport = false; - if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { - player.teleport(from); - } else { - player.teleport(player.getWorld().getSpawnLocation()); - } - this.tmpTeleport = true; - event.setCancelled(true); - return; - } - } else if (now.equals(lastPlot)) { - ForceFieldListener.handleForcefield(player, pp, now); - } else if (!plotEntry(pp, now) && this.tmpTeleport) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_ENTRY_DENIED); - this.tmpTeleport = false; - player.teleport(from); - to.setX(from.getBlockX()); - to.setY(from.getBlockY()); - to.setZ(from.getBlockZ()); - player.teleport(event.getTo()); - this.tmpTeleport = true; - return; - } - int border = area.getBorder(); - if (z2 > border && this.tmpTeleport) { - to.setZ(border - 1); - this.tmpTeleport = false; - player.teleport(event.getTo()); - this.tmpTeleport = true; - MainUtil.sendMessage(pp, Captions.BORDER); - } else if (z2 < -border && this.tmpTeleport) { - to.setZ(-border + 1); - this.tmpTeleport = false; - player.teleport(event.getTo()); - this.tmpTeleport = true; - MainUtil.sendMessage(pp, Captions.BORDER); - } - } - } - - @EventHandler(priority = EventPriority.LOW) public void onChat(AsyncPlayerChatEvent event) { - if (event.isCancelled()) { - return; - } - - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(event.getPlayer()); - Location location = plotPlayer.getLocation(); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getPlot(location); - if (plot == null) { - return; - } - if (!((plot.getFlag(ChatFlag.class) && area.isPlotChat() && plotPlayer.getAttribute("chat")) - || area.isForcingPlotChat())) { - return; - } - if (plot.isDenied(plotPlayer.getUUID()) && !Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_CHAT_BYPASS)) { - return; - } - event.setCancelled(true); - String message = event.getMessage(); - String format = Captions.PLOT_CHAT_FORMAT.getTranslated(); - String sender = event.getPlayer().getDisplayName(); - PlotId id = plot.getId(); - Set recipients = event.getRecipients(); - recipients.clear(); - Set spies = new HashSet<>(); - for (final PlotPlayer pp : PlotSquared.imp().getPlayerManager().getPlayers()) { - if (pp.getAttribute("chatspy")) { - spies.add(((BukkitPlayer) pp).player); - } else { - Plot current = pp.getCurrentPlot(); - if (current != null && current.getBasePlot(false).equals(plot)) { - recipients.add(((BukkitPlayer) pp).player); - } - } - } - String partial = ChatColor.translateAlternateColorCodes('&', - format.replace("%plot_id%", id.x + ";" + id.y).replace("%sender%", sender)); - if (plotPlayer.hasPermission("plots.chat.color")) { - message = Captions.color(message); - } - String full = partial.replace("%msg%", message); - for (Player receiver : recipients) { - receiver.sendMessage(full); - } - if (!spies.isEmpty()) { - String spyMessage = Captions.PLOT_CHAT_SPY_FORMAT.getTranslated() - .replace("%plot_id%", id.x + ";" + id.y).replace("%sender%", sender) - .replace("%msg%", message); - for (Player player : spies) { - player.sendMessage(spyMessage); - } - } - PlotSquared.debug(full); - } - - @EventHandler(priority = EventPriority.LOWEST) public void blockDestroy(BlockBreakEvent event) { - Player player = event.getPlayer(); - Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getPlot(location); - if (plot != null) { - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); - if (event.getBlock().getY() == 0) { - if (!Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL); - event.setCancelled(true); - return; - } - } else if ((location.getY() > area.getMaxBuildHeight() || location.getY() < area - .getMinBuildHeight()) && !Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_HEIGHT_LIMIT)) { - event.setCancelled(true); - MainUtil.sendMessage(plotPlayer, Captions.HEIGHT_LIMIT.getTranslated() - .replace("{limit}", String.valueOf(area.getMaxBuildHeight()))); - } - if (!plot.hasOwner()) { - if (!Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED, true)) { - event.setCancelled(true); - } - return; - } - if (!plot.isAdded(plotPlayer.getUUID())) { - List destroy = plot.getFlag(BreakFlag.class); - Block block = event.getBlock(); - final BlockType blockType = BukkitAdapter.asBlockType(block.getType()); - for (final BlockTypeWrapper blockTypeWrapper : destroy) { - if (blockTypeWrapper.accepts(blockType)) { - return; - } - } - if (Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { - return; - } - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_OTHER); - event.setCancelled(true); - } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { - if (!Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - return; - } - } - return; - } - BukkitPlayer pp = BukkitUtil.getPlayer(player); - if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { - return; - } - if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) { - if (player.getInventory().getItemInMainHand().getType() == Material - .getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) { - return; - } - } - MainUtil - .sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_ROAD); - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBigBoom(EntityExplodeEvent event) { - Location location = BukkitUtil.getLocation(event.getLocation()); - PlotArea area = location.getPlotArea(); - boolean plotArea = location.isPlotArea(); - if (!plotArea) { - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { - return; - } - return; - } - Plot plot = area.getOwnedPlot(location); - if (plot != null) { - if (plot.getFlag(ExplosionFlag.class)) { - List meta = event.getEntity().getMetadata("plot"); - Plot origin; - if (meta.isEmpty()) { - origin = plot; - } else { - origin = (Plot) meta.get(0).value(); - } - if (this.lastRadius != 0) { - List nearby = event.getEntity() - .getNearbyEntities(this.lastRadius, this.lastRadius, this.lastRadius); - for (Entity near : nearby) { - if (near instanceof TNTPrimed || near.getType() - .equals(EntityType.MINECART_TNT)) { - if (!near.hasMetadata("plot")) { - near.setMetadata("plot", - new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); - } - } - } - this.lastRadius = 0; - } - Iterator iterator = event.blockList().iterator(); - while (iterator.hasNext()) { - Block block = iterator.next(); - location = BukkitUtil.getLocation(block.getLocation()); - if (!area.contains(location.getX(), location.getZ()) || !origin - .equals(area.getOwnedPlot(location))) { - iterator.remove(); - } - } - return; - } else { - plot.debug("Explosion was cancelled because explosion = false"); - } - } - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onWorldChanged(PlayerChangedWorldEvent event) { - Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); - // Delete last location - Plot plot = (Plot) pp.deleteMeta(PlotPlayer.META_LAST_PLOT); - pp.deleteMeta(PlotPlayer.META_LOCATION); - if (plot != null) { - plotExit(pp, plot); - } - if (PlotSquared.get().worldedit != null) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_WORLDEDIT_BYPASS)) { - if (pp.getAttribute("worldedit")) { - pp.removeAttribute("worldedit"); - } - } - } - if (Settings.Enabled_Components.PERMISSION_CACHE) { - pp.deleteMeta("perm"); - } - Location location = pp.getLocation(); - PlotArea area = location.getPlotArea(); - if (location.isPlotArea()) { - plot = location.getPlot(); - if (plot != null) { - plotEntry(pp, plot); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPeskyMobsChangeTheWorldLikeWTFEvent(EntityChangeBlockEvent event) { - Entity e = event.getEntity(); - if (!(e instanceof FallingBlock)) { - Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); - PlotArea area = location.getPlotArea(); - if (area != null) { - Plot plot = area.getOwnedPlot(location); - if (plot != null && plot.getFlag(MobPlaceFlag.class)) { - plot.debug(e.getType() + " could not change block because mob-place = false"); - return; - } - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityBlockForm(EntityBlockFormEvent event) { - String world = event.getBlock().getWorld().getName(); - if (!PlotSquared.get().hasPlotArea(world)) { - return; - } - Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlot(location); - if (plot == null) { - event.setCancelled(true); - return; - } - Entity entity = event.getEntity(); - if (entity instanceof Player) { - Player player = (Player) entity; - if (!plot.hasOwner()) { - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); - if (plot.getFlag(IceFormFlag.class)) { - plot.debug("Ice could not be formed because ice-form = false"); - return; - } - event.setCancelled(true); - return; - } - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); - if (!plot.isAdded(plotPlayer.getUUID())) { - if (plot.getFlag(IceFormFlag.class)) { - plot.debug("Ice could not be formed because ice-form = false"); - return; - } - event.setCancelled(true); - return; - } - return; - } - if (!plot.getFlag(IceFormFlag.class)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockSpread(BlockSpreadEvent event) { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - if (location.isPlotRoad()) { - event.setCancelled(true); - return; - } - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlot(location); - if (plot == null) { - return; - } - switch (event.getSource().getType()) { - case GRASS_BLOCK: - if (!plot.getFlag(GrassGrowFlag.class)) { - plot.debug("Grass could not grow because grass-grow = false"); - event.setCancelled(true); - } - break; - case MYCELIUM: - if (!plot.getFlag(MycelGrowFlag.class)) { - plot.debug("Mycelium could not grow because mycel-grow = false"); - event.setCancelled(true); - } - break; - case VINE: - if (!plot.getFlag(VineGrowFlag.class)) { - plot.debug("Vine could not grow because vine-grow = false"); - event.setCancelled(true); - } - break; - case KELP: - if (!plot.getFlag(KelpGrowFlag.class)) { - plot.debug("Kelp could not grow because kelp-grow = false"); - event.setCancelled(true); - } - break; - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockForm(BlockFormEvent event) { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - if (location.isPlotRoad()) { - event.setCancelled(true); - return; - } - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlot(location); - if (plot == null) { - return; - } - switch (event.getNewState().getType()) { - case SNOW: - case SNOW_BLOCK: - if (!plot.getFlag(SnowFormFlag.class)) { - plot.debug("Snow could not form because snow-form = false"); - event.setCancelled(true); - } - return; - case ICE: - case FROSTED_ICE: - case PACKED_ICE: - if (!plot.getFlag(IceFormFlag.class)) { - plot.debug("Ice could not form because ice-form = false"); - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockDamage(BlockDamageEvent event) { - Player player = event.getPlayer(); - Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - if (player.getGameMode() != GameMode.SURVIVAL) { - return; - } - Plot plot = area.getPlot(location); - if (plot != null) { - if (plot.getFlag(InstabreakFlag.class)) { - Block block = event.getBlock(); - BlockBreakEvent call = new BlockBreakEvent(block, player); - Bukkit.getServer().getPluginManager().callEvent(call); - if (!call.isCancelled()) { - event.getBlock().breakNaturally(); - } - } - if (location.getY() == 0) { - event.setCancelled(true); - return; - } - if (!plot.hasOwner()) { - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); - if (Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - return; - } - event.setCancelled(true); - return; - } - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); - if (!plot.isAdded(plotPlayer.getUUID())) { - List destroy = plot.getFlag(BreakFlag.class); - Block block = event.getBlock(); - if (destroy - .contains(BlockTypeWrapper.get(BukkitAdapter.asBlockType(block.getType()))) - || Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { - return; - } - plot.debug(player.getName() + " could not break " + block.getType() - + " because it was not in the break flag"); - event.setCancelled(true); - return; - } - return; - } - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); - if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { - return; - } - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onFade(BlockFadeEvent event) { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlot(location); - if (plot == null) { - event.setCancelled(true); - return; - } - switch (block.getType()) { - case ICE: - if (!plot.getFlag(IceMeltFlag.class)) { - plot.debug("Ice could not melt because ice-melt = false"); - event.setCancelled(true); - } - break; - case SNOW: - if (!plot.getFlag(SnowMeltFlag.class)) { - plot.debug("Snow could not melt because snow-melt = false"); - event.setCancelled(true); - } - break; - case FARMLAND: - if (!plot.getFlag(SoilDryFlag.class)) { - plot.debug("Soil could not dry because soil-dry = false"); - event.setCancelled(true); - } - break; - case TUBE_CORAL_BLOCK: - case BRAIN_CORAL_BLOCK: - case BUBBLE_CORAL_BLOCK: - case FIRE_CORAL_BLOCK: - case HORN_CORAL_BLOCK: - case TUBE_CORAL: - case BRAIN_CORAL: - case BUBBLE_CORAL: - case FIRE_CORAL: - case HORN_CORAL: - case TUBE_CORAL_FAN: - case BRAIN_CORAL_FAN: - case BUBBLE_CORAL_FAN: - case FIRE_CORAL_FAN: - case HORN_CORAL_FAN: - case BRAIN_CORAL_WALL_FAN: - case BUBBLE_CORAL_WALL_FAN: - case FIRE_CORAL_WALL_FAN: - case HORN_CORAL_WALL_FAN: - case TUBE_CORAL_WALL_FAN: - if (!plot.getFlag(CoralDryFlag.class)) { - plot.debug("Coral could not dry because coral-dry = false"); - event.setCancelled(true); - } - break; - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onChange(BlockFromToEvent event) { - Block from = event.getBlock(); - - // Check liquid flow flag inside of origin plot too - final Location fLocation = BukkitUtil.getLocation(from.getLocation()); - final PlotArea fromArea = fLocation.getPlotArea(); - if (fromArea != null) { - final Plot plot = fromArea.getOwnedPlot(fLocation); - if (plot != null - && plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.DISABLED && event - .getBlock().isLiquid()) { - plot.debug("Liquid could now flow because liquid-flow = disabled"); - event.setCancelled(true); - return; - } - } - - Block to = event.getToBlock(); - Location tLocation = BukkitUtil.getLocation(to.getLocation()); - PlotArea area = tLocation.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlot(tLocation); - if (plot != null) { - if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects - .equals(plot, area.getOwnedPlot(fLocation))) { - event.setCancelled(true); - return; - } - if (plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.ENABLED && event - .getBlock().isLiquid()) { - return; - } - if (plot.getFlag(DisablePhysicsFlag.class)) { - plot.debug(event.getBlock().getType() - + " could not update because disable-physics = true"); - event.setCancelled(true); - return; - } - if (plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.DISABLED && event - .getBlock().isLiquid()) { - plot.debug("Liquid could not flow because liquid-flow = disabled"); - event.setCancelled(true); - } - } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects - .equals(null, area.getOwnedPlot(fLocation))) { - event.setCancelled(true); - } else if (event.getBlock().isLiquid()) { - final org.bukkit.Location location = event.getBlock().getLocation(); - - /* - X = block location - A-H = potential plot locations - - Z - ^ - | A B C - o D X E - | F G H - v - <-----O-----> x - */ - if (BukkitUtil.getPlot(location.clone().add(-1, 0, 1) /* A */) != null - || BukkitUtil.getPlot(location.clone().add(1, 0, 0) /* B */) != null - || BukkitUtil.getPlot(location.clone().add(1, 0, 1) /* C */) != null - || BukkitUtil.getPlot(location.clone().add(-1, 0, 0) /* D */) != null - || BukkitUtil.getPlot(location.clone().add(1, 0, 0) /* E */) != null - || BukkitUtil.getPlot(location.clone().add(-1, 0, -1) /* F */) != null - || BukkitUtil.getPlot(location.clone().add(0, 0, -1) /* G */) != null - || BukkitUtil.getPlot(location.clone().add(1, 0, 1) /* H */) != null) { - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onGrow(BlockGrowEvent event) { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - if (location.isUnownedPlotArea()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonExtend(BlockPistonExtendEvent event) { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - BlockFace face = event.getDirection(); - Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ()); - PlotArea area = location.getPlotArea(); - if (area == null) { - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { - return; - } - for (Block block1 : event.getBlocks()) { - Location bloc = BukkitUtil.getLocation(block1.getLocation()); - if (bloc.isPlotArea() || bloc - .add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()) - .isPlotArea()) { - event.setCancelled(true); - return; - } - } - if (location.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()) - .isPlotArea()) { - // Prevent pistons from extending if they are: bordering a plot - // area, facing inside plot area, and not pushing any blocks - event.setCancelled(true); - } - return; - } - Plot plot = area.getOwnedPlot(location); - if (plot == null) { - event.setCancelled(true); - return; - } - for (Block block1 : event.getBlocks()) { - Location bloc = BukkitUtil.getLocation(block1.getLocation()); - if (!area.contains(bloc.getX(), bloc.getZ()) || !area - .contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { - event.setCancelled(true); - return; - } - if (!plot.equals(area.getOwnedPlot(bloc)) || !plot.equals(area.getOwnedPlot( - bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { - event.setCancelled(true); - return; - } - } - if (!plot.equals(area.getOwnedPlot( - location.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { - // This branch is only necessary to prevent pistons from extending - // if they are: on a plot edge, facing outside the plot, and not - // pushing any blocks - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonRetract(BlockPistonRetractEvent event) { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - BlockFace face = event.getDirection(); - Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ()); - PlotArea area = location.getPlotArea(); - if (area == null) { - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { - return; - } - for (Block block1 : event.getBlocks()) { - Location bloc = BukkitUtil.getLocation(block1.getLocation()); - if (bloc.isPlotArea() || bloc - .add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()) - .isPlotArea()) { - event.setCancelled(true); - return; - } - } - return; - } - Plot plot = area.getOwnedPlot(location); - if (plot == null) { - event.setCancelled(true); - return; - } - for (Block block1 : event.getBlocks()) { - Location bloc = BukkitUtil.getLocation(block1.getLocation()); - if (!area.contains(bloc.getX(), bloc.getZ()) || !area - .contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { - event.setCancelled(true); - return; - } - if (!plot.equals(area.getOwnedPlot(bloc)) || !plot.equals(area.getOwnedPlot( - bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { - event.setCancelled(true); - return; - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockDispense(BlockDispenseEvent event) { - Material type = event.getItem().getType(); - switch (type) { - case SHULKER_BOX: - case WHITE_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - case LIME_SHULKER_BOX: - case PINK_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case RED_SHULKER_BOX: - case BLACK_SHULKER_BOX: - case CARVED_PUMPKIN: - case WITHER_SKELETON_SKULL: - case FLINT_AND_STEEL: - case BONE_MEAL: - case SHEARS: - case GLASS_BOTTLE: - case GLOWSTONE: - case COD_BUCKET: - case PUFFERFISH_BUCKET: - case SALMON_BUCKET: - case TROPICAL_FISH_BUCKET: - case BUCKET: - case WATER_BUCKET: - case LAVA_BUCKET: { - if (event.getBlock().getType() == Material.DROPPER) { - return; - } - BlockFace targetFace = - ((Directional) event.getBlock().getState().getData()).getFacing(); - Location location = - BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation()); - if (location.isPlotRoad()) { - event.setCancelled(true); - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onStructureGrow(StructureGrowEvent event) { - if (!PlotSquared.get().hasPlotArea(event.getWorld().getName())) { - return; - } - List blocks = event.getBlocks(); - if (blocks.isEmpty()) { - return; - } - Location location = BukkitUtil.getLocation(blocks.get(0).getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - for (int i = blocks.size() - 1; i >= 0; i--) { - location = BukkitUtil.getLocation(blocks.get(i).getLocation()); - if (location.isPlotArea()) { - blocks.remove(i); - } - } - return; - } else { - Plot origin = area.getOwnedPlot(location); - if (origin == null) { - event.setCancelled(true); - return; - } - for (int i = blocks.size() - 1; i >= 0; i--) { - location = BukkitUtil.getLocation(blocks.get(i).getLocation()); - if (!area.contains(location.getX(), location.getZ())) { - blocks.remove(i); - continue; - } - Plot plot = area.getOwnedPlot(location); - if (!Objects.equals(plot, origin)) { - event.getBlocks().remove(i); - } - } - } - Plot origin = area.getPlot(location); - if (origin == null) { - event.setCancelled(true); - return; - } - for (int i = blocks.size() - 1; i >= 0; i--) { - location = BukkitUtil.getLocation(blocks.get(i).getLocation()); - Plot plot = area.getOwnedPlot(location); - /* - * plot → the base plot of the merged area - * origin → the plot where the event gets called - */ - - // Are plot and origin different AND are both plots merged - if (!Objects.equals(plot, origin) && (!plot.isMerged() && !origin.isMerged())) { - event.getBlocks().remove(i); - } - } - } - - @SuppressWarnings("deprecation") - @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) || !PlotSquared.get() - .hasPlotArea(entity.getWorld().getName())) { - return; - } - - HumanEntity clicker = event.getWhoClicked(); - if (!(clicker instanceof Player)) { - return; - } - Player player = (Player) clicker; - BukkitPlayer pp = BukkitUtil.getPlayer(player); - final PlotInventory inventory = PlotInventory.getOpenPlotInventory(pp); - if (inventory != null && event.getRawSlot() == event.getSlot()) { - if (!inventory.onClick(event.getSlot())) { - event.setResult(Event.Result.DENY); - event.setCancelled(true); - inventory.close(); - } - } - PlayerInventory inv = player.getInventory(); - int slot = inv.getHeldItemSlot(); - if ((slot > 8) || !event.getEventName().equals("InventoryCreativeEvent")) { - return; - } - ItemStack current = inv.getItemInHand(); - ItemStack newItem = event.getCursor(); - ItemMeta newMeta = newItem.getItemMeta(); - ItemMeta oldMeta = newItem.getItemMeta(); - - if (event.getClick() == ClickType.CREATIVE) { - final Plot plot = pp.getCurrentPlot(); - if (plot != null) { - if (plot.getFlag(PreventCreativeCopyFlag.class) && !plot - .isAdded(player.getUniqueId()) && !Permissions - .hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_OTHER)) { - final ItemStack newStack = - new ItemStack(newItem.getType(), newItem.getAmount()); - event.setCursor(newStack); - plot.debug(player.getName() - + " could not creative-copy an item because prevent-creative-copy = true"); - } - } else { - PlotArea area = pp.getPlotAreaAbs(); - if (area != null && area.isRoadFlags() && area - .getRoadFlag(PreventCreativeCopyFlag.class)) { - final ItemStack newStack = - new ItemStack(newItem.getType(), newItem.getAmount()); - event.setCursor(newStack); - } - } - return; - } - - String newLore = ""; - if (newMeta != null) { - List lore = newMeta.getLore(); - if (lore != null) { - newLore = lore.toString(); - } - } - String oldLore = ""; - if (oldMeta != null) { - List lore = oldMeta.getLore(); - if (lore != null) { - oldLore = lore.toString(); - } - } - if (!"[(+NBT)]".equals(newLore) || (current.equals(newItem) && newLore.equals(oldLore))) { - switch (newItem.getType()) { - case LEGACY_BANNER: - case PLAYER_HEAD: - if (newMeta != null) { - break; - } - default: - return; - } - } - Block block = player.getTargetBlock(null, 7); - org.bukkit.block.BlockState state = block.getState(); - Material stateType = state.getType(); - Material itemType = newItem.getType(); - if (stateType != itemType) { - switch (stateType) { - case LEGACY_STANDING_BANNER: - case LEGACY_WALL_BANNER: - if (itemType == Material.LEGACY_BANNER) { - break; - } - case LEGACY_SKULL: - if (itemType == Material.LEGACY_SKULL_ITEM) { - break; - } - default: - return; - } - } - Location location = BukkitUtil.getLocation(state.getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getPlotAbs(location); - boolean cancelled = false; - if (plot == null) { - if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.road"); - cancelled = true; - } - } else if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { - MainUtil - .sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); - cancelled = true; - } - } else { - UUID uuid = pp.getUUID(); - if (!plot.isAdded(uuid)) { - if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.interact.other"); - cancelled = true; - } - } - } - if (cancelled) { - if ((current.getType() == newItem.getType()) && (current.getDurability() == newItem - .getDurability())) { - event.setCursor( - new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); - event.setCancelled(true); - return; - } - event.setCursor( - new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPotionSplash(LingeringPotionSplashEvent event) { - Projectile entity = event.getEntity(); - Location location = BukkitUtil.getLocation(entity); - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { - return; - } - if (!this.onProjectileHit(event)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onInteract(PlayerInteractAtEntityEvent e) { - Entity entity = e.getRightClicked(); - if (!(entity instanceof ArmorStand) && !(entity instanceof ItemFrame)) { - return; - } - Location location = BukkitUtil.getLocation(e.getRightClicked().getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - EntitySpawnListener.testNether(entity); - Plot plot = location.getPlotAbs(); - BukkitPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); - if (plot == null) { - if (!area.isRoadFlags() && !area.getRoadFlag(MiscInteractFlag.class) && !Permissions - .hasPermission(pp, "plots.admin.interact.road")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.road"); - e.setCancelled(true); - } - } else { - if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); - e.setCancelled(true); - return; - } - } - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.interact.unowned"); - e.setCancelled(true); - } - } else { - UUID uuid = pp.getUUID(); - if (plot.isAdded(uuid)) { - return; - } - if (plot.getFlag(MiscInteractFlag.class)) { - return; - } - if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.interact.other"); - e.setCancelled(true); - plot.debug(pp.getName() + " could not interact with " + entity.getType() - + " bcause misc-interact = false"); - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBigBoom(BlockExplodeEvent event) { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - String world = location.getWorld(); - if (!PlotSquared.get().hasPlotArea(world)) { - return; - } - PlotArea area = location.getPlotArea(); - if (area == null) { - Iterator iterator = event.blockList().iterator(); - while (iterator.hasNext()) { - location = BukkitUtil.getLocation(iterator.next().getLocation()); - if (location.isPlotArea()) { - iterator.remove(); - } - } - return; - } - Plot plot = area.getOwnedPlot(location); - if (plot == null || !plot.getFlag(ExplosionFlag.class)) { - event.setCancelled(true); - if (plot != null) { - plot.debug("Explosion was cancelled because explosion = false"); - } - } - event.blockList().removeIf( - blox -> !plot.equals(area.getOwnedPlot(BukkitUtil.getLocation(blox.getLocation())))); - } - - @EventHandler(priority = EventPriority.LOW) - public void onCancelledInteract(PlayerInteractEvent event) { - if (event.isCancelled() && event.getAction() == Action.RIGHT_CLICK_AIR) { - Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); - PlotArea area = pp.getPlotAreaAbs(); - if (area == null) { - return; - } - if (event.getAction() == Action.RIGHT_CLICK_AIR) { - Material item = event.getMaterial(); - if (item.toString().toLowerCase().endsWith("_egg")) { - event.setCancelled(true); - event.setUseItemInHand(Event.Result.DENY); - } - } - ItemStack hand = player.getInventory().getItemInMainHand(); - ItemStack offHand = player.getInventory().getItemInOffHand(); - Material type = hand.getType(); - Material offType = offHand.getType(); - if (type == Material.AIR) { - type = offType; - } - if (type.toString().toLowerCase().endsWith("_egg")) { - Block block = player.getTargetBlockExact(5, FluidCollisionMode.SOURCE_ONLY); - if (block != null && block.getType() != Material.AIR) { - Location location = BukkitUtil.getLocation(block.getLocation()); - if (!PlotSquared.get().getEventDispatcher() - .checkPlayerBlockEvent(pp, PlayerBlockEventType.SPAWN_MOB, location, null, - true)) { - event.setCancelled(true); - event.setUseItemInHand(Event.Result.DENY); - } - } - } - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onInteract(PlayerInteractEvent event) { - Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); - PlotArea area = pp.getPlotAreaAbs(); - if (area == null) { - return; - } - PlayerBlockEventType eventType = null; - BlockType blocktype1; - Block block = event.getClickedBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - Action action = event.getAction(); - outer: - switch (action) { - case PHYSICAL: { - eventType = PlayerBlockEventType.TRIGGER_PHYSICAL; - blocktype1 = BukkitAdapter.asBlockType(block.getType()); - break; - } - //todo rearrange the right click code. it is all over the place. - case RIGHT_CLICK_BLOCK: { - Material blockType = block.getType(); - eventType = PlayerBlockEventType.INTERACT_BLOCK; - blocktype1 = BukkitAdapter.asBlockType(block.getType()); - - if (blockType.isInteractable()) { - if (!player.isSneaking()) { - break; - } - ItemStack hand = player.getInventory().getItemInMainHand(); - ItemStack offHand = player.getInventory().getItemInOffHand(); - - // sneaking players interact with blocks if both hands are empty - if (hand.getType() == Material.AIR && offHand.getType() == Material.AIR) { - break; - } - } - - Material type = event.getMaterial(); - - // in the following, lb needs to have the material of the item in hand i.e. type - switch (type) { - case REDSTONE: - case STRING: - case PUMPKIN_SEEDS: - case MELON_SEEDS: - case COCOA_BEANS: - case WHEAT_SEEDS: - case BEETROOT_SEEDS: - case SWEET_BERRIES: - return; - default: - //eventType = PlayerBlockEventType.PLACE_BLOCK; - if (type.isBlock()) { - return; - } - } - if (PaperLib.isPaper()) { - if (MaterialTags.SPAWN_EGGS.isTagged(type) || Material.EGG.equals(type)) { - eventType = PlayerBlockEventType.SPAWN_MOB; - break outer; - } - } else { - if (type.toString().toLowerCase().endsWith("egg")) { - eventType = PlayerBlockEventType.SPAWN_MOB; - break outer; - } - } - if (type.isEdible()) { - //Allow all players to eat while also allowing the block place event ot be fired - return; - } - switch (type) { - case ACACIA_BOAT: - case BIRCH_BOAT: - case CHEST_MINECART: - case COMMAND_BLOCK_MINECART: - case DARK_OAK_BOAT: - case FURNACE_MINECART: - case HOPPER_MINECART: - case JUNGLE_BOAT: - case MINECART: - case OAK_BOAT: - case SPRUCE_BOAT: - case TNT_MINECART: - eventType = PlayerBlockEventType.PLACE_VEHICLE; - break outer; - case FIREWORK_ROCKET: - case FIREWORK_STAR: - eventType = PlayerBlockEventType.SPAWN_MOB; - break outer; - case BOOK: - case KNOWLEDGE_BOOK: - case WRITABLE_BOOK: - case WRITTEN_BOOK: - eventType = PlayerBlockEventType.READ; - break outer; - case ARMOR_STAND: - location = BukkitUtil - .getLocation(block.getRelative(event.getBlockFace()).getLocation()); - eventType = PlayerBlockEventType.PLACE_MISC; - break outer; - } - break; - } - case LEFT_CLICK_BLOCK: { - location = BukkitUtil.getLocation(block.getLocation()); - //eventType = PlayerBlockEventType.BREAK_BLOCK; - blocktype1 = BukkitAdapter.asBlockType(block.getType()); - if (block.getType() == Material.DRAGON_EGG) { - eventType = PlayerBlockEventType.TELEPORT_OBJECT; - break; - } - - return; - } - default: - return; - } - if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) { - if (event.getMaterial() == Material - .getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) { - return; - } - } - if (!PlotSquared.get().getEventDispatcher() - .checkPlayerBlockEvent(pp, eventType, location, blocktype1, true)) { - event.setCancelled(true); - event.setUseInteractedBlock(Event.Result.DENY); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void creatureSpawnEvent(CreatureSpawnEvent event) { - Entity entity = event.getEntity(); - Location location = BukkitUtil.getLocation(entity.getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - CreatureSpawnEvent.SpawnReason reason = event.getSpawnReason(); - switch (reason.toString()) { - case "DISPENSE_EGG": - case "EGG": - case "OCELOT_BABY": - case "SPAWNER_EGG": - if (!area.isSpawnEggs()) { - event.setCancelled(true); - return; - } - break; - case "REINFORCEMENTS": - case "NATURAL": - case "MOUNT": - case "PATROL": - case "RAID": - case "SHEARED": - case "SHOULDER_ENTITY": - case "SILVERFISH_BLOCK": - case "TRAP": - case "VILLAGE_DEFENSE": - case "VILLAGE_INVASION": - case "BEEHIVE": - case "CHUNK_GEN": - if (!area.isMobSpawning()) { - event.setCancelled(true); - return; - } - case "BREEDING": - if (!area.isSpawnBreeding()) { - event.setCancelled(true); - return; - } - break; - case "BUILD_IRONGOLEM": - case "BUILD_SNOWMAN": - case "BUILD_WITHER": - case "CUSTOM": - if (!area.isSpawnCustom() && entity.getType() != EntityType.ARMOR_STAND) { - event.setCancelled(true); - return; - } - break; - case "SPAWNER": - if (!area.isMobSpawnerSpawning()) { - event.setCancelled(true); - return; - } - break; - } - Plot plot = area.getOwnedPlotAbs(location); - if (plot == null) { - if (!area.isMobSpawning()) { - event.setCancelled(true); - } - return; - } - if (checkEntity(entity, plot)) { - event.setCancelled(true); - } - } - - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void onEntityFall(EntityChangeBlockEvent event) { - if (event.getEntityType() != EntityType.FALLING_BLOCK) { - return; - } - Block block = event.getBlock(); - World world = block.getWorld(); - String worldName = world.getName(); - if (!PlotSquared.get().hasPlotArea(worldName)) { - return; - } - Location location = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlotAbs(location); - if (plot == null || plot.getFlag(DisablePhysicsFlag.class)) { - event.setCancelled(true); - plot.debug("Falling block event was cancelled because disable-physics = true"); - return; - } - if (event.getTo().hasGravity()) { - Entity entity = event.getEntity(); - List meta = entity.getMetadata("plot"); - if (meta.isEmpty()) { - return; - } - Plot origin = (Plot) meta.get(0).value(); - if (origin != null && !origin.equals(plot)) { - event.setCancelled(true); - entity.remove(); - } - } else if (event.getTo() == Material.AIR) { - event.getEntity() - .setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); - } - } - - @EventHandler public void onPrime(ExplosionPrimeEvent event) { - this.lastRadius = event.getRadius() + 1; - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBurn(BlockBurnEvent event) { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - - Plot plot = location.getOwnedPlot(); - if (plot == null || !plot.getFlag(BlockBurnFlag.class)) { - if (plot != null) { - plot.debug("Block burning was cancelled because block-burn = false"); - } - event.setCancelled(true); - } - - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockIgnite(BlockIgniteEvent event) { - Player player = event.getPlayer(); - Entity ignitingEntity = event.getIgnitingEntity(); - Block block = event.getBlock(); - BlockIgniteEvent.IgniteCause igniteCause = event.getCause(); - Location location1 = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = location1.getPlotArea(); - if (area == null) { - return; - } - if (igniteCause == BlockIgniteEvent.IgniteCause.LIGHTNING) { - event.setCancelled(true); - return; - } - - Plot plot = area.getOwnedPlot(location1); - if (player != null) { - BukkitPlayer pp = BukkitUtil.getPlayer(player); - if (plot == null) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_ROAD); - event.setCancelled(true); - } - } else if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_UNOWNED); - event.setCancelled(true); - } - } else if (!plot.isAdded(pp.getUUID())) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - } - } else if (!plot.getFlag(BlockIgnitionFlag.class)) { - event.setCancelled(true); - } - } else { - if (plot == null) { - event.setCancelled(true); - return; - } - if (ignitingEntity != null) { - if (!plot.getFlag(BlockIgnitionFlag.class)) { - event.setCancelled(true); - plot.debug("Block ignition was cancelled because block-ignition = false"); - return; - } - if (igniteCause == BlockIgniteEvent.IgniteCause.FIREBALL) { - if (ignitingEntity instanceof Fireball) { - Projectile fireball = (Projectile) ignitingEntity; - Location location = null; - if (fireball.getShooter() instanceof Entity) { - Entity shooter = (Entity) fireball.getShooter(); - location = BukkitUtil.getLocation(shooter.getLocation()); - } else if (fireball.getShooter() instanceof BlockProjectileSource) { - Block shooter = - ((BlockProjectileSource) fireball.getShooter()).getBlock(); - location = BukkitUtil.getLocation(shooter.getLocation()); - } - if (location != null && !plot.equals(location.getPlot())) { - event.setCancelled(true); - } - } - } - - } else if (event.getIgnitingBlock() != null) { - Block ignitingBlock = event.getIgnitingBlock(); - Plot plotIgnited = BukkitUtil.getLocation(ignitingBlock.getLocation()).getPlot(); - if (igniteCause == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL && ( - !plot.getFlag(BlockIgnitionFlag.class) || plotIgnited == null || !plotIgnited - .equals(plot)) || (igniteCause == BlockIgniteEvent.IgniteCause.SPREAD - || igniteCause == BlockIgniteEvent.IgniteCause.LAVA) && ( - !plot.getFlag(BlockIgnitionFlag.class) || plotIgnited == null || !plotIgnited - .equals(plot))) { - event.setCancelled(true); - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBucketEmpty(PlayerBucketEmptyEvent event) { - BlockFace bf = event.getBlockFace(); - Block block = - event.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()) - .getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - BukkitPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); - Plot plot = area.getPlot(location); - if (plot == null) { - if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { - return; - } - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_ROAD); - event.setCancelled(true); - } else if (!plot.hasOwner()) { - if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { - return; - } - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_UNOWNED); - event.setCancelled(true); - } else if (!plot.isAdded(pp.getUUID())) { - List use = plot.getFlag(UseFlag.class); - final BlockType blockType = BukkitAdapter.asBlockType(block.getType()); - for (final BlockTypeWrapper blockTypeWrapper : use) { - if (blockTypeWrapper.accepts(blockType)) { - return; - } - } - if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - return; - } - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClose(InventoryCloseEvent event) { - HumanEntity closer = event.getPlayer(); - if (!(closer instanceof Player)) { - return; - } - Player player = (Player) closer; - PlotInventory.removePlotInventoryOpen(BukkitUtil.getPlayer(player)); - } - - @EventHandler(priority = EventPriority.MONITOR) public void onLeave(PlayerQuitEvent event) { - TaskManager.TELEPORT_QUEUE.remove(event.getPlayer().getName()); - BukkitPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); - pp.unregister(); - PlotListener.logout(pp.getUUID()); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBucketFill(PlayerBucketFillEvent event) { - Block blockClicked = event.getBlockClicked(); - Location location = BukkitUtil.getLocation(blockClicked.getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Player player = event.getPlayer(); - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); - Plot plot = area.getPlot(location); - if (plot == null) { - if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { - return; - } - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_ROAD); - event.setCancelled(true); - } else if (!plot.hasOwner()) { - if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { - return; - } - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_UNOWNED); - event.setCancelled(true); - } else if (!plot.isAdded(plotPlayer.getUUID())) { - List use = plot.getFlag(UseFlag.class); - Block block = event.getBlockClicked(); - final BlockType blockType = BukkitAdapter.asBlockType(block.getType()); - for (final BlockTypeWrapper blockTypeWrapper : use) { - if (blockTypeWrapper.accepts(blockType)) { - return; - } - } - if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - return; - } - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { - if (!Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onVehicleCreate(VehicleCreateEvent event) { - Vehicle entity = event.getVehicle(); - Location location = BukkitUtil.getLocation(entity); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlotAbs(location); - if (plot == null || checkEntity(entity, plot)) { - entity.remove(); - return; - } - if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { - entity - .setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onHangingPlace(HangingPlaceEvent event) { - Block block = event.getBlock().getRelative(event.getBlockFace()); - Location location = BukkitUtil.getLocation(block.getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Player p = event.getPlayer(); - if (p == null) { - PlotSquared.debug("PlotSquared does not support HangingPlaceEvent for non-players."); - event.setCancelled(true); - return; - } - BukkitPlayer pp = BukkitUtil.getPlayer(p); - Plot plot = area.getPlot(location); - if (plot == null) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_ROAD); - event.setCancelled(true); - } - } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_UNOWNED); - event.setCancelled(true); - } - return; - } - if (!plot.isAdded(pp.getUUID())) { - if (!plot.getFlag(HangingPlaceFlag.class)) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - } - return; - } - } - if (checkEntity(event.getEntity(), plot)) { - event.setCancelled(true); - } - - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onHangingBreakByEntity(HangingBreakByEntityEvent event) { - Entity remover = event.getRemover(); - if (remover instanceof Player) { - Player p = (Player) remover; - Location location = BukkitUtil.getLocation(event.getEntity()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - BukkitPlayer pp = BukkitUtil.getPlayer(p); - Plot plot = area.getPlot(location); - if (plot == null) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_ROAD); - event.setCancelled(true); - } - } else if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_UNOWNED); - event.setCancelled(true); - } - } else if (!plot.isAdded(pp.getUUID())) { - if (plot.getFlag(HangingBreakFlag.class)) { - return; - } - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_OTHER); - event.setCancelled(true); - plot.debug(p.getName() - + " could not break hanging entity because hanging-break = false"); - } - } - } else if (remover instanceof Projectile) { - Projectile p = (Projectile) remover; - if (p.getShooter() instanceof Player) { - Player shooter = (Player) p.getShooter(); - Location location = BukkitUtil.getLocation(event.getEntity()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - BukkitPlayer player = BukkitUtil.getPlayer(shooter); - Plot plot = area.getPlot(BukkitUtil.getLocation(event.getEntity())); - if (plot != null) { - if (!plot.hasOwner()) { - if (!Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_UNOWNED); - event.setCancelled(true); - } - } else if (!plot.isAdded(player.getUUID())) { - if (!plot.getFlag(HangingBreakFlag.class)) { - if (!Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_OTHER); - event.setCancelled(true); - plot.debug(player.getName() - + " could not break hanging entity because hanging-break = false"); - } - } - } - } - } - } else { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { - Location location = BukkitUtil.getLocation(event.getRightClicked().getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Player p = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(p); - Plot plot = area.getPlot(location); - if (plot == null && !area.isRoadFlags()) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_ROAD)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_INTERACT_ROAD); - event.setCancelled(true); - } - } else if (plot != null && !plot.hasOwner()) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_INTERACT_UNOWNED); - event.setCancelled(true); - } - } else if ((plot != null && !plot.isAdded(pp.getUUID())) || (plot == null && area - .isRoadFlags())) { - final Entity entity = event.getRightClicked(); - final com.sk89q.worldedit.world.entity.EntityType entityType = - BukkitAdapter.adapt(entity.getType()); - - FlagContainer flagContainer; - if (plot == null) { - flagContainer = area.getRoadFlagContainer(); - } else { - flagContainer = plot.getFlagContainer(); - } - - if (EntityCategories.HOSTILE.contains(entityType) && flagContainer - .getFlag(HostileInteractFlag.class).getValue()) { - return; - } - - if (EntityCategories.ANIMAL.contains(entityType) && flagContainer - .getFlag(AnimalInteractFlag.class).getValue()) { - return; - } - - // This actually makes use of the interface, so we don't use the - // category - if (entity instanceof Tameable && ((Tameable) entity).isTamed() && flagContainer - .getFlag(TamedInteractFlag.class).getValue()) { - return; - } - - if (EntityCategories.VEHICLE.contains(entityType) && flagContainer - .getFlag(VehicleUseFlag.class).getValue()) { - return; - } - - if (EntityCategories.PLAYER.contains(entityType) && flagContainer - .getFlag(PlayerInteractFlag.class).getValue()) { - return; - } - - if (EntityCategories.VILLAGER.contains(entityType) && flagContainer - .getFlag(VillagerInteractFlag.class).getValue()) { - return; - } - - if ((EntityCategories.HANGING.contains(entityType) || EntityCategories.OTHER - .contains(entityType)) && flagContainer.getFlag(MiscInteractFlag.class) - .getValue()) { - return; - } - - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_INTERACT_OTHER); - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onVehicleDestroy(VehicleDestroyEvent event) { - Location location = BukkitUtil.getLocation(event.getVehicle()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Entity attacker = event.getAttacker(); - if (attacker instanceof Player) { - Player p = (Player) attacker; - BukkitPlayer pp = BukkitUtil.getPlayer(p); - Plot plot = area.getPlot(location); - if (plot == null) { - if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.road")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.vehicle.break.road"); - event.setCancelled(true); - } - } else { - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.unowned")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.vehicle.break.unowned"); - event.setCancelled(true); - return; - } - return; - } - if (!plot.isAdded(pp.getUUID())) { - if (plot.getFlag(VehicleBreakFlag.class)) { - return; - } - if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.other")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.vehicle.break.other"); - event.setCancelled(true); - plot.debug(pp.getName() - + " could not break vehicle because vehicle-break = false"); - } - } - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPotionSplash(PotionSplashEvent event) { - ThrownPotion damager = event.getPotion(); - Location location = BukkitUtil.getLocation(damager); - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { - return; - } - int count = 0; - for (LivingEntity victim : event.getAffectedEntities()) { - if (!entityDamage(damager, victim)) { - event.setIntensity(victim, 0); - count++; - } - } - if ((count > 0 && count == event.getAffectedEntities().size()) || !onProjectileHit(event)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { - EntityDamageByEntityEvent eventChange = - new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), - EntityDamageEvent.DamageCause.FIRE_TICK, event.getDuration()); - onEntityDamageByEntityEvent(eventChange); - if (eventChange.isCancelled()) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { - Entity damager = event.getDamager(); - Location location = BukkitUtil.getLocation(damager); - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { - return; - } - Entity victim = event.getEntity(); -/* - if (victim.getType().equals(EntityType.ITEM_FRAME)) { - Plot plot = BukkitUtil.getLocation(victim).getPlot(); - if (plot != null && !plot.isAdded(damager.getUniqueId())) { - event.setCancelled(true); - return; - } - } -*/ - if (!entityDamage(damager, victim, event.getCause())) { - if (event.isCancelled()) { - if (victim instanceof Ageable) { - Ageable ageable = (Ageable) victim; - if (ageable.getAge() == -24000) { - ageable.setAge(0); - ageable.setAdult(); - } - } - } - event.setCancelled(true); - } - } - - private boolean entityDamage(Entity damager, Entity victim) { - return entityDamage(damager, victim, null); - } - - private boolean entityDamage(Entity damager, Entity victim, - EntityDamageEvent.DamageCause cause) { - Location dloc = BukkitUtil.getLocation(damager); - Location vloc = BukkitUtil.getLocation(victim); - PlotArea dArea = dloc.getPlotArea(); - PlotArea vArea; - if (dArea != null && dArea.contains(vloc.getX(), vloc.getZ())) { - vArea = dArea; - } else { - vArea = vloc.getPlotArea(); - } - if (dArea == null && vArea == null) { - return true; - } - - Plot dplot; - if (dArea != null) { - dplot = dArea.getPlot(dloc); - } else { - dplot = null; - } - Plot vplot; - if (vArea != null) { - vplot = vArea.getPlot(vloc); - } else { - vplot = null; - } - - Plot plot; - String stub; - boolean isPlot = true; - if (dplot == null && vplot == null) { - if (dArea == null) { - return true; - } - plot = null; - stub = "road"; - isPlot = false; - } else { - // Prioritize plots for close to seamless pvp zones - if (victim.getTicksLived() > damager.getTicksLived()) { - if (dplot == null || !(victim instanceof Player)) { - if (vplot == null) { - plot = dplot; - } else { - plot = vplot; - } - } else { - plot = dplot; - } - } else if (dplot == null || !(victim instanceof Player)) { - if (vplot == null) { - plot = dplot; - } else { - plot = vplot; - } - } else if (vplot == null) { - plot = dplot; - } else { - plot = vplot; - } - if (plot.hasOwner()) { - stub = "other"; - } else { - stub = "unowned"; - } - } - boolean roadFlags = vArea != null ? vArea.isRoadFlags() : dArea.isRoadFlags(); - PlotArea area = vArea != null ? vArea : dArea; - - Player player; - if (damager instanceof Player) { // attacker is player - player = (Player) damager; - } else if (damager instanceof Projectile) { - Projectile projectile = (Projectile) damager; - ProjectileSource shooter = projectile.getShooter(); - if (shooter instanceof Player) { // shooter is player - player = (Player) shooter; - } else { // shooter is not player - if (shooter instanceof BlockProjectileSource) { - Location sLoc = BukkitUtil - .getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); - dplot = dArea.getPlot(sLoc); - } - player = null; - } - } else { // Attacker is not player - player = null; - } - if (player != null) { - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); - - final com.sk89q.worldedit.world.entity.EntityType entityType; - - // Create a fake entity type if the type does not have a name - if (victim.getType().getName() == null) { - entityType = FAKE_ENTITY_TYPE; - } else { - entityType = BukkitAdapter.adapt(victim.getType()); - } - - if (EntityCategories.HANGING.contains(entityType)) { // hanging - if (plot != null && (plot.getFlag(HangingBreakFlag.class) || plot - .isAdded(plotPlayer.getUUID()))) { - if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { - if (!Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); - return false; - } - } - return true; - } - if (!Permissions.hasPermission(plotPlayer, "plots.admin.destroy." + stub)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.destroy." + stub); - return false; - } - } else if (victim.getType() == EntityType.ARMOR_STAND) { - if (plot != null && (plot.getFlag(MiscBreakFlag.class) || plot - .isAdded(plotPlayer.getUUID()))) { - return true; - } - if (!Permissions.hasPermission(plotPlayer, "plots.admin.destroy." + stub)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.destroy." + stub); - if (plot != null) { - plot.debug(player.getName() - + " could not break armor stand because misc-break = false"); - } - return false; - } - } else if (EntityCategories.HOSTILE.contains(entityType)) { - if (isPlot) { - if (plot.getFlag(HostileAttackFlag.class) || plot.getFlag(PveFlag.class) || plot - .isAdded(plotPlayer.getUUID())) { - return true; - } - } else if (roadFlags && (area.getRoadFlag(HostileAttackFlag.class) || area - .getFlag(PveFlag.class))) { - return true; - } - if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.pve." + stub); - if (plot != null) { - plot.debug(player.getName() + " could not attack " + entityType - + " because pve = false OR hostile-attack = false"); - } - return false; - } - } else if (EntityCategories.TAMEABLE.contains(entityType)) { // victim is tameable - if (isPlot) { - if (plot.getFlag(TamedAttackFlag.class) || plot.getFlag(PveFlag.class) || plot - .isAdded(plotPlayer.getUUID())) { - return true; - } - } else if (roadFlags && (area.getRoadFlag(TamedAttackFlag.class) || area - .getFlag(PveFlag.class))) { - return true; - } - if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.pve." + stub); - if (plot != null) { - plot.debug(player.getName() + " could not attack " + entityType - + " because pve = false OR tamned-attack = false"); - } - return false; - } - } else if (EntityCategories.PLAYER.contains(entityType)) { - if (isPlot) { - if (!plot.getFlag(PvpFlag.class) && !Permissions - .hasPermission(plotPlayer, "plots.admin.pvp." + stub)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.pvp." + stub); - plot.debug(player.getName() + " could not attack " + entityType - + " because pve = false"); - return false; - } else { - return true; - } - } else if (roadFlags && area.getRoadFlag(PvpFlag.class)) { - return true; - } - if (!Permissions.hasPermission(plotPlayer, "plots.admin.pvp." + stub)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.pvp." + stub); - return false; - } - } else if (EntityCategories.ANIMAL.contains(entityType)) { // victim is animal - if (isPlot) { - if (plot.getFlag(AnimalAttackFlag.class) || plot.getFlag(PveFlag.class) || plot - .isAdded(plotPlayer.getUUID())) { - plot.debug(player.getName() + " could not attack " + entityType - + " because pve = false OR animal-attack = false"); - return true; - } - } else if (roadFlags && (area.getRoadFlag(AnimalAttackFlag.class) || area - .getFlag(PveFlag.class))) { - if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.pve." + stub); - return false; - } - } - } else if (EntityCategories.VEHICLE - .contains(entityType)) { // Vehicles are managed in vehicle destroy event - return true; - } else { // victim is something else - if (isPlot) { - if (plot.getFlag(PveFlag.class) || plot.isAdded(plotPlayer.getUUID())) { - return true; - } - } else if (roadFlags && area.getRoadFlag(PveFlag.class)) { - return true; - } - if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.pve." + stub); - if (plot != null) { - plot.debug(player.getName() + " could not attack " + entityType - + " because pve = false"); - } - return false; - } - } - return true; - } else if (dplot != null && (!dplot.equals(vplot) || Objects - .equals(dplot.getOwnerAbs(), vplot.getOwnerAbs()))) { - return vplot != null && vplot.getFlag(PveFlag.class); - } - //disable the firework damage. too much of a headache to support at the moment. - if (vplot != null) { - if (EntityDamageEvent.DamageCause.ENTITY_EXPLOSION == cause - && damager.getType() == EntityType.FIREWORK) { - return false; - } - } - if (vplot == null && roadFlags && area.getRoadFlag(PveFlag.class)) { - return true; - } - return ((vplot != null && vplot.getFlag(PveFlag.class)) || !(damager instanceof Arrow - && !(victim instanceof Creature))); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerEggThrow(PlayerEggThrowEvent event) { - Location location = BukkitUtil.getLocation(event.getEgg().getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Player player = event.getPlayer(); - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); - Plot plot = area.getPlot(location); - if (plot == null) { - if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.road")) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.projectile.road"); - event.setHatching(false); - } - } else if (!plot.hasOwner()) { - if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.unowned")) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.projectile.unowned"); - event.setHatching(false); - } - } else if (!plot.isAdded(plotPlayer.getUUID())) { - if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.other")) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.projectile.other"); - event.setHatching(false); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void blockCreate(BlockPlaceEvent event) { - Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); - Plot plot = area.getPlot(location); - if (plot != null) { - if ((location.getY() > area.getMaxBuildHeight() || location.getY() < area - .getMinBuildHeight()) && !Permissions - .hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_HEIGHT_LIMIT)) { - event.setCancelled(true); - MainUtil.sendMessage(pp, Captions.HEIGHT_LIMIT.getTranslated() - .replace("{limit}", String.valueOf(area.getMaxBuildHeight()))); - } - if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_UNOWNED); - event.setCancelled(true); - return; - } - } else if (!plot.isAdded(pp.getUUID())) { - List place = plot.getFlag(PlaceFlag.class); - if (place != null) { - Block block = event.getBlock(); - if (place.contains( - BlockTypeWrapper.get(BukkitAdapter.asBlockType(block.getType())))) { - return; - } - } - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - plot.debug(player.getName() + " could not place " + event.getBlock().getType() - + " because of the place flag"); - return; - } - } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { - if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); - event.setCancelled(true); - return; - } - } - if (plot.getFlag(DisablePhysicsFlag.class)) { - Block block = event.getBlockPlaced(); - if (block.getType().hasGravity()) { - sendBlockChange(block.getLocation(), block.getBlockData()); - plot.debug(event.getBlock().getType() - + " did not fall because of disable-physics = true"); - } - } - } else if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_ROAD); - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) public void onDamage(EntityDamageEvent event) { - if (event.getEntityType() != EntityType.PLAYER) { - return; - } - Location location = BukkitUtil.getLocation(event.getEntity()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = location.getOwnedPlot(); - if (plot == null) { - if (area.isRoadFlags() && area.getRoadFlag(InvincibleFlag.class)) { - event.setCancelled(true); - } - return; - } - if (plot.getFlag(InvincibleFlag.class)) { - plot.debug( - event.getEntity().getName() + " could not take damage because invincible = true"); - event.setCancelled(true); - } - } - - @EventHandler public void onItemDrop(PlayerDropItemEvent event) { - Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); - Location location = pp.getLocation(); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = location.getOwnedPlot(); - if (plot == null) { - if (area.isRoadFlags() && !area.getRoadFlag(ItemDropFlag.class)) { - event.setCancelled(true); - } - return; - } - UUID uuid = pp.getUUID(); - if (!plot.isAdded(uuid)) { - if (!plot.getFlag(ItemDropFlag.class)) { - plot.debug(player.getName() + " could not drop item because of item-drop = false"); - event.setCancelled(true); - } - } - } - - @EventHandler public void onItemPickup(EntityPickupItemEvent event) { - LivingEntity ent = event.getEntity(); - if (ent instanceof Player) { - Player player = (Player) ent; - BukkitPlayer pp = BukkitUtil.getPlayer(player); - Location location = pp.getLocation(); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = location.getOwnedPlot(); - if (plot == null) { - if (area.isRoadFlags() && area.getRoadFlag(DropProtectionFlag.class)) { - event.setCancelled(true); - } - return; - } - UUID uuid = pp.getUUID(); - if (!plot.isAdded(uuid) && plot.getFlag(DropProtectionFlag.class)) { - plot.debug( - player.getName() + " could not pick up item because of drop-protection = true"); - event.setCancelled(true); - } - } - } - - @EventHandler public void onDeath(final PlayerDeathEvent event) { - Location location = BukkitUtil.getLocation(event.getEntity()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = location.getOwnedPlot(); - if (plot == null) { - if (area.isRoadFlags() && area.getRoadFlag(KeepInventoryFlag.class)) { - event.setCancelled(true); - } - return; - } - if (plot.getFlag(KeepInventoryFlag.class)) { - if (plot.getFlag(KeepInventoryFlag.class)) { - plot.debug(event.getEntity().getName() - + " kept their inventory because of keep-inventory = true"); - event.setKeepInventory(true); - } - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ProjectileEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ProjectileEventListener.java new file mode 100644 index 000000000..a4cfd6171 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ProjectileEventListener.java @@ -0,0 +1,156 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.bukkit.listener; + +import com.plotsquared.bukkit.util.BukkitEntityUtil; +import com.plotsquared.bukkit.util.BukkitUtil; +import com.plotsquared.core.PlotSquared; +import com.plotsquared.core.configuration.Captions; +import com.plotsquared.core.location.Location; +import com.plotsquared.core.player.PlotPlayer; +import com.plotsquared.core.plot.Plot; +import com.plotsquared.core.plot.PlotArea; +import com.plotsquared.core.plot.PlotHandler; +import com.plotsquared.core.util.Permissions; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.ThrownPotion; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.LingeringPotionSplashEvent; +import org.bukkit.event.entity.PotionSplashEvent; +import org.bukkit.event.entity.ProjectileHitEvent; +import org.bukkit.event.entity.ProjectileLaunchEvent; +import org.bukkit.projectiles.BlockProjectileSource; +import org.bukkit.projectiles.ProjectileSource; + +@SuppressWarnings("unused") +public class ProjectileEventListener implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPotionSplash(LingeringPotionSplashEvent event) { + Projectile entity = event.getEntity(); + Location location = BukkitUtil.getLocation(entity); + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + return; + } + if (!this.onProjectileHit(event)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPotionSplash(PotionSplashEvent event) { + ThrownPotion damager = event.getPotion(); + Location location = BukkitUtil.getLocation(damager); + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + return; + } + int count = 0; + for (LivingEntity victim : event.getAffectedEntities()) { + if (!BukkitEntityUtil.entityDamage(damager, victim)) { + event.setIntensity(victim, 0); + count++; + } + } + if ((count > 0 && count == event.getAffectedEntities().size()) || !onProjectileHit(event)) { + event.setCancelled(true); + } + } + + @EventHandler public void onProjectileLaunch(ProjectileLaunchEvent event) { + Projectile entity = event.getEntity(); + if (!(entity instanceof ThrownPotion)) { + return; + } + ProjectileSource shooter = entity.getShooter(); + if (!(shooter instanceof Player)) { + return; + } + Location location = BukkitUtil.getLocation(entity); + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + return; + } + PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); + Plot plot = location.getOwnedPlot(); + if (plot != null && !plot.isAdded(pp.getUUID())) { + entity.remove(); + event.setCancelled(true); + } + } + + @SuppressWarnings({"BooleanMethodIsAlwaysInverted", "cos it's not... dum IntelliJ"}) @EventHandler + public boolean onProjectileHit(ProjectileHitEvent event) { + Projectile entity = event.getEntity(); + Location location = BukkitUtil.getLocation(entity); + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + return true; + } + PlotArea area = location.getPlotArea(); + if (area == null) { + return true; + } + Plot plot = area.getPlot(location); + ProjectileSource shooter = entity.getShooter(); + if (shooter instanceof Player) { + PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); + if (plot == null) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_PROJECTILE_UNOWNED)) { + entity.remove(); + return false; + } + return true; + } + if (plot.isAdded(pp.getUUID()) || Permissions + .hasPermission(pp, Captions.PERMISSION_PROJECTILE_OTHER)) { + return true; + } + entity.remove(); + return false; + } + if (!(shooter instanceof Entity) && shooter != null) { + if (plot == null) { + entity.remove(); + return false; + } + Location sLoc = + BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); + if (!area.contains(sLoc.getX(), sLoc.getZ())) { + entity.remove(); + return false; + } + Plot sPlot = area.getOwnedPlotAbs(sLoc); + if (sPlot == null || !PlotHandler.sameOwners(plot, sPlot)) { + entity.remove(); + return false; + } + } + return true; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java new file mode 100644 index 000000000..d5ef32ba3 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java @@ -0,0 +1,363 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.bukkit.util; + +import com.plotsquared.bukkit.player.BukkitPlayer; +import com.plotsquared.core.configuration.Captions; +import com.plotsquared.core.configuration.Settings; +import com.plotsquared.core.location.Location; +import com.plotsquared.core.plot.Plot; +import com.plotsquared.core.plot.PlotArea; +import com.plotsquared.core.plot.flag.implementations.AnimalAttackFlag; +import com.plotsquared.core.plot.flag.implementations.AnimalCapFlag; +import com.plotsquared.core.plot.flag.implementations.DoneFlag; +import com.plotsquared.core.plot.flag.implementations.EntityCapFlag; +import com.plotsquared.core.plot.flag.implementations.HangingBreakFlag; +import com.plotsquared.core.plot.flag.implementations.HostileAttackFlag; +import com.plotsquared.core.plot.flag.implementations.HostileCapFlag; +import com.plotsquared.core.plot.flag.implementations.MiscBreakFlag; +import com.plotsquared.core.plot.flag.implementations.MiscCapFlag; +import com.plotsquared.core.plot.flag.implementations.MobCapFlag; +import com.plotsquared.core.plot.flag.implementations.PveFlag; +import com.plotsquared.core.plot.flag.implementations.PvpFlag; +import com.plotsquared.core.plot.flag.implementations.TamedAttackFlag; +import com.plotsquared.core.plot.flag.implementations.VehicleCapFlag; +import com.plotsquared.core.util.EntityUtil; +import com.plotsquared.core.util.MainUtil; +import com.plotsquared.core.util.Permissions; +import com.plotsquared.core.util.entity.EntityCategories; +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Creature; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.projectiles.BlockProjectileSource; +import org.bukkit.projectiles.ProjectileSource; + +import java.util.Objects; + +public class BukkitEntityUtil { + + public static final com.sk89q.worldedit.world.entity.EntityType FAKE_ENTITY_TYPE = + new com.sk89q.worldedit.world.entity.EntityType("plotsquared:fake"); + + public static boolean entityDamage(Entity damager, Entity victim) { + return entityDamage(damager, victim, null); + } + + public static boolean entityDamage(Entity damager, Entity victim, + EntityDamageEvent.DamageCause cause) { + Location dloc = BukkitUtil.getLocation(damager); + Location vloc = BukkitUtil.getLocation(victim); + PlotArea dArea = dloc.getPlotArea(); + PlotArea vArea; + if (dArea != null && dArea.contains(vloc.getX(), vloc.getZ())) { + vArea = dArea; + } else { + vArea = vloc.getPlotArea(); + } + if (dArea == null && vArea == null) { + return true; + } + + Plot dplot; + if (dArea != null) { + dplot = dArea.getPlot(dloc); + } else { + dplot = null; + } + Plot vplot; + if (vArea != null) { + vplot = vArea.getPlot(vloc); + } else { + vplot = null; + } + + Plot plot; + String stub; + boolean isPlot = true; + if (dplot == null && vplot == null) { + if (dArea == null) { + return true; + } + plot = null; + stub = "road"; + isPlot = false; + } else { + // Prioritize plots for close to seamless pvp zones + if (victim.getTicksLived() > damager.getTicksLived()) { + if (dplot == null || !(victim instanceof Player)) { + if (vplot == null) { + plot = dplot; + } else { + plot = vplot; + } + } else { + plot = dplot; + } + } else if (dplot == null || !(victim instanceof Player)) { + if (vplot == null) { + plot = dplot; + } else { + plot = vplot; + } + } else if (vplot == null) { + plot = dplot; + } else { + plot = vplot; + } + if (plot.hasOwner()) { + stub = "other"; + } else { + stub = "unowned"; + } + } + boolean roadFlags = vArea != null ? vArea.isRoadFlags() : dArea.isRoadFlags(); + PlotArea area = vArea != null ? vArea : dArea; + + Player player; + if (damager instanceof Player) { // attacker is player + player = (Player) damager; + } else if (damager instanceof Projectile) { + Projectile projectile = (Projectile) damager; + ProjectileSource shooter = projectile.getShooter(); + if (shooter instanceof Player) { // shooter is player + player = (Player) shooter; + } else { // shooter is not player + if (shooter instanceof BlockProjectileSource) { + Location sLoc = BukkitUtil + .getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); + dplot = dArea.getPlot(sLoc); + } + player = null; + } + } else { // Attacker is not player + player = null; + } + if (player != null) { + BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + + final com.sk89q.worldedit.world.entity.EntityType entityType; + + // Create a fake entity type if the type does not have a name + if (victim.getType().getName() == null) { + entityType = FAKE_ENTITY_TYPE; + } else { + entityType = BukkitAdapter.adapt(victim.getType()); + } + + if (EntityCategories.HANGING.contains(entityType)) { // hanging + if (plot != null && (plot.getFlag(HangingBreakFlag.class) || plot + .isAdded(plotPlayer.getUUID()))) { + if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { + if (!Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); + return false; + } + } + return true; + } + if (!Permissions.hasPermission(plotPlayer, "plots.admin.destroy." + stub)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.destroy." + stub); + return false; + } + } else if (victim.getType() == EntityType.ARMOR_STAND) { + if (plot != null && (plot.getFlag(MiscBreakFlag.class) || plot + .isAdded(plotPlayer.getUUID()))) { + return true; + } + if (!Permissions.hasPermission(plotPlayer, "plots.admin.destroy." + stub)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.destroy." + stub); + if (plot != null) { + plot.debug(player.getName() + + " could not break armor stand because misc-break = false"); + } + return false; + } + } else if (EntityCategories.HOSTILE.contains(entityType)) { + if (isPlot) { + if (plot.getFlag(HostileAttackFlag.class) || plot.getFlag(PveFlag.class) || plot + .isAdded(plotPlayer.getUUID())) { + return true; + } + } else if (roadFlags && (area.getRoadFlag(HostileAttackFlag.class) || area + .getFlag(PveFlag.class))) { + return true; + } + if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.pve." + stub); + if (plot != null) { + plot.debug(player.getName() + " could not attack " + entityType + + " because pve = false OR hostile-attack = false"); + } + return false; + } + } else if (EntityCategories.TAMEABLE.contains(entityType)) { // victim is tameable + if (isPlot) { + if (plot.getFlag(TamedAttackFlag.class) || plot.getFlag(PveFlag.class) || plot + .isAdded(plotPlayer.getUUID())) { + return true; + } + } else if (roadFlags && (area.getRoadFlag(TamedAttackFlag.class) || area + .getFlag(PveFlag.class))) { + return true; + } + if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.pve." + stub); + if (plot != null) { + plot.debug(player.getName() + " could not attack " + entityType + + " because pve = false OR tamned-attack = false"); + } + return false; + } + } else if (EntityCategories.PLAYER.contains(entityType)) { + if (isPlot) { + if (!plot.getFlag(PvpFlag.class) && !Permissions + .hasPermission(plotPlayer, "plots.admin.pvp." + stub)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.pvp." + stub); + plot.debug(player.getName() + " could not attack " + entityType + + " because pve = false"); + return false; + } else { + return true; + } + } else if (roadFlags && area.getRoadFlag(PvpFlag.class)) { + return true; + } + if (!Permissions.hasPermission(plotPlayer, "plots.admin.pvp." + stub)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.pvp." + stub); + return false; + } + } else if (EntityCategories.ANIMAL.contains(entityType)) { // victim is animal + if (isPlot) { + if (plot.getFlag(AnimalAttackFlag.class) || plot.getFlag(PveFlag.class) || plot + .isAdded(plotPlayer.getUUID())) { + plot.debug(player.getName() + " could not attack " + entityType + + " because pve = false OR animal-attack = false"); + return true; + } + } else if (roadFlags && (area.getRoadFlag(AnimalAttackFlag.class) || area + .getFlag(PveFlag.class))) { + if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.pve." + stub); + return false; + } + } + } else if (EntityCategories.VEHICLE + .contains(entityType)) { // Vehicles are managed in vehicle destroy event + return true; + } else { // victim is something else + if (isPlot) { + if (plot.getFlag(PveFlag.class) || plot.isAdded(plotPlayer.getUUID())) { + return true; + } + } else if (roadFlags && area.getRoadFlag(PveFlag.class)) { + return true; + } + if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.pve." + stub); + if (plot != null) { + plot.debug(player.getName() + " could not attack " + entityType + + " because pve = false"); + } + return false; + } + } + return true; + } else if (dplot != null && (!dplot.equals(vplot) || Objects + .equals(dplot.getOwnerAbs(), vplot.getOwnerAbs()))) { + return vplot != null && vplot.getFlag(PveFlag.class); + } + //disable the firework damage. too much of a headache to support at the moment. + if (vplot != null) { + if (EntityDamageEvent.DamageCause.ENTITY_EXPLOSION == cause + && damager.getType() == EntityType.FIREWORK) { + return false; + } + } + if (vplot == null && roadFlags && area.getRoadFlag(PveFlag.class)) { + return true; + } + return ((vplot != null && vplot.getFlag(PveFlag.class)) || !(damager instanceof Arrow + && !(victim instanceof Creature))); + } + + public static boolean checkEntity(Entity entity, Plot plot) { + if (plot == null || !plot.hasOwner() || plot.getFlags().isEmpty() && plot.getArea() + .getFlagContainer().getFlagMap().isEmpty()) { + return false; + } + + final com.sk89q.worldedit.world.entity.EntityType entityType = + BukkitAdapter.adapt(entity.getType()); + + if (EntityCategories.PLAYER.contains(entityType)) { + return false; + } + + if (EntityCategories.PROJECTILE.contains(entityType) || EntityCategories.OTHER + .contains(entityType) || EntityCategories.HANGING.contains(entityType)) { + return EntityUtil.checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED, + MiscCapFlag.MISC_CAP_UNLIMITED); + } + + // Has to go go before vehicle as horses are both + // animals and vehicles + if (EntityCategories.ANIMAL.contains(entityType) || EntityCategories.VILLAGER + .contains(entityType) || EntityCategories.TAMEABLE.contains(entityType)) { + return EntityUtil + .checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED, MobCapFlag.MOB_CAP_UNLIMITED, + AnimalCapFlag.ANIMAL_CAP_UNLIMITED); + } + + if (EntityCategories.HOSTILE.contains(entityType)) { + return EntityUtil + .checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED, MobCapFlag.MOB_CAP_UNLIMITED, + HostileCapFlag.HOSTILE_CAP_UNLIMITED); + } + + if (EntityCategories.VEHICLE.contains(entityType)) { + return EntityUtil.checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED, + VehicleCapFlag.VEHICLE_CAP_UNLIMITED); + } + + return EntityUtil.checkEntity(plot, EntityCapFlag.ENTITY_CAP_UNLIMITED); + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/IPlotMain.java b/Core/src/main/java/com/plotsquared/core/IPlotMain.java index a38045acb..d88d7ccb9 100644 --- a/Core/src/main/java/com/plotsquared/core/IPlotMain.java +++ b/Core/src/main/java/com/plotsquared/core/IPlotMain.java @@ -162,7 +162,7 @@ public interface IPlotMain

extends ILogger { /** * Register the protection system. */ - void registerPlayerEvents(); + void registerEvents(); /** * Register force field events. diff --git a/Core/src/main/java/com/plotsquared/core/util/EntityUtil.java b/Core/src/main/java/com/plotsquared/core/util/EntityUtil.java index 9bbc4e1aa..de451de83 100644 --- a/Core/src/main/java/com/plotsquared/core/util/EntityUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/EntityUtil.java @@ -43,7 +43,7 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; * Entity related general utility methods */ @UtilityClass -public final class EntityUtil { +public class EntityUtil { private static int capNumeral(@NonNull final String flagName) { int i; From c045ef698cae5724697d2d034afa074a0e48bbed Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Sun, 12 Jul 2020 11:42:45 +0100 Subject: [PATCH 02/49] Add license headers and fix method change in PlotSquared.java --- .../bukkit/listener/BlockEventListener.java | 25 +++++++++++++++++++ .../bukkit/listener/EntityEventListener.java | 25 +++++++++++++++++++ .../com/plotsquared/core/PlotSquared.java | 2 +- 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java index 220e8d073..99bce75fe 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java @@ -1,3 +1,28 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ package com.plotsquared.bukkit.listener; import com.plotsquared.bukkit.player.BukkitPlayer; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java index 8de57cdaf..b052cc70b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java @@ -1,3 +1,28 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ package com.plotsquared.bukkit.listener; import com.plotsquared.bukkit.util.BukkitEntityUtil; diff --git a/Core/src/main/java/com/plotsquared/core/PlotSquared.java b/Core/src/main/java/com/plotsquared/core/PlotSquared.java index e9048f726..3e0e0443b 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotSquared.java +++ b/Core/src/main/java/com/plotsquared/core/PlotSquared.java @@ -252,7 +252,7 @@ public class PlotSquared { this.IMP.runEntityTask(); } if (Settings.Enabled_Components.EVENTS) { - this.IMP.registerPlayerEvents(); + this.IMP.registerEvents(); } // Required this.IMP.registerWorldEvents(); From 14b6f84816869e3ac94ecfd42f30bbb084b199ca Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Sun, 12 Jul 2020 18:50:04 +0100 Subject: [PATCH 03/49] fix typos that were c/p over --- .../com/plotsquared/bukkit/listener/BlockEventListener.java | 2 +- .../com/plotsquared/bukkit/listener/EntityEventListener.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java index 99bce75fe..899a03a04 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java @@ -661,7 +661,7 @@ public class BlockEventListener implements Listener { if (plot != null && plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.DISABLED && event .getBlock().isLiquid()) { - plot.debug("Liquid could now flow because liquid-flow = disabled"); + plot.debug("Liquid could not flow because liquid-flow = disabled"); event.setCancelled(true); return; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java index b052cc70b..0363d42cf 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java @@ -200,7 +200,7 @@ public class EntityEventListener implements Listener { if (plot == null || plot.getFlag(DisablePhysicsFlag.class)) { event.setCancelled(true); if (plot != null) { - plot.debug("Fallin block event was cancelled because disable-physics = true"); + plot.debug("Falling block event was cancelled because disable-physics = true"); } return; } From af7db08036c4769544004888070e832a8d4a7f3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Tue, 14 Jul 2020 13:14:02 +0200 Subject: [PATCH 04/49] Add new placeholder system --- .../bukkit/placeholder/Placeholders.java | 130 +--------- .../com/plotsquared/core/PlotSquared.java | 9 + .../java/com/plotsquared/core/plot/Plot.java | 2 +- .../core/plot/flag/GlobalFlagContainer.java | 10 +- .../core/util/EventDispatcher.java | 8 +- .../core/util/placeholders/Placeholder.java | 63 +++++ .../placeholders/PlaceholderRegistry.java | 230 ++++++++++++++++++ .../placeholders/PlotFlagPlaceholder.java | 75 ++++++ .../placeholders/PlotSpecificPlaceholder.java | 59 +++++ 9 files changed, 455 insertions(+), 131 deletions(-) create mode 100644 Core/src/main/java/com/plotsquared/core/util/placeholders/Placeholder.java create mode 100644 Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java create mode 100644 Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java create mode 100644 Core/src/main/java/com/plotsquared/core/util/placeholders/PlotSpecificPlaceholder.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java index c61b29f37..783d80257 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java @@ -27,17 +27,10 @@ package com.plotsquared.bukkit.placeholder; import com.plotsquared.core.PlotSquared; import com.plotsquared.core.player.PlotPlayer; -import com.plotsquared.core.plot.Plot; -import com.plotsquared.core.plot.flag.GlobalFlagContainer; -import com.plotsquared.core.plot.flag.PlotFlag; -import com.plotsquared.core.util.MainUtil; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import java.util.UUID; - public class Placeholders extends PlaceholderExpansion { public Placeholders() { @@ -70,6 +63,7 @@ public class Placeholders extends PlaceholderExpansion { return ""; } + // PAPI specific ones that don't translate well over into other placeholder APIs if (identifier.startsWith("has_plot_")) { identifier = identifier.substring("has_plot_".length()); if (identifier.isEmpty()) @@ -88,126 +82,8 @@ public class Placeholders extends PlaceholderExpansion { return String.valueOf(pl.getPlotCount(identifier)); } - switch (identifier) { - case "currentplot_world": { - return p.getWorld().getName(); - } - case "has_plot": { - return (pl.getPlotCount() > 0) ? - PlaceholderAPIPlugin.booleanTrue() : - PlaceholderAPIPlugin.booleanFalse(); - } - case "allowed_plot_count": { - return String.valueOf(pl.getAllowedPlots()); - } - case "plot_count": { - return String.valueOf(pl.getPlotCount()); - } - } - - Plot plot = pl.getCurrentPlot(); - - if (plot == null) { - return ""; - } - - switch (identifier) { - case "currentplot_alias": { - return plot.getAlias(); - } - case "currentplot_owner": { - final UUID plotOwner = plot.getOwnerAbs(); - if (plotOwner == null) { - return ""; - } - - try { - return MainUtil.getName(plotOwner, false); - } catch (final Exception ignored) {} - - final String name = Bukkit.getOfflinePlayer(plotOwner).getName(); - return name != null ? name : "unknown"; - } - case "currentplot_members": { - if (plot.getMembers() == null && plot.getTrusted() == null) { - return "0"; - } - return String.valueOf(plot.getMembers().size() + plot.getTrusted().size()); - } - case "currentplot_members_added": { - if (plot.getMembers() == null) { - return "0"; - } - return String.valueOf(plot.getMembers().size()); - } - case "currentplot_members_trusted": { - if (plot.getTrusted() == null) { - return "0"; - } - return String.valueOf(plot.getTrusted().size()); - } - case "currentplot_members_denied": { - if (plot.getDenied() == null) { - return "0"; - } - return String.valueOf(plot.getDenied().size()); - } - case "has_build_rights": { - return plot.isAdded(pl.getUUID()) ? - PlaceholderAPIPlugin.booleanTrue() : - PlaceholderAPIPlugin.booleanFalse(); - } - case "currentplot_x": { - return String.valueOf(plot.getId().getX()); - } - case "currentplot_y": { - return String.valueOf(plot.getId().getY()); - } - case "currentplot_xy": { - return plot.getId().getX() + ";" + plot.getId().getY(); - } - case "currentplot_rating": { - return String.valueOf(plot.getAverageRating()); - } - case "currentplot_biome": { - return plot.getBiomeSynchronous() + ""; - } - default: - break; - } - if (identifier.startsWith("currentplot_localflag_")) { - return getFlagValue(plot, identifier.substring("currentplot_localflag_".length()), - false); - } - if (identifier.startsWith("currentplot_flag_")) { - return getFlagValue(plot, identifier.substring("currentplot_flag_".length()), true); - } - return ""; + // PlotSquared placeholders + return PlotSquared.get().getPlaceholderRegistry().getPlaceholderValue(identifier, pl); } - /** - * Return the flag value from its name on the current plot. - * If the flag doesn't exist it returns an empty string. - * If the flag exists but it is not set on current plot and the parameter inherit is set to true, - * it returns the default value. - * - * @param plot Current plot where the player is - * @param flagName Name of flag to get from current plot - * @param inherit Define if it returns only the flag set on currentplot or also inherited flag - * @return The value of flag serialized in string - */ - private String getFlagValue(final Plot plot, final String flagName, final boolean inherit) { - if (flagName.isEmpty()) - return ""; - final PlotFlag flag = GlobalFlagContainer.getInstance().getFlagFromString(flagName); - if (flag == null) - return ""; - - if (inherit) { - return plot.getFlag(flag).toString(); - } else { - final PlotFlag plotFlag = plot.getFlagContainer().queryLocal(flag.getClass()); - return (plotFlag != null) ? plotFlag.getValue().toString() : ""; - } - } } diff --git a/Core/src/main/java/com/plotsquared/core/PlotSquared.java b/Core/src/main/java/com/plotsquared/core/PlotSquared.java index e9048f726..3451b0a1c 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotSquared.java +++ b/Core/src/main/java/com/plotsquared/core/PlotSquared.java @@ -62,6 +62,7 @@ import com.plotsquared.core.plot.PlotManager; import com.plotsquared.core.plot.comment.CommentManager; import com.plotsquared.core.plot.expiration.ExpireManager; import com.plotsquared.core.plot.expiration.ExpiryTask; +import com.plotsquared.core.plot.flag.GlobalFlagContainer; import com.plotsquared.core.plot.world.DefaultPlotAreaManager; import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.plot.world.SinglePlotArea; @@ -82,6 +83,7 @@ import com.plotsquared.core.util.SetupUtils; import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.logger.ILogger; +import com.plotsquared.core.util.placeholders.PlaceholderRegistry; import com.plotsquared.core.util.query.PlotQuery; import com.plotsquared.core.util.task.TaskManager; import com.plotsquared.core.uuid.UUIDPipeline; @@ -171,6 +173,7 @@ public class PlotSquared { private File storageFile; @Getter private PlotAreaManager plotAreaManager; @Getter private EventDispatcher eventDispatcher; + @Getter private PlaceholderRegistry placeholderRegistry; /** * Initialize PlotSquared with the desired Implementation class. @@ -194,6 +197,9 @@ public class PlotSquared { // ConfigurationSerialization.registerClass(BlockBucket.class, "BlockBucket"); + // Setup the global flag container + GlobalFlagContainer.setup(); + try { new ReflectionUtils(this.IMP.getNMSPackage()); try { @@ -209,6 +215,7 @@ public class PlotSquared { "PlotSquared-" + platform + ".jar"); } } + TaskManager.IMP = this.IMP.getTaskManager(); // World Util. Has to be done before config files are loaded @@ -262,6 +269,8 @@ public class PlotSquared { startExpiryTasks(); // Create Event utility class eventDispatcher = new EventDispatcher(); + // Create placeholder registry + placeholderRegistry = new PlaceholderRegistry(eventDispatcher); // create Hybrid utility class HybridUtils.manager = this.IMP.initHybridUtils(); // Inventory utility class diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index 2adca5334..ac1766e93 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -2256,7 +2256,7 @@ public class Plot { * * @return The plot alias */ - public String getAlias() { + @NotNull public String getAlias() { if (this.settings == null) { return ""; } diff --git a/Core/src/main/java/com/plotsquared/core/plot/flag/GlobalFlagContainer.java b/Core/src/main/java/com/plotsquared/core/plot/flag/GlobalFlagContainer.java index 4d7fdd396..3c44a8b5a 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/flag/GlobalFlagContainer.java +++ b/Core/src/main/java/com/plotsquared/core/plot/flag/GlobalFlagContainer.java @@ -25,6 +25,7 @@ */ package com.plotsquared.core.plot.flag; +import com.google.common.base.Preconditions; import com.plotsquared.core.plot.flag.implementations.AnalysisFlag; import com.plotsquared.core.plot.flag.implementations.AnimalAttackFlag; import com.plotsquared.core.plot.flag.implementations.AnimalCapFlag; @@ -114,7 +115,13 @@ import java.util.Map; public final class GlobalFlagContainer extends FlagContainer { - @Getter private static final GlobalFlagContainer instance = new GlobalFlagContainer(); + @Getter private static GlobalFlagContainer instance; + + public static void setup() { + Preconditions.checkState(instance == null, "Cannot setup the container twice"); + instance = new GlobalFlagContainer(); + } + private static Map> stringClassMap; private GlobalFlagContainer() { @@ -124,6 +131,7 @@ public final class GlobalFlagContainer extends FlagContainer { } }); stringClassMap = new HashMap<>(); + // Register all default flags here // Boolean flags this.addFlag(ExplosionFlag.EXPLOSION_FALSE); diff --git a/Core/src/main/java/com/plotsquared/core/util/EventDispatcher.java b/Core/src/main/java/com/plotsquared/core/util/EventDispatcher.java index cb554b754..23d5dd15f 100644 --- a/Core/src/main/java/com/plotsquared/core/util/EventDispatcher.java +++ b/Core/src/main/java/com/plotsquared/core/util/EventDispatcher.java @@ -80,9 +80,9 @@ import java.util.UUID; public class EventDispatcher { - private EventBus eventBus = new EventBus("PlotSquaredEvents"); + private final EventBus eventBus = new EventBus("PlotSquaredEvents"); - private List listeners = new ArrayList<>(); + private final List listeners = new ArrayList<>(); public void registerListener(Object listener) { eventBus.register(listener); @@ -100,6 +100,10 @@ public class EventDispatcher { } } + public void callGenericEvent(@NotNull final Object event) { + eventBus.post(event); + } + public void callEvent(@NotNull final PlotEvent event) { eventBus.post(event); } diff --git a/Core/src/main/java/com/plotsquared/core/util/placeholders/Placeholder.java b/Core/src/main/java/com/plotsquared/core/util/placeholders/Placeholder.java new file mode 100644 index 000000000..38e28a586 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/util/placeholders/Placeholder.java @@ -0,0 +1,63 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.core.util.placeholders; + +import com.google.common.base.Preconditions; +import com.plotsquared.core.player.PlotPlayer; +import lombok.EqualsAndHashCode; +import lombok.ToString; +import org.jetbrains.annotations.NotNull; + +/** + * A placeholder is a keyed value that gets replaced by a {@link PlotPlayer player}-specific value at runtime + */ +@EqualsAndHashCode(of = "key") @ToString(of = "key") +public abstract class Placeholder { + + private final String key; + + public Placeholder(@NotNull final String key) { + this.key = Preconditions.checkNotNull(key, "Key may not be null"); + } + + /** + * Get the value of the placeholder for a particular player + * + * @param player Player + * @return Placeholder value. Return {@code ""} if no placeholder value can be returned + */ + @NotNull public abstract String getValue(@NotNull final PlotPlayer player); + + /** + * Get the placeholder key + * + * @return Placeholder key + */ + @NotNull public final String getKey() { + return this.key; + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java new file mode 100644 index 000000000..243ca0909 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java @@ -0,0 +1,230 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.core.util.placeholders; + +import com.google.common.base.Function; +import com.google.common.base.Preconditions; +import com.google.common.collect.Maps; +import com.plotsquared.core.player.PlotPlayer; +import com.plotsquared.core.plot.Plot; +import com.plotsquared.core.plot.flag.GlobalFlagContainer; +import com.plotsquared.core.plot.flag.PlotFlag; +import com.plotsquared.core.util.EventDispatcher; +import com.plotsquared.core.util.MainUtil; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.Collections; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.function.BiFunction; + +/** + * Registry that contains {@link Placeholder placeholders} + */ +public final class PlaceholderRegistry { + + private final Map placeholders; + private final EventDispatcher eventDispatcher; + + public PlaceholderRegistry(@NotNull final EventDispatcher eventDispatcher) { + this.placeholders = Maps.newHashMap(); + this.eventDispatcher = eventDispatcher; + this.registerDefault(); + } + + private void registerDefault() { + final GlobalFlagContainer globalFlagContainer = GlobalFlagContainer.getInstance(); + for (final PlotFlag flag : globalFlagContainer.getRecognizedPlotFlags()) { + this.registerPlaceholder(new PlotFlagPlaceholder(flag, true)); + this.registerPlaceholder(new PlotFlagPlaceholder(flag, false)); + } + GlobalFlagContainer.getInstance().subscribe((flag, type) -> { + this.registerPlaceholder(new PlotFlagPlaceholder(flag, true)); + this.registerPlaceholder(new PlotFlagPlaceholder(flag, false)); + }); + this.createPlaceholder("currentplot_world", player -> player.getLocation().getWorld()); + this.createPlaceholder("has_plot", player -> player.getPlotCount() > 0 ? "true" : "false"); + this.createPlaceholder("allowed_plot_count", player -> Integer.toString(player.getAllowedPlots())); + this.createPlaceholder("plot_count", player -> Integer.toString(player.getPlotCount())); + this.createPlaceholder("currentplot_alias", (player, plot) -> plot.getAlias()); + this.createPlaceholder("currentplot_owner", (player, plot) -> { + final UUID plotOwner = plot.getOwnerAbs(); + if (plotOwner == null) { + return ""; + } + + try { + return MainUtil.getName(plotOwner, false); + } catch (final Exception ignored) {} + + return "unknown"; + }); + this.createPlaceholder("currentplot_members", (player, plot) -> { + if (plot.getMembers() == null && plot.getTrusted() == null) { + return "0"; + } + return String.valueOf(plot.getMembers().size() + plot.getTrusted().size()); + }); + this.createPlaceholder("currentplot_members_added", (player, plot) -> { + if (plot.getMembers() == null) { + return "0"; + } + return String.valueOf(plot.getMembers().size()); + }); + this.createPlaceholder("currentplot_members_trusted", (player, plot) -> { + if (plot.getTrusted() == null) { + return "0"; + } + return String.valueOf(plot.getTrusted().size()); + }); + this.createPlaceholder("currentplot_members_denied", (player, plot) -> { + if (plot.getDenied() == null) { + return "0"; + } + return String.valueOf(plot.getDenied().size()); + }); + this.createPlaceholder("has_build_rights", (player, plot) -> + plot.isAdded(player.getUUID()) ? "true" : "false"); + this.createPlaceholder("currentplot_x", (player, plot) -> Integer.toString(plot.getId().getX())); + this.createPlaceholder("currentplot_y", (player, plot) -> Integer.toString(plot.getId().getY())); + this.createPlaceholder("currentplot_xy", (player, plot) -> plot.getId().toString()); + this.createPlaceholder("currentplot_rating", (player, plot) -> Double.toString(plot.getAverageRating())); + this.createPlaceholder("currentplot_biome", (player, plot) -> plot.getBiomeSynchronous().toString()); + } + + /** + * Create a functional placeholder + * + * @param key Placeholder key + * @param placeholderFunction Placeholder generator. Cannot return null + */ + @SuppressWarnings("ALL") public void createPlaceholder(@NotNull final String key, + @NotNull final Function, String> placeholderFunction) { + this.registerPlaceholder(new Placeholder(key) { + @Override @NotNull public String getValue(@NotNull final PlotPlayer player) { + return placeholderFunction.apply(player); + } + }); + } + + /** + * Create a functional placeholder + * + * @param key Placeholder key + * @param placeholderFunction Placeholder generator. Cannot return null + */ + public void createPlaceholder(@NotNull final String key, + @NotNull final BiFunction, Plot, String> placeholderFunction) { + this.registerPlaceholder(new PlotSpecificPlaceholder(key) { + @Override @NotNull public String getValue(@NotNull final PlotPlayer player, @NotNull final Plot plot) { + return placeholderFunction.apply(player, plot); + } + }); + } + + /** + * Register a placeholder + * + * @param placeholder Placeholder instance + */ + public void registerPlaceholder(@NotNull final Placeholder placeholder) { + final Placeholder previous = this.placeholders + .put(placeholder.getKey().toLowerCase(Locale.ENGLISH), + Preconditions.checkNotNull(placeholder, "Placeholder may not be null")); + if (previous != null) { + this.eventDispatcher.callGenericEvent(new PlaceholderAddedEvent(placeholder)); + } + } + + /** + * Get a placeholder instance from its key + * + * @param key Placeholder key + * @return Placeholder value + */ + @Nullable public Placeholder getPlaceholder(@NotNull final String key) { + return this.placeholders.get( + Preconditions.checkNotNull(key, "Key may not be null").toLowerCase(Locale.ENGLISH)); + } + + /** + * Get the placeholder value evaluated for a player, and catch and deal with any problems + * occurring while doing so + * + * @param key Placeholder key + * @param player Player to evaluate for + * @return Replacement value + */ + @NotNull public String getPlaceholderValue(@NotNull final String key, + @NotNull final PlotPlayer player) { + final Placeholder placeholder = getPlaceholder(key); + if (placeholder == null) { + return ""; + } + String placeholderValue = ""; + try { + placeholderValue = placeholder.getValue(player); + // If a placeholder for some reason decides to be disobedient, we catch it here + if (placeholderValue == null) { + new RuntimeException(String + .format("Placeholder '%s' returned null for player '%s'", placeholder.getKey(), + player.getName())).printStackTrace(); + } + } catch (final Exception exception) { + new RuntimeException(String + .format("Placeholder '%s' failed to evalulate for player '%s'", + placeholder.getKey(), player.getName()), exception).printStackTrace(); + } + return placeholderValue; + } + + /** + * Get all placeholders + * + * @return Unmodifiable collection of placeholders + */ + @NotNull public Collection getPlaceholders() { + return Collections.unmodifiableCollection(this.placeholders.values()); + } + + + /** + * Event called when a new {@link Placeholder} has been added + */ + @RequiredArgsConstructor + @Getter + public static class PlaceholderAddedEvent { + + private final Placeholder placeholder; + + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java new file mode 100644 index 000000000..40b963d06 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java @@ -0,0 +1,75 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.core.util.placeholders; + +import com.plotsquared.core.player.PlotPlayer; +import com.plotsquared.core.plot.Plot; +import com.plotsquared.core.plot.flag.GlobalFlagContainer; +import com.plotsquared.core.plot.flag.PlotFlag; +import org.jetbrains.annotations.NotNull; + +public final class PlotFlagPlaceholder extends PlotSpecificPlaceholder { + + private final PlotFlag flag; + private final boolean local; + + public PlotFlagPlaceholder(@NotNull final PlotFlag flag, final boolean local) { + super(String.format("currentplot_%sflag_%s", local ? "local": "", flag.getName())); + this.flag = flag; + this.local = local; + } + + @Override @NotNull public String getValue(@NotNull final PlotPlayer player, @NotNull final Plot plot) { + return this.getFlagValue(plot, this.flag.getName(), !this.local); + } + + /** + * Return the flag value from its name on the current plot. + * If the flag doesn't exist it returns an empty string. + * If the flag exists but it is not set on current plot and the parameter inherit is set to true, + * it returns the default value. + * + * @param plot Current plot where the player is + * @param flagName Name of flag to get from current plot + * @param inherit Define if it returns only the flag set on currentplot or also inherited flag + * @return The value of flag serialized in string + */ + private String getFlagValue(final Plot plot, final String flagName, final boolean inherit) { + if (flagName.isEmpty()) + return ""; + final PlotFlag flag = GlobalFlagContainer.getInstance().getFlagFromString(flagName); + if (flag == null) + return ""; + + if (inherit) { + return plot.getFlag(flag).toString(); + } else { + final PlotFlag plotFlag = plot.getFlagContainer().queryLocal(flag.getClass()); + return (plotFlag != null) ? plotFlag.getValue().toString() : ""; + } + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotSpecificPlaceholder.java b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotSpecificPlaceholder.java new file mode 100644 index 000000000..92285238d --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotSpecificPlaceholder.java @@ -0,0 +1,59 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.core.util.placeholders; + +import com.plotsquared.core.player.PlotPlayer; +import com.plotsquared.core.plot.Plot; +import org.jetbrains.annotations.NotNull; + +/** + * A {@link Placeholder placeholder} that requires a {@link com.plotsquared.core.plot.Plot plot} + */ +public abstract class PlotSpecificPlaceholder extends Placeholder { + + public PlotSpecificPlaceholder(@NotNull final String key) { + super(key); + } + + @Override @NotNull public final String getValue(@NotNull final PlotPlayer player) { + final Plot plot = player.getCurrentPlot(); + if (plot == null) { + return ""; + } + return this.getValue(player, plot); + } + + /** + * Get the value of the placeholder for the {@link PlotPlayer player} in a specific {@link Plot plot} + * + * @param player Player that the placeholder is evaluated for + * @param plot Plot that the player is in + * @return Placeholder value, or {@code ""} if the placeholder does not apply + */ + @NotNull public abstract String getValue(@NotNull final PlotPlayer player, + @NotNull final Plot plot); + +} From 1908588fcbd4c35ad16b1f17f6870a0e34db0cbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Tue, 14 Jul 2020 13:17:21 +0200 Subject: [PATCH 05/49] Change expansion author and version --- .../com/plotsquared/bukkit/placeholder/Placeholders.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java index 783d80257..0c3b8bfad 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java @@ -45,7 +45,7 @@ public class Placeholders extends PlaceholderExpansion { } @Override public String getAuthor() { - return "NotMyFault"; + return "IntellectualSites"; } @Override public String getIdentifier() { @@ -53,11 +53,11 @@ public class Placeholders extends PlaceholderExpansion { } @Override public String getVersion() { - return "2.5"; + return "3"; } @Override public String onPlaceholderRequest(Player p, String identifier) { - final PlotPlayer pl = PlotSquared.imp().getPlayerManager().getPlayerIfExists(p.getUniqueId()); + final PlotPlayer pl = PlotSquared.imp().getPlayerManager().getPlayerIfExists(p.getUniqueId()); if (pl == null) { return ""; From 2e4c43c251c3011ae13bf0670850cae1670ca41d Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Tue, 14 Jul 2020 19:10:53 +0100 Subject: [PATCH 06/49] Add config option to disable placing top wall blocks --- .../core/generator/ClassicPlotManager.java | 67 +++++++++++-------- .../core/generator/ClassicPlotWorld.java | 4 ++ .../plotsquared/core/generator/HybridGen.java | 12 ++-- 3 files changed, 50 insertions(+), 33 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java index 46333a84c..be60498bd 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java @@ -84,8 +84,8 @@ public class ClassicPlotManager extends SquarePlotManager { @Override public boolean unClaimPlot(Plot plot, Runnable whenDone) { setWallFilling(plot.getId(), classicPlotWorld.WALL_FILLING.toPattern()); - if (!classicPlotWorld.WALL_BLOCK.isAir() || !classicPlotWorld.WALL_BLOCK - .equals(classicPlotWorld.CLAIMED_WALL_BLOCK)) { + if (classicPlotWorld.PLACE_TOP_BLOCK && (!classicPlotWorld.WALL_BLOCK.isAir() + || !classicPlotWorld.WALL_BLOCK.equals(classicPlotWorld.CLAIMED_WALL_BLOCK))) { setWall(plot.getId(), classicPlotWorld.WALL_BLOCK.toPattern()); } return GlobalBlockQueue.IMP.addEmptyTask(whenDone); @@ -324,19 +324,23 @@ public class ClassicPlotManager extends SquarePlotManager { queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx, 1, sz + 1), new Location(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid( - new Location(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, - sz + 1), - new Location(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, - ez - 1), classicPlotWorld.WALL_BLOCK.toPattern()); + if (classicPlotWorld.PLACE_TOP_BLOCK) { + queue.setCuboid( + new Location(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, + sz + 1), + new Location(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, + ez - 1), classicPlotWorld.WALL_BLOCK.toPattern()); + } queue.setCuboid(new Location(classicPlotWorld.getWorldName(), ex, 1, sz + 1), new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid( - new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, - sz + 1), - new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, - ez - 1), classicPlotWorld.WALL_BLOCK.toPattern()); + if (classicPlotWorld.PLACE_TOP_BLOCK) { + queue.setCuboid( + new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, + sz + 1), + new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, + ez - 1), classicPlotWorld.WALL_BLOCK.toPattern()); + } queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); @@ -362,19 +366,21 @@ public class ClassicPlotManager extends SquarePlotManager { queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 1, sz), new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, sz), classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid( - new Location(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, - sz), - new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, - sz), classicPlotWorld.WALL_BLOCK.toPattern()); + if (classicPlotWorld.PLACE_TOP_BLOCK) { + queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, + classicPlotWorld.WALL_HEIGHT + 1, sz), + new Location(classicPlotWorld.getWorldName(), ex - 1, + classicPlotWorld.WALL_HEIGHT + 1, sz), classicPlotWorld.WALL_BLOCK.toPattern()); + } queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 1, ez), new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, ez), classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid( - new Location(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, - ez), - new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, - ez), classicPlotWorld.WALL_BLOCK.toPattern()); + if (classicPlotWorld.PLACE_TOP_BLOCK) { + queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, + classicPlotWorld.WALL_HEIGHT + 1, ez), + new Location(classicPlotWorld.getWorldName(), ex - 1, + classicPlotWorld.WALL_HEIGHT + 1, ez), classicPlotWorld.WALL_BLOCK.toPattern()); + } queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), new Location(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); @@ -456,10 +462,10 @@ public class ClassicPlotManager extends SquarePlotManager { int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; LocalBlockQueue queue = classicPlotWorld.getQueue(false); queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), - new Location(classicPlotWorld.getWorldName(), ex, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), - BlockTypes.AIR.getDefaultState()); + Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), + new Location(classicPlotWorld.getWorldName(), ex, + classicPlotWorld.getPlotManager().getWorldHeight(), ez), + BlockTypes.AIR.getDefaultState()); queue.setCuboid(new Location(classicPlotWorld.getWorldName(), sx, 1, sz), new Location(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez), classicPlotWorld.MAIN_BLOCK.toPattern()); @@ -477,7 +483,8 @@ public class ClassicPlotManager extends SquarePlotManager { */ @Override public boolean finishPlotMerge(List plotIds) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; - if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { + if (classicPlotWorld.PLACE_TOP_BLOCK && (!claim.isAir() || !claim + .equals(classicPlotWorld.WALL_BLOCK))) { for (PlotId plotId : plotIds) { setWall(plotId, claim.toPattern()); } @@ -493,7 +500,8 @@ public class ClassicPlotManager extends SquarePlotManager { @Override public boolean finishPlotUnlink(List plotIds) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; - if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { + if (classicPlotWorld.PLACE_TOP_BLOCK && (!claim.isAir() || !claim + .equals(classicPlotWorld.WALL_BLOCK))) { for (PlotId id : plotIds) { setWall(id, claim.toPattern()); } @@ -511,7 +519,8 @@ public class ClassicPlotManager extends SquarePlotManager { @Override public boolean claimPlot(Plot plot) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; - if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { + if (classicPlotWorld.PLACE_TOP_BLOCK && (!claim.isAir() || !claim + .equals(classicPlotWorld.WALL_BLOCK))) { return setWall(plot.getId(), claim.toPattern()); } return true; diff --git a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotWorld.java b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotWorld.java index 13b2fb352..8a0e41c02 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotWorld.java +++ b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotWorld.java @@ -52,6 +52,7 @@ public abstract class ClassicPlotWorld extends SquarePlotWorld { public BlockBucket ROAD_BLOCK = new BlockBucket(BlockTypes.QUARTZ_BLOCK); // BlockUtil.get((short) 155, (byte) 0); public boolean PLOT_BEDROCK = true; + public boolean PLACE_TOP_BLOCK = true; public ClassicPlotWorld(String worldName, String id, @NotNull IndependentPlotGenerator generator, PlotId min, PlotId max) { @@ -79,6 +80,8 @@ public abstract class ClassicPlotWorld extends SquarePlotWorld { ConfigurationUtil.BLOCK_BUCKET), new ConfigurationNode("wall.block_claimed", this.CLAIMED_WALL_BLOCK, "Wall block (claimed)", ConfigurationUtil.BLOCK_BUCKET), + new ConfigurationNode("wall.place_top_block", this.PLACE_TOP_BLOCK, + "Place or not the top block", ConfigurationUtil.BOOLEAN), new ConfigurationNode("road.width", this.ROAD_WIDTH, "Road width", ConfigurationUtil.INTEGER), new ConfigurationNode("road.height", this.ROAD_HEIGHT, "Road height", @@ -109,5 +112,6 @@ public abstract class ClassicPlotWorld extends SquarePlotWorld { this.WALL_FILLING = new BlockBucket(config.getString("wall.filling")); this.WALL_HEIGHT = Math.min(254, config.getInt("wall.height")); this.CLAIMED_WALL_BLOCK = new BlockBucket(config.getString("wall.block_claimed")); + this.PLACE_TOP_BLOCK = config.getBoolean("wall.place_top_block"); } } diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridGen.java b/Core/src/main/java/com/plotsquared/core/generator/HybridGen.java index a4f955682..c45931d81 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridGen.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridGen.java @@ -172,8 +172,10 @@ public class HybridGen extends IndependentPlotGenerator { result.setBlock(x, y, z, hybridPlotWorld.WALL_FILLING.toPattern()); } if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { - result.setBlock(x, hybridPlotWorld.WALL_HEIGHT + 1, z, - hybridPlotWorld.WALL_BLOCK.toPattern()); + if (hybridPlotWorld.PLACE_TOP_BLOCK) { + result.setBlock(x, hybridPlotWorld.WALL_HEIGHT + 1, z, + hybridPlotWorld.WALL_BLOCK.toPattern()); + } } else { placeSchem(hybridPlotWorld, result, relativeX[x], relativeZ[z], x, z, true); @@ -197,8 +199,10 @@ public class HybridGen extends IndependentPlotGenerator { result.setBlock(x, y, z, hybridPlotWorld.WALL_FILLING.toPattern()); } if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { - result.setBlock(x, hybridPlotWorld.WALL_HEIGHT + 1, z, - hybridPlotWorld.WALL_BLOCK.toPattern()); + if (hybridPlotWorld.PLACE_TOP_BLOCK) { + result.setBlock(x, hybridPlotWorld.WALL_HEIGHT + 1, z, + hybridPlotWorld.WALL_BLOCK.toPattern()); + } } else { placeSchem(hybridPlotWorld, result, relativeX[x], relativeZ[z], x, z, true); From 30327d2fa3a288c19f97724a75f73f15d7b2331c Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Tue, 14 Jul 2020 19:11:46 +0100 Subject: [PATCH 07/49] update bukkit pom --- Bukkit/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index cde998b9a..0e7adcda4 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -45,7 +45,7 @@ io.papermc paperlib - 1.0.2 + 1.0.4 compile From 34655b8d4114ce6190d2974758becaebcc41308b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Tue, 14 Jul 2020 20:41:08 +0200 Subject: [PATCH 08/49] Add (untested) MVdWPlaceholderAPI support --- Bukkit/build.gradle | 2 + .../com/plotsquared/bukkit/BukkitMain.java | 10 ++- .../bukkit/placeholder/MVdWPlaceholders.java | 76 +++++++++++++++++++ ...laceholders.java => PAPIPlaceholders.java} | 4 +- Bukkit/src/main/resources/plugin.yml | 2 +- 5 files changed, 89 insertions(+), 5 deletions(-) create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java rename Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/{Placeholders.java => PAPIPlaceholders.java} (97%) diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index e206fbe5b..fa23da2ff 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -14,6 +14,7 @@ repositories { maven { url = "https://ci.ender.zone/plugin/repository/everything/" } maven { url = "https://mvn.intellectualsites.com/content/repositories/snapshots" } maven { url = "https://repo.wea-ondara.net/repository/public/" } + maven { url = "http://repo.mvdw-software.be/content/groups/public/" } mavenLocal() } @@ -41,6 +42,7 @@ dependencies { implementation("net.alpenblock:BungeePerms:4.0-dev-106") compile("se.hyperver.hyperverse:Core:0.6.0-SNAPSHOT"){ transitive = false } compile('com.sk89q:squirrelid:1.0.0-SNAPSHOT'){ transitive = false } + compile('be.maximvdw:MVdWPlaceholderAPI:2.1.1-SNAPSHOT'){ transitive = false } } sourceCompatibility = 1.8 diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java index c03cdd694..66bc5ed3c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java @@ -36,8 +36,9 @@ import com.plotsquared.bukkit.listener.WorldEvents; import com.plotsquared.bukkit.managers.BukkitWorldManager; import com.plotsquared.bukkit.managers.HyperverseWorldManager; import com.plotsquared.bukkit.managers.MultiverseWorldManager; +import com.plotsquared.bukkit.placeholder.MVdWPlaceholders; import com.plotsquared.bukkit.placeholder.PlaceholderFormatter; -import com.plotsquared.bukkit.placeholder.Placeholders; +import com.plotsquared.bukkit.placeholder.PAPIPlaceholders; import com.plotsquared.bukkit.player.BukkitPlayerManager; import com.plotsquared.bukkit.queue.BukkitLocalQueue; import com.plotsquared.bukkit.schematic.BukkitSchematicHandler; @@ -363,7 +364,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain< } if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { - new Placeholders().register(); + new PAPIPlaceholders().register(); if (Settings.Enabled_Components.EXTERNAL_PLACEHOLDERS) { ChatFormatter.formatters.add(new PlaceholderFormatter()); } @@ -373,6 +374,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain< .debug(Captions.PREFIX + "&6PlaceholderAPI is not in use. Hook deactivated."); } + if (Bukkit.getPluginManager().isPluginEnabled("MVdWPlaceholderAPI")) { + new MVdWPlaceholders(this, PlotSquared.get().getPlaceholderRegistry()); + PlotSquared.log(Captions.PREFIX + "&cPlotSquared hooked into MVdWPlaceholderAPI"); + } + this.startMetrics(); if (Settings.Enabled_Components.WORLDS) { TaskManager.IMP.taskRepeat(this::unload, 20); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java new file mode 100644 index 000000000..5bd835de0 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java @@ -0,0 +1,76 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.bukkit.placeholder; + +import be.maximvdw.placeholderapi.PlaceholderAPI; +import com.google.common.eventbus.Subscribe; +import com.plotsquared.bukkit.util.BukkitUtil; +import com.plotsquared.core.PlotSquared; +import com.plotsquared.core.player.PlotPlayer; +import com.plotsquared.core.util.placeholders.Placeholder; +import com.plotsquared.core.util.placeholders.PlaceholderRegistry; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; + +/** + * Placeholder support for MVdWPlaceholderAPI + */ +public class MVdWPlaceholders { + + private final Plugin plugin; + private final PlaceholderRegistry registry; + + public MVdWPlaceholders(@NotNull final Plugin plugin, + @NotNull final PlaceholderRegistry registry) { + this.plugin = plugin; + this.registry = registry; + for (final Placeholder placeholder : registry.getPlaceholders()) { + this.addPlaceholder(placeholder); + } + PlotSquared.get().getEventDispatcher().registerListener(this); + } + + @Subscribe public void onNewPlaceholder(@NotNull final + PlaceholderRegistry.PlaceholderAddedEvent event) { + this.addPlaceholder(event.getPlaceholder()); + } + + private void addPlaceholder(@NotNull final Placeholder placeholder) { + PlaceholderAPI.registerPlaceholder(plugin, String.format("plotsquared_%s", placeholder.getKey()), + placeholderReplaceEvent -> { + if (!placeholderReplaceEvent.isOnline() || placeholderReplaceEvent.getPlayer() == null) { + return ""; + } + final PlotPlayer player = BukkitUtil.getPlayer(placeholderReplaceEvent.getPlayer()); + if (player == null) { + return ""; + } + return registry.getPlaceholderValue(placeholderReplaceEvent.getPlaceholder(), player); + }); + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/PAPIPlaceholders.java similarity index 97% rename from Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/PAPIPlaceholders.java index 0c3b8bfad..52d30d5ed 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/Placeholders.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/PAPIPlaceholders.java @@ -31,9 +31,9 @@ import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.entity.Player; -public class Placeholders extends PlaceholderExpansion { +public class PAPIPlaceholders extends PlaceholderExpansion { - public Placeholders() { + public PAPIPlaceholders() { } @Override public boolean persist() { diff --git a/Bukkit/src/main/resources/plugin.yml b/Bukkit/src/main/resources/plugin.yml index 41967220c..2dd7edbac 100644 --- a/Bukkit/src/main/resources/plugin.yml +++ b/Bukkit/src/main/resources/plugin.yml @@ -6,7 +6,7 @@ load: STARTUP description: "Easy, yet powerful Plot World generation and management." authors: [Citymonstret, Empire92, MattBDev, dordsor21, NotMyFault, SirYwell] website: https://www.spigotmc.org/resources/77506/ -softdepend: [Vault, PlaceholderAPI, Essentials, LuckPerms, BungeePerms] +softdepend: [Vault, PlaceholderAPI, Essentials, LuckPerms, BungeePerms, MVdWPlaceholderAPI] loadbefore: [MultiWorld, Multiverse-Core] depend: [WorldEdit] database: false From 64f5580eddbdcf1e0e10e06bed8d373f4cc43fe5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Tue, 14 Jul 2020 20:46:52 +0200 Subject: [PATCH 09/49] Fix code styling issue --- .../core/util/placeholders/PlotFlagPlaceholder.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java index 40b963d06..51d075d26 100644 --- a/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java +++ b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java @@ -57,13 +57,14 @@ public final class PlotFlagPlaceholder extends PlotSpecificPlaceholder { * @param inherit Define if it returns only the flag set on currentplot or also inherited flag * @return The value of flag serialized in string */ - private String getFlagValue(final Plot plot, final String flagName, final boolean inherit) { - if (flagName.isEmpty()) + @NotNull private String getFlagValue(@NotNull final Plot plot, @NotNull final String flagName, final boolean inherit) { + if (flagName.isEmpty()) { return ""; + } final PlotFlag flag = GlobalFlagContainer.getInstance().getFlagFromString(flagName); - if (flag == null) + if (flag == null) { return ""; - + } if (inherit) { return plot.getFlag(flag).toString(); } else { From 5d2d4ac12b1a243890373da8a8386d805e962f84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Tue, 14 Jul 2020 20:47:15 +0200 Subject: [PATCH 10/49] fix language issue --- .../plotsquared/core/util/placeholders/PlotFlagPlaceholder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java index 51d075d26..4a3d1876a 100644 --- a/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java +++ b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlotFlagPlaceholder.java @@ -54,7 +54,7 @@ public final class PlotFlagPlaceholder extends PlotSpecificPlaceholder { * * @param plot Current plot where the player is * @param flagName Name of flag to get from current plot - * @param inherit Define if it returns only the flag set on currentplot or also inherited flag + * @param inherit Define if it returns only the flag set on the current plot or also inherited flags * @return The value of flag serialized in string */ @NotNull private String getFlagValue(@NotNull final Plot plot, @NotNull final String flagName, final boolean inherit) { From a52249513e17dc65e31d9493e3afac735800ae23 Mon Sep 17 00:00:00 2001 From: N0tMyFaultOG Date: Wed, 15 Jul 2020 12:05:42 +0200 Subject: [PATCH 11/49] Update MVdW version --- Bukkit/build.gradle | 2 +- Bukkit/pom.xml | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index fa23da2ff..61842d3ce 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -42,7 +42,7 @@ dependencies { implementation("net.alpenblock:BungeePerms:4.0-dev-106") compile("se.hyperver.hyperverse:Core:0.6.0-SNAPSHOT"){ transitive = false } compile('com.sk89q:squirrelid:1.0.0-SNAPSHOT'){ transitive = false } - compile('be.maximvdw:MVdWPlaceholderAPI:2.1.1-SNAPSHOT'){ transitive = false } + compile('be.maximvdw:MVdWPlaceholderAPI:3.1.1-SNAPSHOT'){ transitive = false } } sourceCompatibility = 1.8 diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index cde998b9a..c70676567 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -45,7 +45,7 @@ io.papermc paperlib - 1.0.2 + 1.0.4 compile @@ -84,6 +84,18 @@ + + be.maximvdw + MVdWPlaceholderAPI + 3.1.1-SNAPSHOT + compile + + + * + * + + + com.sk89q.worldedit worldedit-core From e8c155763be355172f28b54c5ff3545d5182406f Mon Sep 17 00:00:00 2001 From: N0tMyFaultOG Date: Wed, 15 Jul 2020 12:44:07 +0200 Subject: [PATCH 12/49] Register placeholders --- Bukkit/pom.xml | 2 +- .../src/main/java/com/plotsquared/bukkit/BukkitMain.java | 7 ++----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index c70676567..07e1a9ca7 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -87,7 +87,7 @@ be.maximvdw MVdWPlaceholderAPI - 3.1.1-SNAPSHOT + 2.1.1-SNAPSHOT compile diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java index 66bc5ed3c..5ee38078c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java @@ -369,14 +369,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain< ChatFormatter.formatters.add(new PlaceholderFormatter()); } PlotSquared.log(Captions.PREFIX + "&6PlotSquared hooked into PlaceholderAPI"); - } else { - PlotSquared - .debug(Captions.PREFIX + "&6PlaceholderAPI is not in use. Hook deactivated."); } - if (Bukkit.getPluginManager().isPluginEnabled("MVdWPlaceholderAPI")) { + if (Bukkit.getPluginManager().getPlugin("MVdWPlaceholderAPI") != null) { new MVdWPlaceholders(this, PlotSquared.get().getPlaceholderRegistry()); - PlotSquared.log(Captions.PREFIX + "&cPlotSquared hooked into MVdWPlaceholderAPI"); + PlotSquared.log(Captions.PREFIX + "&6PlotSquared hooked into MVdWPlaceholderAPI"); } this.startMetrics(); From 4996d8bcd1cfa1982513d626c3ba2761d873fa65 Mon Sep 17 00:00:00 2001 From: N0tMyFaultOG Date: Wed, 15 Jul 2020 14:05:15 +0200 Subject: [PATCH 13/49] Remove left over debugs --- .../com/plotsquared/bukkit/listener/EntityEventListener.java | 2 -- .../com/plotsquared/bukkit/listener/PlayerEventListener.java | 2 -- 2 files changed, 4 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java index 0363d42cf..5bfb26a56 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java @@ -305,13 +305,11 @@ public class EntityEventListener implements Listener { if (area != null) { Plot plot = area.getOwnedPlot(location); if (plot != null && plot.getFlag(MobPlaceFlag.class)) { - System.out.println("bb"); return; } if (plot != null) { plot.debug(e.getType() + " could not change block because mob-place = false"); } - System.out.println("aa"); event.setCancelled(true); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java index e2bb3cb36..6d11cd75c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java @@ -933,7 +933,6 @@ public class PlayerEventListener extends PlotListener implements Listener { case PHYSICAL: { eventType = PlayerBlockEventType.TRIGGER_PHYSICAL; blocktype1 = BukkitAdapter.asBlockType(block.getType()); - System.out.println("cc"); break; } //todo rearrange the right click code. it is all over the place. @@ -1044,7 +1043,6 @@ public class PlayerEventListener extends PlotListener implements Listener { } if (!PlotSquared.get().getEventDispatcher() .checkPlayerBlockEvent(pp, eventType, location, blocktype1, true)) { - System.out.println("dd"); event.setCancelled(true); event.setUseInteractedBlock(Event.Result.DENY); } From 32b28a4ca5679607580fb2e3f2677f1464d77bd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Wed, 15 Jul 2020 22:42:58 +0200 Subject: [PATCH 14/49] Turn all UUID messages into debug messages --- .../com/plotsquared/core/uuid/UUIDPipeline.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/uuid/UUIDPipeline.java b/Core/src/main/java/com/plotsquared/core/uuid/UUIDPipeline.java index 997cdfdc1..9ca6e783a 100644 --- a/Core/src/main/java/com/plotsquared/core/uuid/UUIDPipeline.java +++ b/Core/src/main/java/com/plotsquared/core/uuid/UUIDPipeline.java @@ -164,8 +164,9 @@ public class UUIDPipeline { } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } catch (TimeoutException ignored) { - PlotSquared.log(Captions.PREFIX + " (UUID) Request for " + username + " timed out"); - // This is completely valid, we just don't care anymore + if (Settings.DEBUG) { + PlotSquared.debug(Captions.PREFIX + " (UUID) Request for " + username + " timed out"); + } } return null; } @@ -187,8 +188,9 @@ public class UUIDPipeline { } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } catch (TimeoutException ignored) { - PlotSquared.log(Captions.PREFIX + " (UUID) Request for " + uuid + " timed out"); - // This is completely valid, we just don't care anymore + if (Settings.DEBUG) { + PlotSquared.debug(Captions.PREFIX + " (UUID) Request for " + uuid + " timed out"); + } } return null; } @@ -321,7 +323,7 @@ public class UUIDPipeline { this.consume(mappings); return mappings; } else if (Settings.DEBUG) { - PlotSquared.log("Failed to find all usernames"); + PlotSquared.debug("Failed to find all usernames"); } if (Settings.UUID.UNKNOWN_AS_DEFAULT) { @@ -384,7 +386,7 @@ public class UUIDPipeline { this.consume(mappings); return mappings; } else if (Settings.DEBUG) { - PlotSquared.log("Failed to find all UUIDs"); + PlotSquared.debug("Failed to find all UUIDs"); } throw new ServiceError("End of pipeline"); From 2d9cf8b7597bb7b8684fce35263813b7194874de Mon Sep 17 00:00:00 2001 From: Hannes Greule Date: Thu, 16 Jul 2020 18:04:17 +0200 Subject: [PATCH 15/49] Get placeholders working --- .../com/plotsquared/bukkit/BukkitMain.java | 12 ++++---- .../bukkit/listener/ServerListener.java | 29 +++++++++++++++++++ .../bukkit/placeholder/MVdWPlaceholders.java | 6 ++-- .../java/com/plotsquared/core/IPlotMain.java | 5 ++++ .../com/plotsquared/core/PlotSquared.java | 1 + .../placeholders/PlaceholderRegistry.java | 2 +- 6 files changed, 46 insertions(+), 9 deletions(-) create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java index 5ee38078c..fc3689dcd 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java @@ -31,12 +31,12 @@ import com.plotsquared.bukkit.listener.ChunkListener; import com.plotsquared.bukkit.listener.EntitySpawnListener; import com.plotsquared.bukkit.listener.PaperListener; import com.plotsquared.bukkit.listener.PlayerEvents; +import com.plotsquared.bukkit.listener.ServerListener; import com.plotsquared.bukkit.listener.SingleWorldListener; import com.plotsquared.bukkit.listener.WorldEvents; import com.plotsquared.bukkit.managers.BukkitWorldManager; import com.plotsquared.bukkit.managers.HyperverseWorldManager; import com.plotsquared.bukkit.managers.MultiverseWorldManager; -import com.plotsquared.bukkit.placeholder.MVdWPlaceholders; import com.plotsquared.bukkit.placeholder.PlaceholderFormatter; import com.plotsquared.bukkit.placeholder.PAPIPlaceholders; import com.plotsquared.bukkit.player.BukkitPlayerManager; @@ -371,11 +371,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain< PlotSquared.log(Captions.PREFIX + "&6PlotSquared hooked into PlaceholderAPI"); } - if (Bukkit.getPluginManager().getPlugin("MVdWPlaceholderAPI") != null) { - new MVdWPlaceholders(this, PlotSquared.get().getPlaceholderRegistry()); - PlotSquared.log(Captions.PREFIX + "&6PlotSquared hooked into MVdWPlaceholderAPI"); - } - this.startMetrics(); if (Settings.Enabled_Components.WORLDS) { TaskManager.IMP.taskRepeat(this::unload, 20); @@ -1052,6 +1047,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain< getServer().getPluginManager().registerEvents(new WorldEvents(), this); } + @Override + public void registerServerEvents() { + getServer().getPluginManager().registerEvents(new ServerListener(this), this); + } + @NotNull @Override public IndependentPlotGenerator getDefaultGenerator() { return new HybridGen(); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java new file mode 100644 index 000000000..c6f8b072e --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java @@ -0,0 +1,29 @@ +package com.plotsquared.bukkit.listener; + +import com.plotsquared.bukkit.BukkitMain; +import com.plotsquared.bukkit.placeholder.MVdWPlaceholders; +import com.plotsquared.core.PlotSquared; +import com.plotsquared.core.configuration.Captions; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.server.ServerLoadEvent; + +public class ServerListener implements Listener { + + private final BukkitMain plugin; + + public ServerListener(BukkitMain plugin) { + this.plugin = plugin; + } + + @EventHandler public void onServerLoad(ServerLoadEvent event) { + if (Bukkit.getPluginManager().getPlugin("MVdWPlaceholderAPI") != null) { + new MVdWPlaceholders(this.plugin, PlotSquared.get().getPlaceholderRegistry()); + PlotSquared.log(Captions.PREFIX + "&6PlotSquared hooked into MVdWPlaceholderAPI"); + } else { + System.out.println("Nope"); + } + + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java index 5bd835de0..599a1122b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java @@ -41,6 +41,7 @@ import org.jetbrains.annotations.NotNull; */ public class MVdWPlaceholders { + private static final String PREFIX = "plotsquared_"; private final Plugin plugin; private final PlaceholderRegistry registry; @@ -60,7 +61,7 @@ public class MVdWPlaceholders { } private void addPlaceholder(@NotNull final Placeholder placeholder) { - PlaceholderAPI.registerPlaceholder(plugin, String.format("plotsquared_%s", placeholder.getKey()), + PlaceholderAPI.registerPlaceholder(plugin, PREFIX + String.format("%s", placeholder.getKey()), placeholderReplaceEvent -> { if (!placeholderReplaceEvent.isOnline() || placeholderReplaceEvent.getPlayer() == null) { return ""; @@ -69,7 +70,8 @@ public class MVdWPlaceholders { if (player == null) { return ""; } - return registry.getPlaceholderValue(placeholderReplaceEvent.getPlaceholder(), player); + String key = placeholderReplaceEvent.getPlaceholder().substring(PREFIX.length()); + return registry.getPlaceholderValue(key, player); }); } diff --git a/Core/src/main/java/com/plotsquared/core/IPlotMain.java b/Core/src/main/java/com/plotsquared/core/IPlotMain.java index a38045acb..5dcc6d5a1 100644 --- a/Core/src/main/java/com/plotsquared/core/IPlotMain.java +++ b/Core/src/main/java/com/plotsquared/core/IPlotMain.java @@ -270,6 +270,11 @@ public interface IPlotMain

extends ILogger { */ void registerWorldEvents(); + /** + * Register events related to the server + */ + void registerServerEvents(); + /** * Usually HybridGen * diff --git a/Core/src/main/java/com/plotsquared/core/PlotSquared.java b/Core/src/main/java/com/plotsquared/core/PlotSquared.java index 3451b0a1c..f1287dbcb 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotSquared.java +++ b/Core/src/main/java/com/plotsquared/core/PlotSquared.java @@ -262,6 +262,7 @@ public class PlotSquared { this.IMP.registerPlayerEvents(); } // Required + this.IMP.registerServerEvents(); this.IMP.registerWorldEvents(); if (Settings.Enabled_Components.CHUNK_PROCESSOR) { this.IMP.registerChunkProcessor(); diff --git a/Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java index 243ca0909..d18859b2e 100644 --- a/Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java +++ b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java @@ -159,7 +159,7 @@ public final class PlaceholderRegistry { final Placeholder previous = this.placeholders .put(placeholder.getKey().toLowerCase(Locale.ENGLISH), Preconditions.checkNotNull(placeholder, "Placeholder may not be null")); - if (previous != null) { + if (previous == null) { this.eventDispatcher.callGenericEvent(new PlaceholderAddedEvent(placeholder)); } } From 10ab28c1ec3a44b9b947349c39e3feaec338b359 Mon Sep 17 00:00:00 2001 From: Hannes Greule Date: Thu, 16 Jul 2020 18:08:00 +0200 Subject: [PATCH 16/49] Add missing license headers --- .../bukkit/listener/ServerListener.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java index c6f8b072e..245393ba0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java @@ -1,3 +1,28 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ package com.plotsquared.bukkit.listener; import com.plotsquared.bukkit.BukkitMain; From 97a356c4a072ee1b96ed76162b218f8309746962 Mon Sep 17 00:00:00 2001 From: Hannes Greule Date: Thu, 16 Jul 2020 18:13:02 +0200 Subject: [PATCH 17/49] Very attentive reviewers, can recommend --- .../java/com/plotsquared/bukkit/listener/ServerListener.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java index 245393ba0..c74db87d4 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ServerListener.java @@ -46,9 +46,6 @@ public class ServerListener implements Listener { if (Bukkit.getPluginManager().getPlugin("MVdWPlaceholderAPI") != null) { new MVdWPlaceholders(this.plugin, PlotSquared.get().getPlaceholderRegistry()); PlotSquared.log(Captions.PREFIX + "&6PlotSquared hooked into MVdWPlaceholderAPI"); - } else { - System.out.println("Nope"); } - } } From ff3a94933aada14eb7b495e5c58ad4011a4c7e43 Mon Sep 17 00:00:00 2001 From: N0tMyFaultOG Date: Thu, 16 Jul 2020 18:43:52 +0200 Subject: [PATCH 18/49] Bump version --- Bukkit/pom.xml | 4 ++-- build.gradle | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index 07e1a9ca7..bba553386 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -21,7 +21,7 @@ com.plotsquared PlotSquared-Core - 5.12.5 + 5.13.0 compile @@ -87,7 +87,7 @@ be.maximvdw MVdWPlaceholderAPI - 2.1.1-SNAPSHOT + 3.1.1-SNAPSHOT compile diff --git a/build.gradle b/build.gradle index a0bae9c0c..bfd4ef86f 100644 --- a/build.gradle +++ b/build.gradle @@ -30,7 +30,7 @@ ext { git = Grgit.open(dir: new File(rootDir.toString() + "/.git")) } -def ver = "5.12.5" +def ver = "5.13.0" def versuffix = "" ext { if (project.hasProperty("versionsuffix")) { From 57435fdf349a9af989b13f9ddd70b0466370f25a Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Thu, 16 Jul 2020 23:24:11 +0100 Subject: [PATCH 19/49] verbosely ensure items cannot be duplicated when keeping inventory on death Seemingly there's duplication issues on some servers (and apparently even when only PlotSquared is installed). Likely a Spigot issue, but there's nothing to be done for Spigot on 1.13/14/15 --- .../com/plotsquared/bukkit/listener/PlayerEventListener.java | 1 + 1 file changed, 1 insertion(+) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java index 6d11cd75c..c4d7c6d90 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java @@ -1509,6 +1509,7 @@ public class PlayerEventListener extends PlotListener implements Listener { if (plot.getFlag(KeepInventoryFlag.class)) { plot.debug(event.getEntity().getName() + " kept their inventory because of keep-inventory = true"); + event.getDrops().clear(); event.setKeepInventory(true); } } From def9a1bcf84f3951a49870fbb1b6004e237a974e Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 17 Jul 2020 13:22:33 +0100 Subject: [PATCH 20/49] begin new block setting/chunk pipeline This will ultimately replace both the GlobalBlockQueue and the ChunkTask stuff --- ...nator.java => BukkitChunkCoordinator.java} | 137 +------- .../bukkit/queue/BukkitQueueCoordinator.java | 52 +++ .../inject/annotations/QueuePipeline.java | 39 +++ .../factory/QueueCoordinatorFactory.java | 36 +++ ...=> AreaBoundDelegateQueueCoordinator.java} | 16 +- .../core/queue/BasicLocalBlockQueue.java | 272 ---------------- .../core/queue/BasicQueueCoordinator.java | 135 ++++++++ ...kQueue.java => ChunkQueueCoordinator.java} | 8 +- ...eue.java => DelegateQueueCoordinator.java} | 72 +---- .../core/queue/GlobalBlockQueue.java | 298 +----------------- .../plotsquared/core/queue/LocalChunk.java | 80 +++++ ...cationOffsetDelegateQueueCoordinator.java} | 13 +- ...Queue.java => OffsetQueueCoordinator.java} | 14 +- ...lBlockQueue.java => QueueCoordinator.java} | 66 +--- .../plotsquared/core/queue/QueueProvider.java | 12 +- ...Queue.java => ScopedQueueCoordinator.java} | 10 +- 16 files changed, 436 insertions(+), 824 deletions(-) rename Bukkit/src/main/java/com/plotsquared/bukkit/queue/{ChunkCoordinator.java => BukkitChunkCoordinator.java} (65%) create mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java create mode 100644 Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java create mode 100644 Core/src/main/java/com/plotsquared/core/inject/factory/QueueCoordinatorFactory.java rename Core/src/main/java/com/plotsquared/core/queue/{AreaBoundDelegateLocalBlockQueue.java => AreaBoundDelegateQueueCoordinator.java} (85%) delete mode 100644 Core/src/main/java/com/plotsquared/core/queue/BasicLocalBlockQueue.java create mode 100644 Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java rename Core/src/main/java/com/plotsquared/core/queue/{ChunkBlockQueue.java => ChunkQueueCoordinator.java} (95%) rename Core/src/main/java/com/plotsquared/core/queue/{DelegateLocalBlockQueue.java => DelegateQueueCoordinator.java} (64%) create mode 100644 Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java rename Core/src/main/java/com/plotsquared/core/queue/{LocationOffsetDelegateLocalBlockQueue.java => LocationOffsetDelegateQueueCoordinator.java} (83%) rename Core/src/main/java/com/plotsquared/core/queue/{OffsetLocalBlockQueue.java => OffsetQueueCoordinator.java} (77%) rename Core/src/main/java/com/plotsquared/core/queue/{LocalBlockQueue.java => QueueCoordinator.java} (68%) rename Core/src/main/java/com/plotsquared/core/queue/{ScopedLocalBlockQueue.java => ScopedQueueCoordinator.java} (89%) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/ChunkCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java similarity index 65% rename from Bukkit/src/main/java/com/plotsquared/bukkit/queue/ChunkCoordinator.java rename to Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java index cc5c1f72f..ecb0f3500 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/ChunkCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java @@ -26,7 +26,7 @@ package com.plotsquared.bukkit.queue; import com.google.common.base.Preconditions; -import com.plotsquared.bukkit.BukkitMain; +import com.plotsquared.bukkit.BukkitPlatform; import com.sk89q.worldedit.math.BlockVector2; import io.papermc.lib.PaperLib; import org.bukkit.Chunk; @@ -44,34 +44,7 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; -/** - * Utility that allows for the loading and coordination of chunk actions - *

- * The coordinator takes in collection of chunk coordinates, loads them - * and allows the caller to specify a sink for the loaded chunks. The - * coordinator will prevent the chunks from being unloaded until the sink - * has fully consumed the chunk - *

- * Usage: - *

{@code
- * final ChunkCoordinator chunkCoordinator = ChunkCoordinator.builder()
- *     .inWorld(Objects.requireNonNull(Bukkit.getWorld("world"))).withChunk(BlockVector2.at(0, 0))
- *     .withConsumer(chunk -> System.out.printf("Got chunk %d;%d", chunk.getX(), chunk.getZ()))
- *     .withFinalAction(() -> System.out.println("All chunks have been loaded"))
- *     .withThrowableConsumer(throwable -> System.err.println("Something went wrong... =("))
- *     .withMaxIterationTime(25L)
- *     .build();
- * chunkCoordinator.subscribeToProgress((coordinator, progress) ->
- *     System.out.printf("Progress: %.1f", progress * 100.0f));
- * chunkCoordinator.start();
- * }
- * - * @author Alexander Söderberg - * @see #builder() To create a new coordinator instance - */ -public final class ChunkCoordinator extends BukkitRunnable { - - private final List progressSubscribers = new LinkedList<>(); +public final class BukkitChunkCoordinator extends BukkitRunnable { private final Queue requestedChunks; private final Queue availableChunks; @@ -80,48 +53,32 @@ public final class ChunkCoordinator extends BukkitRunnable { private final Consumer chunkConsumer; private final World world; private final Runnable whenDone; - private final Consumer throwableConsumer; - private final int totalSize; private AtomicInteger expectedSize; private int batchSize; - private ChunkCoordinator(final long maxIterationTime, final int initialBatchSize, + private BukkitChunkCoordinator(final long maxIterationTime, final int initialBatchSize, @NotNull final Consumer chunkConsumer, @NotNull final World world, - @NotNull final Collection requestedChunks, @NotNull final Runnable whenDone, - @NotNull final Consumer throwableConsumer) { + @NotNull final Collection requestedChunks, @NotNull final Runnable whenDone) { this.requestedChunks = new LinkedBlockingQueue<>(requestedChunks); this.availableChunks = new LinkedBlockingQueue<>(); - this.totalSize = requestedChunks.size(); - this.expectedSize = new AtomicInteger(this.totalSize); + this.expectedSize = new AtomicInteger(requestedChunks.size()); this.world = world; this.batchSize = initialBatchSize; this.chunkConsumer = chunkConsumer; this.maxIterationTime = maxIterationTime; this.whenDone = whenDone; - this.throwableConsumer = throwableConsumer; - this.plugin = JavaPlugin.getPlugin(BukkitMain.class); - } - - /** - * Create a new {@link ChunkCoordinator} instance - * - * @return Coordinator builder instance - */ - @NotNull public static ChunkCoordinatorBuilder builder() { - return new ChunkCoordinatorBuilder(); - } - - /** - * Start the coordinator instance - */ - public void start() { + this.plugin = JavaPlugin.getPlugin(BukkitPlatform.class); // Request initial batch this.requestBatch(); // Wait until next tick to give the chunks a chance to be loaded this.runTaskTimer(this.plugin, 1L, 1L); } + @NotNull public static ChunkCoordinatorBuilder builder() { + return new ChunkCoordinatorBuilder(); + } + @Override public void run() { Chunk chunk = this.availableChunks.poll(); if (chunk == null) { @@ -133,8 +90,7 @@ public final class ChunkCoordinator extends BukkitRunnable { final long start = System.currentTimeMillis(); try { this.chunkConsumer.accept(chunk); - } catch (final Throwable throwable) { - this.throwableConsumer.accept(throwable); + } catch (final Exception ignored) { } this.freeChunk(chunk); processedChunks++; @@ -147,19 +103,10 @@ public final class ChunkCoordinator extends BukkitRunnable { // Adjust batch size based on the amount of processed chunks per tick this.batchSize = processedChunks; } - - final int expected = this.expectedSize.addAndGet(-processedChunks); - - final float progress = ((float) totalSize - (float) expected) / (float) totalSize; - for (final ProgressSubscriber subscriber : this.progressSubscribers) { - subscriber.notifyProgress(this, progress); - } - - if (expected <= 0) { + if (this.expectedSize.addAndGet(-processedChunks) <= 0) { try { this.whenDone.run(); - } catch (final Throwable throwable) { - this.throwableConsumer.accept(throwable); + } catch (final Exception ignored) { } this.cancel(); } else { @@ -203,52 +150,10 @@ public final class ChunkCoordinator extends BukkitRunnable { chunk.removePluginChunkTicket(this.plugin); } - /** - * Get the amount of remaining chunks (at the time of the method call) - * - * @return Snapshot view of remaining chunk count - */ - public int getRemainingChunks() { - return this.expectedSize.get(); - } - - /** - * Get the amount of requested chunks - * - * @return Requested chunk count - */ - public int getTotalChunks() { - return this.totalSize; - } - - /** - * Subscribe to coordinator progress updates - * - * @param subscriber Subscriber - */ - public void subscribeToProgress(@NotNull final ChunkCoordinator.ProgressSubscriber subscriber) { - this.progressSubscribers.add(subscriber); - } - - - @FunctionalInterface - public interface ProgressSubscriber { - - /** - * Notify about a progress update in the coordinator - * - * @param coordinator Coordinator instance that triggered the notification - * @param progress Progress in the range [0, 1] - */ - void notifyProgress(@NotNull final ChunkCoordinator coordinator, final float progress); - - } - public static final class ChunkCoordinatorBuilder { private final List requestedChunks = new LinkedList<>(); - private Consumer throwableConsumer = Throwable::printStackTrace; private World world; private Consumer chunkConsumer; private Runnable whenDone = () -> { @@ -303,22 +208,12 @@ public final class ChunkCoordinator extends BukkitRunnable { return this; } - @NotNull public ChunkCoordinatorBuilder withThrowableConsumer( - @NotNull final Consumer throwableConsumer) { - this.throwableConsumer = - Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null"); - return this; - } - - @NotNull public ChunkCoordinator build() { + @NotNull public BukkitChunkCoordinator build() { Preconditions.checkNotNull(this.world, "No world was supplied"); Preconditions.checkNotNull(this.chunkConsumer, "No chunk consumer was supplied"); Preconditions.checkNotNull(this.whenDone, "No final action was supplied"); - Preconditions - .checkNotNull(this.throwableConsumer, "No throwable consumer was supplied"); - return new ChunkCoordinator(this.maxIterationTime, this.initialBatchSize, - this.chunkConsumer, this.world, this.requestedChunks, this.whenDone, - this.throwableConsumer); + return new BukkitChunkCoordinator(this.maxIterationTime, this.initialBatchSize, + this.chunkConsumer, this.world, this.requestedChunks, this.whenDone); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java new file mode 100644 index 000000000..9dce356c5 --- /dev/null +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -0,0 +1,52 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.bukkit.queue; + +import com.plotsquared.bukkit.util.BukkitBlockUtil; +import com.plotsquared.core.queue.BasicQueueCoordinator; +import com.plotsquared.core.util.BlockUtil; +import com.sk89q.worldedit.world.block.BlockState; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.block.Block; + +public class BukkitQueueCoordinator extends BasicQueueCoordinator { + + public BukkitQueueCoordinator(String world) { + super(world); + } + + @Override public BlockState getBlock(int x, int y, int z) { + World worldObj = Bukkit.getWorld(getWorld()); + if (worldObj != null) { + Block block = worldObj.getBlockAt(x, y, z); + return BukkitBlockUtil.get(block); + } else { + return BlockUtil.get(0, 0); + } + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java b/Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java new file mode 100644 index 000000000..96ce1e242 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java @@ -0,0 +1,39 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.core.inject.annotations; + +import com.google.inject.BindingAnnotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.PARAMETER, ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@BindingAnnotation +public @interface QueuePipeline { +} diff --git a/Core/src/main/java/com/plotsquared/core/inject/factory/QueueCoordinatorFactory.java b/Core/src/main/java/com/plotsquared/core/inject/factory/QueueCoordinatorFactory.java new file mode 100644 index 000000000..969ceed3b --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/inject/factory/QueueCoordinatorFactory.java @@ -0,0 +1,36 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.core.inject.factory; + +import com.plotsquared.core.queue.QueueCoordinator; + +import javax.annotation.Nonnull; + +public interface QueueCoordinatorFactory { + + @Nonnull QueueCoordinator create(); + +} diff --git a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateLocalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java similarity index 85% rename from Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateLocalBlockQueue.java rename to Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java index 75de960f1..ac427471d 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateLocalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java @@ -26,22 +26,23 @@ package com.plotsquared.core.queue; import com.plotsquared.core.plot.PlotArea; +import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import lombok.Getter; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Objects; -public class AreaBoundDelegateLocalBlockQueue extends DelegateLocalBlockQueue { +public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator { @Getter private final PlotArea area; - public AreaBoundDelegateLocalBlockQueue(@Nonnull final PlotArea area, - @Nullable final LocalBlockQueue parent) { + public AreaBoundDelegateQueueCoordinator(@Nonnull final PlotArea area, + @Nullable final QueueCoordinator parent) { super(parent); this.area = Objects.requireNonNull(area); } @@ -74,4 +75,11 @@ public class AreaBoundDelegateLocalBlockQueue extends DelegateLocalBlockQueue { return false; } + @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { + if (area.contains(x, z)) { + return super.setTile(x, y, z, tag); + } + return false; + } + } diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicLocalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/BasicLocalBlockQueue.java deleted file mode 100644 index e2bdd37e6..000000000 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicLocalBlockQueue.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2020 IntellectualSites - * - * 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, see . - */ -package com.plotsquared.core.queue; - -import com.plotsquared.core.util.MainUtil; -import com.plotsquared.core.util.MathMan; -import com.plotsquared.core.util.PatternUtil; -import com.plotsquared.core.util.task.RunnableVal; -import com.plotsquared.core.util.task.TaskManager; -import com.sk89q.worldedit.function.pattern.Pattern; -import com.sk89q.worldedit.world.biome.BiomeType; -import com.sk89q.worldedit.world.block.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; -import javax.annotation.Nonnull; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedDeque; -import java.util.concurrent.ExecutionException; - -public abstract class BasicLocalBlockQueue extends LocalBlockQueue { - - private final String world; - private final ConcurrentHashMap blockChunks = new ConcurrentHashMap<>(); - private final ConcurrentLinkedDeque chunks = new ConcurrentLinkedDeque<>(); - private long modified; - private LocalChunk lastWrappedChunk; - private int lastX = Integer.MIN_VALUE; - private int lastZ = Integer.MIN_VALUE; - private boolean setbiome = false; - - private GlobalBlockQueue globalBlockQueue; - - public BasicLocalBlockQueue(String world) { - super(world); - this.world = world; - this.modified = System.currentTimeMillis(); - } - - public abstract LocalChunk getLocalChunk(int x, int z); - - @Override public abstract BlockState getBlock(int x, int y, int z); - - public abstract void setComponents(LocalChunk lc) - throws ExecutionException, InterruptedException; - - @Override public final String getWorld() { - return world; - } - - @Override public final boolean next() { - lastX = Integer.MIN_VALUE; - lastZ = Integer.MIN_VALUE; - try { - if (this.blockChunks.size() == 0) { - return false; - } - synchronized (blockChunks) { - LocalChunk chunk = chunks.poll(); - if (chunk != null) { - blockChunks.remove(chunk.longHash()); - return this.execute(chunk); - } - } - } catch (Throwable e) { - e.printStackTrace(); - } - return false; - } - - public final boolean execute(@Nonnull LocalChunk lc) - throws ExecutionException, InterruptedException { - this.setComponents(lc); - return true; - } - - @Override public void startSet(boolean parallel) { - // Do nothing - } - - @Override public void endSet(boolean parallel) { - // Do nothing - } - - @Override public final int size() { - return chunks.size(); - } - - @Override public final long getModified() { - return modified; - } - - @Override public final void setModified(long modified) { - this.modified = modified; - } - - @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { - return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z)); - } - - @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { - if ((y > 255) || (y < 0)) { - return false; - } - int cx = x >> 4; - int cz = z >> 4; - if (cx != lastX || cz != lastZ) { - lastX = cx; - lastZ = cz; - long pair = (long) (cx) << 32 | (cz) & 0xFFFFFFFFL; - lastWrappedChunk = this.blockChunks.get(pair); - if (lastWrappedChunk == null) { - lastWrappedChunk = this.getLocalChunk(x >> 4, z >> 4); - lastWrappedChunk.setBlock(x & 15, y, z & 15, id); - LocalChunk previous = this.blockChunks.put(pair, lastWrappedChunk); - if (previous == null) { - return chunks.add(lastWrappedChunk); - } - this.blockChunks.put(pair, previous); - lastWrappedChunk = previous; - } - } - lastWrappedChunk.setBlock(x & 15, y, z & 15, id); - return true; - } - - @Override public boolean setBlock(int x, int y, int z, BlockState id) { - // Trying to mix BlockState and BaseBlock leads to all kinds of issues. - // Since BaseBlock has more features than BlockState, simply convert - // all BlockStates to BaseBlocks - return setBlock(x, y, z, id.toBaseBlock()); - } - - @Override public final boolean setBiome(int x, int z, BiomeType biomeType) { - long pair = (long) (x >> 4) << 32 | (z >> 4) & 0xFFFFFFFFL; - LocalChunk result = this.blockChunks.get(pair); - if (result == null) { - result = this.getLocalChunk(x >> 4, z >> 4); - LocalChunk previous = this.blockChunks.put(pair, result); - if (previous != null) { - this.blockChunks.put(pair, previous); - result = previous; - } else { - chunks.add(result); - } - } - result.setBiome(x & 15, z & 15, biomeType); - setbiome = true; - return true; - } - - @Override public final boolean setBiome() { - return setbiome; - } - - public final void setChunk(LocalChunk chunk) { - LocalChunk previous = this.blockChunks.put(chunk.longHash(), chunk); - if (previous != null) { - chunks.remove(previous); - } - chunks.add(chunk); - } - - @Override public void flush() { - this.globalBlockQueue.dequeue(this); - TaskManager.getImplementation().sync(new RunnableVal() { - @Override public void run(Object value) { - while (next()) { - } - } - }); - } - - - public abstract class LocalChunk { - public final BasicLocalBlockQueue parent; - public final int z; - public final int x; - - public BaseBlock[][] baseblocks; - public BiomeType[][] biomes; - - public LocalChunk(BasicLocalBlockQueue parent, int x, int z) { - this.parent = parent; - this.x = x; - this.z = z; - } - - /** - * Get the parent queue this chunk belongs to - * - * @return - */ - public BasicLocalBlockQueue getParent() { - return parent; - } - - public int getX() { - return x; - } - - public int getZ() { - return z; - } - - public abstract void setBlock(final int x, final int y, final int z, final BaseBlock block); - - public void setBiome(int x, int z, BiomeType biomeType) { - if (this.biomes == null) { - this.biomes = new BiomeType[16][]; - } - BiomeType[] index = this.biomes[x]; - if (index == null) { - index = this.biomes[x] = new BiomeType[16]; - } - index[z] = biomeType; - } - - public long longHash() { - return MathMan.pairInt(x, z); - } - - @Override public int hashCode() { - return MathMan.pair((short) x, (short) z); - } - } - - - public class BasicLocalChunk extends LocalChunk { - - public BasicLocalChunk(BasicLocalBlockQueue parent, int x, int z) { - super(parent, x, z); - baseblocks = new BaseBlock[16][]; - } - - @Override public void setBlock(int x, int y, int z, BaseBlock block) { - this.setInternal(x, y, z, block); - } - - private void setInternal(final int x, final int y, final int z, final BaseBlock baseBlock) { - final int i = MainUtil.CACHE_I[y][x][z]; - final int j = MainUtil.CACHE_J[y][x][z]; - BaseBlock[] array = baseblocks[i]; - if (array == null) { - array = (baseblocks[i] = new BaseBlock[4096]); - } - array[j] = baseBlock; - } - } -} diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java new file mode 100644 index 000000000..e22376fd3 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -0,0 +1,135 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.core.queue; + +import com.plotsquared.core.util.PatternUtil; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; + +import javax.annotation.Nonnull; +import java.util.concurrent.ConcurrentHashMap; + +public abstract class BasicQueueCoordinator extends QueueCoordinator { + + private final String world; + private final ConcurrentHashMap blockChunks = new ConcurrentHashMap<>(); + private long modified; + private LocalChunk lastWrappedChunk; + private int lastX = Integer.MIN_VALUE; + private int lastZ = Integer.MIN_VALUE; + private boolean setbiome = false; + + private GlobalBlockQueue globalBlockQueue; + + public BasicQueueCoordinator(String world) { + this.world = world; + this.modified = System.currentTimeMillis(); + } + + public LocalChunk getLocalChunk(int x, int z) { + return new LocalChunk(this, x, z) { + // Allow implementation-specific custom stuff here + }; + } + + @Override public abstract BlockState getBlock(int x, int y, int z); + + @Override public final String getWorld() { + return world; + } + + @Override public final int size() { + return blockChunks.size(); + } + + @Override public final void setModified(long modified) { + this.modified = modified; + } + + @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { + return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z)); + } + + @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { + if ((y > 255) || (y < 0)) { + return false; + } + LocalChunk chunk = getChunk(x >> 4, z >> 4); + chunk.setBlock(x & 15, y, z & 15, id); + return true; + } + + @Override public boolean setBlock(int x, int y, int z, BlockState id) { + // Trying to mix BlockState and BaseBlock leads to all kinds of issues. + // Since BaseBlock has more features than BlockState, simply convert + // all BlockStates to BaseBlocks + return setBlock(x, y, z, id.toBaseBlock()); + } + + @Override public final boolean setBiome(int x, int z, BiomeType biomeType) { + LocalChunk chunk = getChunk(x >> 4, z >> 4); + chunk.setBiome(x & 15, z & 15, biomeType); + setbiome = true; + return true; + } + + @Override public final boolean setTile(int x, int y, int z, CompoundTag tag) { + LocalChunk chunk = getChunk(x >> 4, z >> 4); + chunk.setTile(x, y, z, tag); + return true; + } + + @Override public final boolean settingBiome() { + return setbiome; + } + + public final void setChunk(LocalChunk chunk) { + this.blockChunks.put(chunk.longHash(), chunk); + } + + private LocalChunk getChunk(final int chunkX, final int ChunkZ) { + if (chunkX != lastX || ChunkZ != lastZ) { + lastX = chunkX; + lastZ = ChunkZ; + long pair = (long) (chunkX) << 32 | (ChunkZ) & 0xFFFFFFFFL; + lastWrappedChunk = this.blockChunks.get(pair); + if (lastWrappedChunk == null) { + lastWrappedChunk = this.getLocalChunk(chunkX, ChunkZ); + LocalChunk previous = this.blockChunks.put(pair, lastWrappedChunk); + if (previous == null) { + return lastWrappedChunk; + } + lastWrappedChunk = previous; + } + } + return lastWrappedChunk; + } + + +} diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java similarity index 95% rename from Core/src/main/java/com/plotsquared/core/queue/ChunkBlockQueue.java rename to Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java index fcd40d26e..59daca67c 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java @@ -31,26 +31,24 @@ import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; + import javax.annotation.Nonnull; import javax.annotation.Nullable; - import java.util.Arrays; -public class ChunkBlockQueue extends ScopedLocalBlockQueue { +public class ChunkQueueCoordinator extends ScopedQueueCoordinator { public final BiomeType[] biomeGrid; public final BlockState[][][] result; private final int width; private final int length; - @Deprecated private final int area; private final BlockVector3 bot; private final BlockVector3 top; - public ChunkBlockQueue(BlockVector3 bot, BlockVector3 top, boolean biomes) { + public ChunkQueueCoordinator(BlockVector3 bot, BlockVector3 top, boolean biomes) { super(null, Location.at("", 0, 0, 0), Location.at("", 15, 255, 15)); this.width = top.getX() - bot.getX() + 1; this.length = top.getZ() - bot.getZ() + 1; - this.area = width * length; this.result = new BlockState[256][][]; this.biomeGrid = biomes ? new BiomeType[width * length] : null; this.bot = bot; diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateLocalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java similarity index 64% rename from Core/src/main/java/com/plotsquared/core/queue/DelegateLocalBlockQueue.java rename to Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index 22176671c..5712d5694 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateLocalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -25,45 +25,32 @@ */ package com.plotsquared.core.queue; +import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import lombok.Getter; +import lombok.Setter; -public class DelegateLocalBlockQueue extends LocalBlockQueue { +import javax.annotation.Nullable; - private final LocalBlockQueue parent; +public class DelegateQueueCoordinator extends QueueCoordinator { - public DelegateLocalBlockQueue(LocalBlockQueue parent) { - super(parent == null ? null : parent.getWorld()); + private final QueueCoordinator parent; + + public DelegateQueueCoordinator(QueueCoordinator parent) { this.parent = parent; if (parent != null) { this.setForceSync(parent.isForceSync()); - this.setChunkObject(parent.getChunkObject()); } } - public LocalBlockQueue getParent() { + public QueueCoordinator getParent() { return parent; } - @Override public boolean next() { - return parent.next(); - } - - @Override public void startSet(boolean parallel) { - if (parent != null) { - parent.startSet(parallel); - } - } - - @Override public void endSet(boolean parallel) { - if (parent != null) { - parent.endSet(parallel); - } - } - @Override public int size() { if (parent != null) { return parent.size(); @@ -71,19 +58,6 @@ public class DelegateLocalBlockQueue extends LocalBlockQueue { return 0; } - @Override public void optimize() { - if (parent != null) { - parent.optimize(); - } - } - - @Override public long getModified() { - if (parent != null) { - return parent.getModified(); - } - return 0; - } - @Override public void setModified(long modified) { if (parent != null) { parent.setModified(modified); @@ -110,36 +84,16 @@ public class DelegateLocalBlockQueue extends LocalBlockQueue { return parent.setBiome(x, z, biome); } - @Override public boolean setBiome() { - return parent.setBiome(); + @Override public boolean settingBiome() { + return parent.settingBiome(); } @Override public String getWorld() { return parent.getWorld(); } - @Override public void flush() { - if (parent != null) { - parent.flush(); - } - } - - @Override public void refreshChunk(int x, int z) { - if (parent != null) { - parent.refreshChunk(x, z); - } - } - - @Override public void fixChunkLighting(int x, int z) { - if (parent != null) { - parent.fixChunkLighting(x, z); - } - } - - @Override public void regenChunk(int x, int z) { - if (parent != null) { - parent.regenChunk(x, z); - } + @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { + return parent.setTile(x, y, z, tag); } @Override public boolean enqueue() { diff --git a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java index 9f79102b0..a450ef045 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java @@ -25,169 +25,21 @@ */ package com.plotsquared.core.queue; -import com.plotsquared.core.PlotSquared; -import com.plotsquared.core.util.task.RunnableVal2; -import com.plotsquared.core.util.task.TaskManager; +import lombok.Getter; +import lombok.Setter; import java.util.ArrayList; -import java.util.ConcurrentModificationException; -import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; -import java.util.concurrent.atomic.AtomicBoolean; public class GlobalBlockQueue { - private final int PARALLEL_THREADS; - private final ConcurrentLinkedDeque activeQueues; - private final ConcurrentLinkedDeque inactiveQueues; - private final ConcurrentLinkedDeque runnables; - private final AtomicBoolean running; - private final int targetTime; - private QueueProvider provider; - /** - * Used to calculate elapsed time in milliseconds and ensure block placement doesn't lag the - * server - */ - private long last; - private long secondLast; - private long lastSuccess; - private double lastPeriod = 0; - private final RunnableVal2 SET_TASK = - new RunnableVal2() { - @Override public void run(Long free, LocalBlockQueue queue) { - do { - boolean more = queue.next(); - if (!more) { - lastSuccess = last; - if (inactiveQueues.size() == 0 && activeQueues.size() == 0) { - runEmptyTasks(); - } - return; - } - } while ((lastPeriod = - ((GlobalBlockQueue.this.secondLast = System.currentTimeMillis()) - - GlobalBlockQueue.this.last)) < free); - } - }; + private final ConcurrentLinkedDeque activeQueues; + @Getter @Setter private QueueProvider provider; - public GlobalBlockQueue(QueueProvider provider, int threads, int targetTime) { + public GlobalBlockQueue(QueueProvider provider) { this.provider = provider; this.activeQueues = new ConcurrentLinkedDeque<>(); - this.inactiveQueues = new ConcurrentLinkedDeque<>(); - this.runnables = new ConcurrentLinkedDeque<>(); - this.running = new AtomicBoolean(); - this.targetTime = targetTime; - this.PARALLEL_THREADS = threads; - } - - public QueueProvider getProvider() { - return provider; - } - - public void setProvider(QueueProvider provider) { - this.provider = provider; - } - - public LocalBlockQueue getNewQueue(String world, boolean autoQueue) { - LocalBlockQueue queue = provider.getNewQueue(world); - // Auto-inject into the queue - PlotSquared.platform().getInjector().injectMembers(queue); - if (autoQueue) { - inactiveQueues.add(queue); - } - return queue; - } - - public boolean stop() { - if (!running.get()) { - return false; - } - running.set(false); - return true; - } - - public boolean runTask() { - if (running.get()) { - return false; - } - running.set(true); - TaskManager.runTaskRepeat(new Runnable() { - @Override public void run() { - if (inactiveQueues.isEmpty() && activeQueues.isEmpty()) { - lastSuccess = System.currentTimeMillis(); - lastPeriod = 0; - GlobalBlockQueue.this.runEmptyTasks(); - return; - } - // Server laggy? Skip. - if (lastPeriod > targetTime) { - lastPeriod -= targetTime; - return; - } - SET_TASK.value1 = 50 + Math.min( - (50 + GlobalBlockQueue.this.last) - (GlobalBlockQueue.this.last = - System.currentTimeMillis()), - GlobalBlockQueue.this.secondLast - System.currentTimeMillis()); - SET_TASK.value2 = GlobalBlockQueue.this.getNextQueue(); - if (SET_TASK.value2 == null) { - return; - } - if (!PlotSquared.get().isMainThread(Thread.currentThread())) { - throw new IllegalStateException( - "This shouldn't be possible for placement to occur off the main thread"); - } - // Disable the async catcher as it can't discern async vs parallel - SET_TASK.value2.startSet(true); - try { - if (PARALLEL_THREADS <= 1) { - SET_TASK.run(); - } else { - ArrayList threads = new ArrayList<>(); - for (int i = 0; i < PARALLEL_THREADS; i++) { - threads.add(new Thread(SET_TASK)); - } - for (Thread thread : threads) { - thread.start(); - } - for (Thread thread : threads) { - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } catch (Throwable e) { - e.printStackTrace(); - } finally { - // Enable it again (note that we are still on the main thread) - SET_TASK.value2.endSet(true); - } - } - }, 1); - return true; - } - - public QueueStage getStage(LocalBlockQueue queue) { - if (activeQueues.contains(queue)) { - return QueueStage.ACTIVE; - } else if (inactiveQueues.contains(queue)) { - return QueueStage.INACTIVE; - } - return QueueStage.NONE; - } - - public boolean isStage(LocalBlockQueue queue, QueueStage stage) { - switch (stage) { - case ACTIVE: - return activeQueues.contains(queue); - case INACTIVE: - return inactiveQueues.contains(queue); - case NONE: - return !activeQueues.contains(queue) && !inactiveQueues.contains(queue); - } - return false; } /** @@ -196,155 +48,23 @@ public class GlobalBlockQueue { * @param queue todo * @return true if added to queue, false otherwise */ - public boolean enqueue(LocalBlockQueue queue) { + public boolean enqueue(QueueCoordinator queue) { boolean success = false; - success = inactiveQueues.remove(queue); if (queue.size() > 0 && !activeQueues.contains(queue)) { - queue.optimize(); success = activeQueues.add(queue); } return success; } - public void dequeue(LocalBlockQueue queue) { - inactiveQueues.remove(queue); + public void dequeue(QueueCoordinator queue) { activeQueues.remove(queue); } - public List getAllQueues() { - ArrayList list = - new ArrayList<>(activeQueues.size() + inactiveQueues.size()); - list.addAll(inactiveQueues); - list.addAll(activeQueues); - return list; - } - - public List getActiveQueues() { + public List getActiveQueues() { return new ArrayList<>(activeQueues); } - public List getInactiveQueues() { - return new ArrayList<>(inactiveQueues); - } - - public void flush(LocalBlockQueue queue) { - SET_TASK.value1 = Long.MAX_VALUE; - SET_TASK.value2 = queue; - if (SET_TASK.value2 == null) { - return; - } - if (PlotSquared.get().isMainThread(Thread.currentThread())) { - throw new IllegalStateException("Must be flushed on the main thread!"); - } - // Disable the async catcher as it can't discern async vs parallel - SET_TASK.value2.startSet(true); - try { - if (PARALLEL_THREADS <= 1) { - SET_TASK.run(); - } else { - ArrayList threads = new ArrayList<>(); - for (int i = 0; i < PARALLEL_THREADS; i++) { - Thread thread = new Thread(SET_TASK); - thread.setName("PlotSquared Flush Task"); - threads.add(thread); - } - for (Thread thread : threads) { - thread.start(); - } - for (Thread thread : threads) { - try { - thread.join(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } catch (Throwable e) { - e.printStackTrace(); - } finally { - // Enable it again (note that we are still on the main thread) - SET_TASK.value2.endSet(true); - dequeue(queue); - } - } - - public LocalBlockQueue getNextQueue() { - long now = System.currentTimeMillis(); - while (!activeQueues.isEmpty()) { - LocalBlockQueue queue = activeQueues.peek(); - if (queue != null && queue.size() > 0) { - queue.setModified(now); - return queue; - } else { - activeQueues.poll(); - } - } - int size = inactiveQueues.size(); - if (size > 0) { - Iterator iter = inactiveQueues.iterator(); - try { - int total = 0; - LocalBlockQueue firstNonEmpty = null; - while (iter.hasNext()) { - LocalBlockQueue queue = iter.next(); - long age = now - queue.getModified(); - total += queue.size(); - if (queue.size() == 0) { - if (age > 60000) { - iter.remove(); - } - continue; - } - if (firstNonEmpty == null) { - firstNonEmpty = queue; - } - if (total > 64) { - firstNonEmpty.setModified(now); - return firstNonEmpty; - } - if (age > 1000) { - queue.setModified(now); - return queue; - } - } - } catch (ConcurrentModificationException e) { - e.printStackTrace(); - } - } - return null; - } - public boolean isDone() { - return activeQueues.size() == 0 && inactiveQueues.size() == 0; - } - - public boolean addEmptyTask(final Runnable whenDone) { - if (this.isDone()) { - // Run - this.runEmptyTasks(); - if (whenDone != null) { - whenDone.run(); - } - return true; - } - if (whenDone != null) { - this.runnables.add(whenDone); - } - return false; - } - - private synchronized void runEmptyTasks() { - if (this.runnables.isEmpty()) { - return; - } - final ConcurrentLinkedDeque tmp = new ConcurrentLinkedDeque<>(this.runnables); - this.runnables.clear(); - for (final Runnable runnable : tmp) { - runnable.run(); - } - } - - public enum QueueStage { - INACTIVE, ACTIVE, NONE + return activeQueues.size() == 0; } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java new file mode 100644 index 000000000..99975cae6 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java @@ -0,0 +1,80 @@ +package com.plotsquared.core.queue; + +import com.plotsquared.core.util.MainUtil; +import com.plotsquared.core.util.MathMan; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.block.BaseBlock; + +import java.util.HashMap; + +public class LocalChunk { + public final BasicQueueCoordinator parent; + public final int z; + public final int x; + + public BaseBlock[][] baseblocks; + public BiomeType[][] biomes; + public HashMap tiles = null; + + public LocalChunk(BasicQueueCoordinator parent, int x, int z) { + this.parent = parent; + this.x = x; + this.z = z; + baseblocks = new BaseBlock[16][]; + } + + /** + * Get the parent queue this chunk belongs to + * + * @return + */ + public BasicQueueCoordinator getParent() { + return parent; + } + + public int getX() { + return x; + } + + public int getZ() { + return z; + } + + public void setBiome(int x, int z, BiomeType biomeType) { + if (this.biomes == null) { + this.biomes = new BiomeType[16][]; + } + BiomeType[] index = this.biomes[x]; + if (index == null) { + index = this.biomes[x] = new BiomeType[16]; + } + index[z] = biomeType; + } + + public long longHash() { + return MathMan.pairInt(x, z); + } + + @Override public int hashCode() { + return MathMan.pair((short) x, (short) z); + } + + public void setBlock(final int x, final int y, final int z, final BaseBlock baseBlock) { + final int i = MainUtil.CACHE_I[y][x][z]; + final int j = MainUtil.CACHE_J[y][x][z]; + BaseBlock[] array = baseblocks[i]; + if (array == null) { + array = (baseblocks[i] = new BaseBlock[4096]); + } + array[j] = baseBlock; + } + + public void setTile(final int x, final int y, final int z, final CompoundTag tag) { + if (tiles == null) { + tiles = new HashMap<>(); + } + tiles.put(BlockVector3.at(x, y, z), tag); + } +} diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateLocalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java similarity index 83% rename from Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateLocalBlockQueue.java rename to Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java index eefae99d3..3b067e8ca 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateLocalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java @@ -25,6 +25,7 @@ */ package com.plotsquared.core.queue; +import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BiomeType; @@ -35,16 +36,17 @@ import org.slf4j.LoggerFactory; import javax.annotation.Nullable; -public class LocationOffsetDelegateLocalBlockQueue extends DelegateLocalBlockQueue { +public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordinator { - private static final Logger logger = LoggerFactory.getLogger("P2/" + LocationOffsetDelegateLocalBlockQueue.class.getSimpleName()); + private static final Logger logger = LoggerFactory + .getLogger("P2/" + LocationOffsetDelegateQueueCoordinator.class.getSimpleName()); private final boolean[][] canPlace; private final int blockX; private final int blockZ; - public LocationOffsetDelegateLocalBlockQueue(final boolean[][] canPlace, final int blockX, - final int blockZ, @Nullable LocalBlockQueue parent) { + public LocationOffsetDelegateQueueCoordinator(final boolean[][] canPlace, final int blockX, + final int blockZ, @Nullable QueueCoordinator parent) { super(parent); this.canPlace = canPlace; this.blockX = blockX; @@ -78,4 +80,7 @@ public class LocationOffsetDelegateLocalBlockQueue extends DelegateLocalBlockQue return super.setBiome(x, y, biome); } + @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { + return super.setTile(x, y, z, tag); + } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/OffsetLocalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java similarity index 77% rename from Core/src/main/java/com/plotsquared/core/queue/OffsetLocalBlockQueue.java rename to Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java index 06233277d..78b945c7b 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/OffsetLocalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java @@ -25,15 +25,17 @@ */ package com.plotsquared.core.queue; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; -public class OffsetLocalBlockQueue extends DelegateLocalBlockQueue { +public class OffsetQueueCoordinator extends DelegateQueueCoordinator { private final int ox; private final int oy; private final int oz; - public OffsetLocalBlockQueue(LocalBlockQueue parent, int ox, int oy, int oz) { + public OffsetQueueCoordinator(QueueCoordinator parent, int ox, int oy, int oz) { super(parent); this.ox = ox; this.oy = oy; @@ -47,4 +49,12 @@ public class OffsetLocalBlockQueue extends DelegateLocalBlockQueue { @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { return super.setBlock(ox + x, oy + y, oz + z, id); } + + @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { + return super.setBlock(ox + x, oy + y, oz + z, pattern); + } + + @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { + return super.setTile(ox + x, oy + y, oz + z, tag); + } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java similarity index 68% rename from Core/src/main/java/com/plotsquared/core/queue/LocalBlockQueue.java rename to Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index 1f2ccb995..df537d909 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -28,59 +28,31 @@ package com.plotsquared.core.queue; import com.google.inject.Inject; import com.plotsquared.core.PlotSquared; import com.plotsquared.core.location.Location; -import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.util.PatternUtil; -import com.plotsquared.core.util.SchematicHandler; -import com.plotsquared.core.util.StringMan; -import com.plotsquared.core.util.WorldUtil; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.function.pattern.Pattern; -import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import lombok.Getter; import lombok.Setter; + import javax.annotation.Nonnull; import javax.annotation.Nullable; -public abstract class LocalBlockQueue { +public abstract class QueueCoordinator { @Getter @Setter private boolean forceSync = false; @Getter @Setter @Nullable private Object chunkObject; - @Inject private SchematicHandler schematicHandler; - @Inject private WorldUtil worldUtil; @Inject private GlobalBlockQueue blockQueue; - /** - * Needed for compatibility with FAWE. - * - * @param world unused - */ - @Deprecated public LocalBlockQueue(String world) { + public QueueCoordinator() { PlotSquared.platform().getInjector().injectMembers(this); } - public ScopedLocalBlockQueue getForChunk(int x, int z) { - int bx = x << 4; - int bz = z << 4; - return new ScopedLocalBlockQueue(this, Location.at(getWorld(), bx, 0, bz), - Location.at(getWorld(), bx + 15, 255, bz + 255)); - } - - public abstract boolean next(); - - public abstract void startSet(boolean parallel); - - public abstract void endSet(boolean parallel); - public abstract int size(); - public abstract void optimize(); - - public abstract long getModified(); - public abstract void setModified(long modified); /** @@ -99,48 +71,22 @@ public abstract class LocalBlockQueue { return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z)); } - public boolean setTile(int x, int y, int z, CompoundTag tag) { - this.schematicHandler.restoreTile(this, tag, x, y, z); - return true; - } + public abstract boolean setTile(int x, int y, int z, CompoundTag tag); public abstract BlockState getBlock(int x, int y, int z); public abstract boolean setBiome(int x, int z, BiomeType biome); - public abstract boolean setBiome(); + public abstract boolean settingBiome(); public abstract String getWorld(); - public abstract void flush(); - public final void setModified() { setModified(System.currentTimeMillis()); } - public abstract void refreshChunk(int x, int z); - - public abstract void fixChunkLighting(int x, int z); - - public abstract void regenChunk(int x, int z); - - public final void regenChunkSafe(int x, int z) { - regenChunk(x, z); - fixChunkLighting(x, z); - BlockVector2 loc = BlockVector2.at(x, z); - - for (final PlotPlayer pp : PlotSquared.platform().getPlayerManager().getPlayers()) { - Location pLoc = pp.getLocation(); - if (!StringMan.isEqual(getWorld(), pLoc.getWorldName()) || !pLoc.getChunkLocation() - .equals(loc)) { - continue; - } - pp.teleport(pLoc.withY(this.worldUtil.getHighestBlockSynchronous(getWorld(), pLoc.getX(), pLoc.getZ()))); - } - } - public boolean enqueue() { - return blockQueue.enqueue(this); + return this.blockQueue.enqueue(this); } public void setCuboid(Location pos1, Location pos2, BlockState block) { diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java index 2fee2fa99..207b29ee0 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java @@ -26,23 +26,23 @@ package com.plotsquared.core.queue; public abstract class QueueProvider { - public static QueueProvider of(final Class primary, - final Class fallback) { + public static QueueProvider of(final Class primary, + final Class fallback) { return new QueueProvider() { private boolean failed = false; - @Override public LocalBlockQueue getNewQueue(String world) { + @Override public QueueCoordinator getNewQueue(String world) { if (!failed) { try { - return (LocalBlockQueue) primary.getConstructors()[0].newInstance(world); + return (QueueCoordinator) primary.getConstructors()[0].newInstance(world); } catch (Throwable e) { e.printStackTrace(); failed = true; } } try { - return (LocalBlockQueue) fallback.getConstructors()[0].newInstance(world); + return (QueueCoordinator) fallback.getConstructors()[0].newInstance(world); } catch (Throwable e) { e.printStackTrace(); } @@ -51,5 +51,5 @@ public abstract class QueueProvider { }; } - public abstract LocalBlockQueue getNewQueue(String world); + public abstract QueueCoordinator getNewQueue(String world); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ScopedLocalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java similarity index 89% rename from Core/src/main/java/com/plotsquared/core/queue/ScopedLocalBlockQueue.java rename to Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java index fc43e1ce0..49631dceb 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ScopedLocalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java @@ -26,12 +26,13 @@ package com.plotsquared.core.queue; import com.plotsquared.core.location.Location; +import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -public class ScopedLocalBlockQueue extends DelegateLocalBlockQueue { +public class ScopedQueueCoordinator extends DelegateQueueCoordinator { private final int minX; private final int minY; private final int minZ; @@ -44,7 +45,7 @@ public class ScopedLocalBlockQueue extends DelegateLocalBlockQueue { private final int dy; private final int dz; - public ScopedLocalBlockQueue(LocalBlockQueue parent, Location min, Location max) { + public ScopedQueueCoordinator(QueueCoordinator parent, Location min, Location max) { super(parent); this.minX = min.getX(); this.minY = min.getY(); @@ -86,6 +87,11 @@ public class ScopedLocalBlockQueue extends DelegateLocalBlockQueue { .setBlock(x + minX, y + minY, z + minZ, pattern); } + @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { + return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super + .setTile(x + minX, y + minY, z + minZ, tag); + } + public Location getMin() { return Location.at(this.getWorld(), this.minX, this.minY, this.minZ); } From 09aca839a802c64d656a961143ba79ce09cd414a Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 17 Jul 2020 14:00:01 +0100 Subject: [PATCH 21/49] Add back changes to ChunkCoordinator --- .../bukkit/queue/BukkitChunkCoordinator.java | 127 ++++++++++++++++-- 1 file changed, 117 insertions(+), 10 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java index ecb0f3500..5cc5de1b1 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java @@ -44,8 +44,35 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; +/** + * Utility that allows for the loading and coordination of chunk actions + *

+ * The coordinator takes in collection of chunk coordinates, loads them + * and allows the caller to specify a sink for the loaded chunks. The + * coordinator will prevent the chunks from being unloaded until the sink + * has fully consumed the chunk + *

+ * Usage: + *

{@code
+ * final ChunkCoordinator chunkCoordinator = ChunkCoordinator.builder()
+ *     .inWorld(Objects.requireNonNull(Bukkit.getWorld("world"))).withChunk(BlockVector2.at(0, 0))
+ *     .withConsumer(chunk -> System.out.printf("Got chunk %d;%d", chunk.getX(), chunk.getZ()))
+ *     .withFinalAction(() -> System.out.println("All chunks have been loaded"))
+ *     .withThrowableConsumer(throwable -> System.err.println("Something went wrong... =("))
+ *     .withMaxIterationTime(25L)
+ *     .build();
+ * chunkCoordinator.subscribeToProgress((coordinator, progress) ->
+ *     System.out.printf("Progress: %.1f", progress * 100.0f));
+ * chunkCoordinator.start();
+ * }
+ * + * @author Alexander Söderberg + * @see #builder() To create a new coordinator instance + */ public final class BukkitChunkCoordinator extends BukkitRunnable { + private final List progressSubscribers = new LinkedList<>(); + private final Queue requestedChunks; private final Queue availableChunks; private final long maxIterationTime; @@ -53,32 +80,48 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { private final Consumer chunkConsumer; private final World world; private final Runnable whenDone; + private final Consumer throwableConsumer; + private final int totalSize; private AtomicInteger expectedSize; private int batchSize; private BukkitChunkCoordinator(final long maxIterationTime, final int initialBatchSize, @NotNull final Consumer chunkConsumer, @NotNull final World world, - @NotNull final Collection requestedChunks, @NotNull final Runnable whenDone) { + @NotNull final Collection requestedChunks, @NotNull final Runnable whenDone, + @NotNull final Consumer throwableConsumer) { this.requestedChunks = new LinkedBlockingQueue<>(requestedChunks); this.availableChunks = new LinkedBlockingQueue<>(); - this.expectedSize = new AtomicInteger(requestedChunks.size()); + this.totalSize = requestedChunks.size(); + this.expectedSize = new AtomicInteger(this.totalSize); this.world = world; this.batchSize = initialBatchSize; this.chunkConsumer = chunkConsumer; this.maxIterationTime = maxIterationTime; this.whenDone = whenDone; + this.throwableConsumer = throwableConsumer; this.plugin = JavaPlugin.getPlugin(BukkitPlatform.class); + } + + /** + * Create a new {@link BukkitChunkCoordinator} instance + * + * @return Coordinator builder instance + */ + @NotNull public static ChunkCoordinatorBuilder builder() { + return new ChunkCoordinatorBuilder(); + } + + /** + * Start the coordinator instance + */ + public void start() { // Request initial batch this.requestBatch(); // Wait until next tick to give the chunks a chance to be loaded this.runTaskTimer(this.plugin, 1L, 1L); } - @NotNull public static ChunkCoordinatorBuilder builder() { - return new ChunkCoordinatorBuilder(); - } - @Override public void run() { Chunk chunk = this.availableChunks.poll(); if (chunk == null) { @@ -90,7 +133,8 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { final long start = System.currentTimeMillis(); try { this.chunkConsumer.accept(chunk); - } catch (final Exception ignored) { + } catch (final Throwable throwable) { + this.throwableConsumer.accept(throwable); } this.freeChunk(chunk); processedChunks++; @@ -103,10 +147,19 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { // Adjust batch size based on the amount of processed chunks per tick this.batchSize = processedChunks; } - if (this.expectedSize.addAndGet(-processedChunks) <= 0) { + + final int expected = this.expectedSize.addAndGet(-processedChunks); + + final float progress = ((float) totalSize - (float) expected) / (float) totalSize; + for (final ProgressSubscriber subscriber : this.progressSubscribers) { + subscriber.notifyProgress(this, progress); + } + + if (expected <= 0) { try { this.whenDone.run(); - } catch (final Exception ignored) { + } catch (final Throwable throwable) { + this.throwableConsumer.accept(throwable); } this.cancel(); } else { @@ -150,10 +203,54 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { chunk.removePluginChunkTicket(this.plugin); } + /** + * Get the amount of remaining chunks (at the time of the method call) + * + * @return Snapshot view of remaining chunk count + */ + public int getRemainingChunks() { + return this.expectedSize.get(); + } + + /** + * Get the amount of requested chunks + * + * @return Requested chunk count + */ + public int getTotalChunks() { + return this.totalSize; + } + + /** + * Subscribe to coordinator progress updates + * + * @param subscriber Subscriber + */ + public void subscribeToProgress( + @NotNull final BukkitChunkCoordinator.ProgressSubscriber subscriber) { + this.progressSubscribers.add(subscriber); + } + + + @FunctionalInterface + public interface ProgressSubscriber { + + /** + * Notify about a progress update in the coordinator + * + * @param coordinator Coordinator instance that triggered the notification + * @param progress Progress in the range [0, 1] + */ + void notifyProgress(@NotNull final BukkitChunkCoordinator coordinator, + final float progress); + + } + public static final class ChunkCoordinatorBuilder { private final List requestedChunks = new LinkedList<>(); + private Consumer throwableConsumer = Throwable::printStackTrace; private World world; private Consumer chunkConsumer; private Runnable whenDone = () -> { @@ -208,12 +305,22 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { return this; } + @NotNull public ChunkCoordinatorBuilder withThrowableConsumer( + @NotNull final Consumer throwableConsumer) { + this.throwableConsumer = + Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null"); + return this; + } + @NotNull public BukkitChunkCoordinator build() { Preconditions.checkNotNull(this.world, "No world was supplied"); Preconditions.checkNotNull(this.chunkConsumer, "No chunk consumer was supplied"); Preconditions.checkNotNull(this.whenDone, "No final action was supplied"); + Preconditions + .checkNotNull(this.throwableConsumer, "No throwable consumer was supplied"); return new BukkitChunkCoordinator(this.maxIterationTime, this.initialBatchSize, - this.chunkConsumer, this.world, this.requestedChunks, this.whenDone); + this.chunkConsumer, this.world, this.requestedChunks, this.whenDone, + this.throwableConsumer); } } From ed77522c0863c13e2f35d491f34c040716cfa5f3 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 17 Jul 2020 14:38:50 +0100 Subject: [PATCH 22/49] Add wna block setting, use WorldEdit worlds rather than Strings. --- Bukkit/build.gradle | 2 +- .../bukkit/queue/BukkitLocalQueue.java | 239 ------------------ .../bukkit/queue/BukkitQueueCoordinator.java | 127 +++++++++- .../core/queue/BasicQueueCoordinator.java | 34 +-- .../core/queue/ChunkQueueCoordinator.java | 9 +- .../core/queue/DelegateQueueCoordinator.java | 15 +- .../plotsquared/core/queue/LocalChunk.java | 53 ++-- .../core/queue/QueueCoordinator.java | 9 +- .../core/queue/ScopedQueueCoordinator.java | 4 +- 9 files changed, 178 insertions(+), 314 deletions(-) delete mode 100644 Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitLocalQueue.java diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index 8e32904c5..e752aca5f 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -24,7 +24,7 @@ dependencies { compile(project(":PlotSquared-Core")) compile("com.destroystokyo.paper:paper-api:1.16.1-R0.1-SNAPSHOT") implementation("org.spigotmc:spigot-api:1.16.1-R0.1-SNAPSHOT") - compile(group: "com.sk89q.worldedit", name: "worldedit-bukkit", version: "7.1.0") { + compile(group: "com.sk89q.worldedit", name: "worldedit-bukkit", version: "7.2.0-SNAPSHOT") { exclude(module: "bukkit") } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitLocalQueue.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitLocalQueue.java deleted file mode 100644 index fa6ccd69d..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitLocalQueue.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2020 IntellectualSites - * - * 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, see . - */ -package com.plotsquared.bukkit.queue; - -import com.plotsquared.bukkit.schematic.StateWrapper; -import com.plotsquared.bukkit.util.BukkitBlockUtil; -import com.plotsquared.core.queue.BasicLocalBlockQueue; -import com.plotsquared.core.util.BlockUtil; -import com.plotsquared.core.util.MainUtil; -import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.bukkit.BukkitAdapter; -import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldedit.regions.CuboidRegion; -import com.sk89q.worldedit.world.biome.BiomeType; -import com.sk89q.worldedit.world.block.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; -import io.papermc.lib.PaperLib; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.Block; -import org.bukkit.block.Container; -import org.bukkit.block.data.BlockData; -import javax.annotation.Nonnull; - -import java.util.concurrent.ExecutionException; -import java.util.function.Consumer; - -public class BukkitLocalQueue extends BasicLocalBlockQueue { - - public BukkitLocalQueue(String world) { - super(world); - } - - @Override public LocalChunk getLocalChunk(int x, int z) { - return new BasicLocalChunk(this, x, z) { - // Custom stuff? - }; - } - - @Override public void optimize() { - - } - - @Override public BlockState getBlock(int x, int y, int z) { - World worldObj = Bukkit.getWorld(getWorld()); - if (worldObj != null) { - Block block = worldObj.getBlockAt(x, y, z); - return BukkitBlockUtil.get(block); - } else { - return BlockUtil.get(0, 0); - } - } - - @Override public void refreshChunk(int x, int z) { - World worldObj = Bukkit.getWorld(getWorld()); - if (worldObj != null) { - worldObj.refreshChunk(x, z); - } - } - - @Override public void fixChunkLighting(int x, int z) { - // Do nothing - } - - @Override public final void regenChunk(int x, int z) { - World worldObj = Bukkit.getWorld(getWorld()); - if (worldObj != null) { - try { - worldObj.regenerateChunk(x, z); - } catch (UnsupportedOperationException e) { - com.sk89q.worldedit.world.World world = BukkitAdapter.adapt(worldObj); - try (EditSession editSession = WorldEdit.getInstance().getEditSessionFactory() - .getEditSession(world, -1);) { - CuboidRegion region = - new CuboidRegion(world, BlockVector3.at((x << 4), 0, (z << 4)), - BlockVector3.at((x << 4) + 15, 255, (z << 4) + 15)); - world.regenerate(region, editSession); - } - } - } - } - - @Override public final void setComponents(LocalChunk lc) - throws ExecutionException, InterruptedException { - setBaseBlocks(lc); - } - - public void setBaseBlocks(LocalChunk localChunk) { - World worldObj = Bukkit.getWorld(getWorld()); - if (worldObj == null) { - throw new NullPointerException("World cannot be null."); - } - final Consumer chunkConsumer = chunk -> { - for (int layer = 0; layer < localChunk.baseblocks.length; layer++) { - BaseBlock[] blocksLayer = localChunk.baseblocks[layer]; - if (blocksLayer != null) { - for (int j = 0; j < blocksLayer.length; j++) { - if (blocksLayer[j] != null) { - BaseBlock block = blocksLayer[j]; - int x = MainUtil.x_loc[layer][j]; - int y = MainUtil.y_loc[layer][j]; - int z = MainUtil.z_loc[layer][j]; - - BlockData blockData = BukkitAdapter.adapt(block); - - Block existing = chunk.getBlock(x, y, z); - final BlockState existingBaseBlock = - BukkitAdapter.adapt(existing.getBlockData()); - if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing - .getBlockData().matches(blockData)) { - continue; - } - - if (existing.getState() instanceof Container) { - ((Container) existing.getState()).getInventory().clear(); - } - - existing.setType(BukkitAdapter.adapt(block.getBlockType()), false); - existing.setBlockData(blockData, false); - if (block.hasNbtData()) { - CompoundTag tag = block.getNbtData(); - StateWrapper sw = new StateWrapper(tag); - - sw.restoreTag(worldObj.getName(), existing.getX(), existing.getY(), - existing.getZ()); - } - } - } - } - } - if (setBiome() && localChunk.biomes != null) { - for (int x = 0; x < localChunk.biomes.length; x++) { - BiomeType[] biomeZ = localChunk.biomes[x]; - if (biomeZ != null) { - for (int z = 0; z < biomeZ.length; z++) { - if (biomeZ[z] != null) { - BiomeType biomeType = biomeZ[z]; - - Biome biome = BukkitAdapter.adapt(biomeType); - worldObj.setBiome((chunk.getX() << 4) + x, (chunk.getZ() << 4) + z, - biome); - } - } - } - } - } - }; - if (isForceSync()) { - chunkConsumer.accept(getChunk(worldObj, localChunk)); - } else { - PaperLib.getChunkAtAsync(worldObj, localChunk.getX(), localChunk.getZ(), true) - .thenAccept(chunkConsumer); - } - } - - private Chunk getChunk(final World world, final LocalChunk localChunk) { - Chunk chunk = null; - if (this.getChunkObject() != null && this.getChunkObject() instanceof Chunk) { - chunk = (Chunk) this.getChunkObject(); - } - if (chunk == null) { - chunk = world.getChunkAt(localChunk.getX(), localChunk.getZ()); - } - if (!chunk.isLoaded()) { - chunk.load(true); - } - return chunk; - } - - private void setMaterial(@Nonnull final BlockState plotBlock, @Nonnull final Block block) { - Material material = BukkitAdapter.adapt(plotBlock.getBlockType()); - block.setType(material, false); - } - - private boolean equals(@Nonnull final BlockState plotBlock, @Nonnull final Block block) { - return plotBlock.equals(BukkitBlockUtil.get(block)); - } - - public void setBiomes(LocalChunk lc) { - World worldObj = Bukkit.getWorld(getWorld()); - if (worldObj == null) { - throw new NullPointerException("World cannot be null."); - } - if (lc.biomes == null) { - throw new NullPointerException("Biomes cannot be null."); - } - final Consumer chunkConsumer = chunk -> { - for (int x = 0; x < lc.biomes.length; x++) { - BiomeType[] biomeZ = lc.biomes[x]; - if (biomeZ != null) { - for (int z = 0; z < biomeZ.length; z++) { - if (biomeZ[z] != null) { - BiomeType biomeType = biomeZ[z]; - - Biome biome = BukkitAdapter.adapt(biomeType); - worldObj - .setBiome((chunk.getX() << 4) + x, (chunk.getZ() << 4) + z, biome); - } - } - } - } - }; - if (this.isForceSync()) { - chunkConsumer.accept(getChunk(worldObj, lc)); - } else { - PaperLib.getChunkAtAsync(worldObj, lc.getX(), lc.getZ(), true) - .thenAccept(chunkConsumer); - } - } - -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index 9dce356c5..b356bea11 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -25,22 +25,44 @@ */ package com.plotsquared.bukkit.queue; +import com.plotsquared.bukkit.schematic.StateWrapper; import com.plotsquared.bukkit.util.BukkitBlockUtil; import com.plotsquared.core.queue.BasicQueueCoordinator; +import com.plotsquared.core.queue.LocalChunk; import com.plotsquared.core.util.BlockUtil; +import com.plotsquared.core.util.MainUtil; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.util.SideEffect; +import com.sk89q.worldedit.util.SideEffectSet; +import com.sk89q.worldedit.world.World; +import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import org.bukkit.Bukkit; -import org.bukkit.World; +import org.bukkit.Material; import org.bukkit.block.Block; +import org.bukkit.block.Container; +import org.bukkit.block.data.BlockData; + +import javax.annotation.Nonnull; public class BukkitQueueCoordinator extends BasicQueueCoordinator { - public BukkitQueueCoordinator(String world) { + private final World world; + private final SideEffectSet sideEffectSet; + + public BukkitQueueCoordinator(World world) { super(world); + this.world = world; + sideEffectSet = SideEffectSet.none().with(SideEffect.LIGHTING, SideEffect.State.OFF) + .with(SideEffect.NEIGHBORS, SideEffect.State.OFF); } @Override public BlockState getBlock(int x, int y, int z) { - World worldObj = Bukkit.getWorld(getWorld()); + org.bukkit.World worldObj = BukkitAdapter.adapt(world); if (worldObj != null) { Block block = worldObj.getBlockAt(x, y, z); return BukkitBlockUtil.get(block); @@ -49,4 +71,101 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { } } + @Override public boolean enqueue() { + BukkitChunkCoordinator.builder().inWorld(BukkitAdapter.adapt(world)) + .withChunks(getBlockChunks().keySet()).withInitialBatchSize(3).withMaxIterationTime(40) + .withThrowableConsumer(Throwable::printStackTrace).withConsumer(chunk -> { + LocalChunk localChunk = + getBlockChunks().get(BlockVector2.at(chunk.getX(), chunk.getZ())); + if (localChunk == null) { + throw new NullPointerException( + "LocalChunk cannot be null when accessed from ChunkCoordinator"); + } + World worldObj = getWorld(); + int sx = chunk.getX() << 4; + int sz = chunk.getX() << 4; + for (int layer = 0; layer < localChunk.getBaseblocks().length; layer++) { + BaseBlock[] blocksLayer = localChunk.getBaseblocks()[layer]; + if (blocksLayer == null) { + continue; + } + for (int j = 0; j < blocksLayer.length; j++) { + if (blocksLayer[j] == null) { + continue; + } + BaseBlock block = blocksLayer[j]; + int x = sx + MainUtil.x_loc[layer][j]; + int y = MainUtil.y_loc[layer][j]; + int z = sz + MainUtil.z_loc[layer][j]; + try { + worldObj.setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); + } catch (WorldEditException ignored) { + // Fallback to not so nice method + BlockData blockData = BukkitAdapter.adapt(block); + + Block existing = chunk.getBlock(x, y, z); + final BlockState existingBaseBlock = + BukkitAdapter.adapt(existing.getBlockData()); + if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing + .getBlockData().matches(blockData)) { + continue; + } + + if (existing.getState() instanceof Container) { + ((Container) existing.getState()).getInventory().clear(); + } + + existing.setType(BukkitAdapter.adapt(block.getBlockType()), false); + existing.setBlockData(blockData, false); + if (block.hasNbtData()) { + CompoundTag tag = block.getNbtData(); + StateWrapper sw = new StateWrapper(tag); + + sw.restoreTag(worldObj.getName(), existing.getX(), existing.getY(), + existing.getZ()); + } + } + } + } + for (int layer = 0; layer < localChunk.getBaseblocks().length; layer++) { + BiomeType[] biomesLayer = localChunk.getBiomes()[layer]; + if (biomesLayer == null) { + continue; + } + for (int j = 0; j < biomesLayer.length; j++) { + if (biomesLayer[j] == null) { + continue; + } + BiomeType biome = biomesLayer[j]; + int x = sx + MainUtil.x_loc[layer][j]; + int y = MainUtil.y_loc[layer][j]; + int z = sz + MainUtil.z_loc[layer][j]; + worldObj.setBiome(BlockVector3.at(x, y, z), biome); + } + } + if (localChunk.getTiles().size() > 0) { + localChunk.getTiles().forEach(((blockVector3, tag) -> { + try { + BaseBlock block = worldObj.getBlock(blockVector3).toBaseBlock(tag); + worldObj.setBlock(blockVector3, block, sideEffectSet); + } catch (WorldEditException ignored) { + StateWrapper sw = new StateWrapper(tag); + sw.restoreTag(worldObj.getName(), blockVector3.getX(), blockVector3.getY(), + blockVector3.getZ()); + } + })); + } + }); + return super.enqueue(); + } + + private void setMaterial(@Nonnull final BlockState plotBlock, @Nonnull final Block block) { + Material material = BukkitAdapter.adapt(plotBlock.getBlockType()); + block.setType(material, false); + } + + private boolean equals(@Nonnull final BlockState plotBlock, @Nonnull final Block block) { + return plotBlock.equals(BukkitBlockUtil.get(block)); + } + } diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index e22376fd3..3b20d17c6 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -28,26 +28,31 @@ package com.plotsquared.core.queue; import com.plotsquared.core.util.PatternUtil; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import lombok.Getter; import javax.annotation.Nonnull; import java.util.concurrent.ConcurrentHashMap; public abstract class BasicQueueCoordinator extends QueueCoordinator { - private final String world; - private final ConcurrentHashMap blockChunks = new ConcurrentHashMap<>(); + private final World world; + @Getter private final ConcurrentHashMap blockChunks = + new ConcurrentHashMap<>(); private long modified; private LocalChunk lastWrappedChunk; private int lastX = Integer.MIN_VALUE; private int lastZ = Integer.MIN_VALUE; - private boolean setbiome = false; + @Getter private boolean settingBiomes = false; + @Getter private boolean settingTiles = false; private GlobalBlockQueue globalBlockQueue; - public BasicQueueCoordinator(String world) { + public BasicQueueCoordinator(World world) { this.world = world; this.modified = System.currentTimeMillis(); } @@ -60,7 +65,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { @Override public abstract BlockState getBlock(int x, int y, int z); - @Override public final String getWorld() { + @Override public final World getWorld() { return world; } @@ -95,32 +100,29 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { @Override public final boolean setBiome(int x, int z, BiomeType biomeType) { LocalChunk chunk = getChunk(x >> 4, z >> 4); chunk.setBiome(x & 15, z & 15, biomeType); - setbiome = true; + settingBiomes = true; return true; } @Override public final boolean setTile(int x, int y, int z, CompoundTag tag) { LocalChunk chunk = getChunk(x >> 4, z >> 4); chunk.setTile(x, y, z, tag); + settingTiles = true; return true; } - @Override public final boolean settingBiome() { - return setbiome; - } - public final void setChunk(LocalChunk chunk) { - this.blockChunks.put(chunk.longHash(), chunk); + this.blockChunks.put(BlockVector2.at(chunk.getX(), chunk.getZ()), chunk); } - private LocalChunk getChunk(final int chunkX, final int ChunkZ) { - if (chunkX != lastX || ChunkZ != lastZ) { + private LocalChunk getChunk(final int chunkX, final int chunkZ) { + if (chunkX != lastX || chunkZ != lastZ) { lastX = chunkX; - lastZ = ChunkZ; - long pair = (long) (chunkX) << 32 | (ChunkZ) & 0xFFFFFFFFL; + lastZ = chunkZ; + BlockVector2 pair = BlockVector2.at(chunkX, chunkZ); lastWrappedChunk = this.blockChunks.get(pair); if (lastWrappedChunk == null) { - lastWrappedChunk = this.getLocalChunk(chunkX, ChunkZ); + lastWrappedChunk = this.getLocalChunk(chunkX, chunkZ); LocalChunk previous = this.blockChunks.put(pair, lastWrappedChunk); if (previous == null) { return lastWrappedChunk; diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java index 59daca67c..e221ee7ad 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java @@ -28,6 +28,7 @@ package com.plotsquared.core.queue; import com.plotsquared.core.location.Location; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; @@ -112,15 +113,15 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { return null; } - @Override @Nonnull public String getWorld() { - return ""; + @Override @Nonnull public World getWorld() { + return super.getWorld(); } @Override public Location getMax() { - return Location.at(getWorld(), top.getX(), top.getY(), top.getZ()); + return Location.at(getWorld().getName(), top.getX(), top.getY(), top.getZ()); } @Override public Location getMin() { - return Location.at(getWorld(), bot.getX(), bot.getY(), bot.getZ()); + return Location.at(getWorld().getName(), bot.getX(), bot.getY(), bot.getZ()); } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index 5712d5694..9e4826f32 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -27,13 +27,10 @@ package com.plotsquared.core.queue; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import lombok.Getter; -import lombok.Setter; - -import javax.annotation.Nullable; public class DelegateQueueCoordinator extends QueueCoordinator { @@ -84,11 +81,11 @@ public class DelegateQueueCoordinator extends QueueCoordinator { return parent.setBiome(x, z, biome); } - @Override public boolean settingBiome() { - return parent.settingBiome(); + @Override public boolean isSettingBiomes() { + return parent.isSettingBiomes(); } - @Override public String getWorld() { + @Override public World getWorld() { return parent.getWorld(); } @@ -96,6 +93,10 @@ public class DelegateQueueCoordinator extends QueueCoordinator { return parent.setTile(x, y, z, tag); } + @Override public boolean isSettingTiles() { + return parent.isSettingTiles(); + } + @Override public boolean enqueue() { if (parent != null) { return parent.enqueue(); diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java index 99975cae6..e638fe4ef 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java @@ -6,55 +6,35 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; +import lombok.Getter; import java.util.HashMap; public class LocalChunk { - public final BasicQueueCoordinator parent; - public final int z; - public final int x; + @Getter private final BasicQueueCoordinator parent; + @Getter private final int z; + @Getter private final int x; - public BaseBlock[][] baseblocks; - public BiomeType[][] biomes; - public HashMap tiles = null; + @Getter private final BaseBlock[][] baseblocks; + @Getter private final BiomeType[][] biomes; + @Getter private final HashMap tiles = new HashMap<>(); public LocalChunk(BasicQueueCoordinator parent, int x, int z) { this.parent = parent; this.x = x; this.z = z; baseblocks = new BaseBlock[16][]; + biomes = new BiomeType[16][]; } - /** - * Get the parent queue this chunk belongs to - * - * @return - */ - public BasicQueueCoordinator getParent() { - return parent; - } - - public int getX() { - return x; - } - - public int getZ() { - return z; - } - - public void setBiome(int x, int z, BiomeType biomeType) { - if (this.biomes == null) { - this.biomes = new BiomeType[16][]; + public void setBiome(final int x, final int y, final int z, final BiomeType biomeType) { + final int i = MainUtil.CACHE_I[y][x][z]; + final int j = MainUtil.CACHE_J[y][x][z]; + BiomeType[] array = this.biomes[i]; + if (array == null) { + array = this.biomes[i] = new BiomeType[4096]; } - BiomeType[] index = this.biomes[x]; - if (index == null) { - index = this.biomes[x] = new BiomeType[16]; - } - index[z] = biomeType; - } - - public long longHash() { - return MathMan.pairInt(x, z); + array[j] = biomeType; } @Override public int hashCode() { @@ -72,9 +52,6 @@ public class LocalChunk { } public void setTile(final int x, final int y, final int z, final CompoundTag tag) { - if (tiles == null) { - tiles = new HashMap<>(); - } tiles.put(BlockVector3.at(x, y, z), tag); } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index df537d909..7a2c8e86c 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -31,6 +31,7 @@ import com.plotsquared.core.location.Location; import com.plotsquared.core.util.PatternUtil; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; @@ -73,20 +74,22 @@ public abstract class QueueCoordinator { public abstract boolean setTile(int x, int y, int z, CompoundTag tag); + public abstract boolean isSettingTiles(); + public abstract BlockState getBlock(int x, int y, int z); public abstract boolean setBiome(int x, int z, BiomeType biome); - public abstract boolean settingBiome(); + public abstract boolean isSettingBiomes(); - public abstract String getWorld(); + public abstract World getWorld(); public final void setModified() { setModified(System.currentTimeMillis()); } public boolean enqueue() { - return this.blockQueue.enqueue(this); + return blockQueue.enqueue(this); } public void setCuboid(Location pos1, Location pos2, BlockState block) { diff --git a/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java index 49631dceb..f19b7caaf 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java @@ -93,11 +93,11 @@ public class ScopedQueueCoordinator extends DelegateQueueCoordinator { } public Location getMin() { - return Location.at(this.getWorld(), this.minX, this.minY, this.minZ); + return Location.at(this.getWorld().getName(), this.minX, this.minY, this.minZ); } public Location getMax() { - return Location.at(this.getWorld(), this.maxX, this.maxY, this.maxZ); + return Location.at(this.getWorld().getName(), this.maxX, this.maxY, this.maxZ); } } From 9fefe57c90c0a77d6b19ba9547537f761984a58c Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 17 Jul 2020 15:41:06 +0100 Subject: [PATCH 23/49] Switch to using QueueCoordinators everywhere --- .../plotsquared/bukkit/BukkitPlatform.java | 99 +++++++----- .../bukkit/generator/BlockStatePopulator.java | 10 +- .../bukkit/generator/BukkitPlotGenerator.java | 4 +- .../generator/DelegatePlotGenerator.java | 9 +- .../bukkit/inject/BukkitModule.java | 20 ++- .../bukkit/queue/BukkitQueueCoordinator.java | 142 +++++++++--------- .../plotsquared/bukkit/queue/GenChunk.java | 17 ++- .../schematic/BukkitSchematicHandler.java | 6 +- .../bukkit/util/BukkitChunkManager.java | 11 +- .../bukkit/util/BukkitRegionManager.java | 65 ++++---- .../com/plotsquared/core/command/Relight.java | 9 +- .../com/plotsquared/core/command/Trim.java | 4 +- .../core/generator/AugmentedUtils.java | 29 ++-- .../core/generator/ClassicPlotManager.java | 22 +-- .../plotsquared/core/generator/HybridGen.java | 6 +- .../core/generator/HybridPlotManager.java | 38 ++--- .../core/generator/HybridUtils.java | 16 +- .../generator/IndependentPlotGenerator.java | 12 +- .../core/generator/SingleWorldGenerator.java | 4 +- .../java/com/plotsquared/core/plot/Plot.java | 114 +++++++------- .../com/plotsquared/core/plot/PlotArea.java | 5 +- .../AreaBoundDelegateQueueCoordinator.java | 7 + .../core/queue/BasicQueueCoordinator.java | 11 +- .../core/queue/ChunkQueueCoordinator.java | 34 +++-- .../core/queue/DelegateQueueCoordinator.java | 8 + .../core/queue/GlobalBlockQueue.java | 11 ++ ...ocationOffsetDelegateQueueCoordinator.java | 13 +- .../core/queue/OffsetQueueCoordinator.java | 8 +- .../core/queue/QueueCoordinator.java | 13 +- .../core/queue/ScopedQueueCoordinator.java | 13 +- .../plotsquared/core/util/ChunkManager.java | 32 ++-- .../plotsquared/core/util/RegionManager.java | 23 ++- .../core/util/SchematicHandler.java | 25 +-- 33 files changed, 485 insertions(+), 355 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index e40b6698e..60a49bc27 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -90,7 +90,6 @@ import com.plotsquared.core.plot.message.PlainChatManager; import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.plot.world.SinglePlotArea; import com.plotsquared.core.plot.world.SinglePlotAreaManager; -import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.setup.PlotAreaBuilder; import com.plotsquared.core.setup.SettingsNodesWrapper; import com.plotsquared.core.util.ChatManager; @@ -156,9 +155,11 @@ import static com.plotsquared.core.util.PremiumVerification.getResourceID; import static com.plotsquared.core.util.PremiumVerification.getUserID; import static com.plotsquared.core.util.ReflectionUtils.getRefClass; -@SuppressWarnings("unused") public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPlatform { +@SuppressWarnings("unused") +public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPlatform { - private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitPlatform.class.getSimpleName()); + private static final Logger logger = + LoggerFactory.getLogger("P2/" + BukkitPlatform.class.getSimpleName()); private static final int BSTATS_ID = 1404; static { @@ -233,8 +234,9 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; // We create the injector after PlotSquared has been initialized, so that we have access // to generated instances and settings - this.injector = Guice.createInjector(Stage.PRODUCTION, new WorldManagerModule(), new PlotSquaredModule(), - new BukkitModule(this), new BackupModule()); + this.injector = Guice + .createInjector(Stage.PRODUCTION, new WorldManagerModule(), new PlotSquaredModule(), + new BukkitModule(this), new BackupModule()); this.injector.injectMembers(this); if (PremiumVerification.isPremium() && Settings.Enabled_Components.UPDATE_NOTIFICATIONS) { @@ -288,34 +290,37 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; if (Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) { try { logger.info("[P2] {} hooked into WorldEdit", this.getPluginName()); - WorldEdit.getInstance().getEventBus().register(this.getInjector().getInstance(WESubscriber.class)); + WorldEdit.getInstance().getEventBus() + .register(this.getInjector().getInstance(WESubscriber.class)); if (Settings.Enabled_Components.COMMANDS) { new WE_Anywhere(); } } catch (Throwable e) { - logger.error("[P2] Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master"); + logger.error( + "[P2] Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master"); } } if (Settings.Enabled_Components.EVENTS) { - getServer().getPluginManager().registerEvents(getInjector().getInstance(PlayerEvents.class), this); - getServer().getPluginManager().registerEvents(getInjector().getInstance(EntitySpawnListener.class), this); + getServer().getPluginManager() + .registerEvents(getInjector().getInstance(PlayerEvents.class), this); + getServer().getPluginManager() + .registerEvents(getInjector().getInstance(EntitySpawnListener.class), this); if (PaperLib.isPaper() && Settings.Paper_Components.PAPER_LISTENERS) { - getServer().getPluginManager().registerEvents(getInjector().getInstance(PaperListener.class), this); + getServer().getPluginManager() + .registerEvents(getInjector().getInstance(PaperListener.class), this); } this.plotListener.startRunnable(); } // Required - getServer().getPluginManager().registerEvents(getInjector().getInstance(WorldEvents.class), this); + getServer().getPluginManager() + .registerEvents(getInjector().getInstance(WorldEvents.class), this); if (Settings.Enabled_Components.CHUNK_PROCESSOR) { - getServer().getPluginManager().registerEvents(getInjector().getInstance(ChunkListener.class), this); + getServer().getPluginManager() + .registerEvents(getInjector().getInstance(ChunkListener.class), this); } - // Start the global block queue - final GlobalBlockQueue globalBlockQueue = this.injector.getInstance(GlobalBlockQueue.class); - globalBlockQueue.runTask(); - // Commands if (Settings.Enabled_Components.COMMANDS) { this.registerCommands(); @@ -344,7 +349,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; } // World generators: - final ConfigurationSection section = this.worldConfiguration.getConfigurationSection("worlds"); + final ConfigurationSection section = + this.worldConfiguration.getConfigurationSection("worlds"); final WorldUtil worldUtil = getInjector().getInstance(WorldUtil.class); if (section != null) { @@ -362,11 +368,15 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; continue; } if (!worldUtil.isWorld(world) && !world.equals("*")) { - logger.warn("[P2] `{}` was not properly loaded - {} will now try to load it properly", + logger.warn( + "[P2] `{}` was not properly loaded - {} will now try to load it properly", world, this.getPluginName()); - logger.warn("[P2] - Are you trying to delete this world? Remember to remove it from the worlds.yml, bukkit.yml and multiverse worlds.yml"); - logger.warn("[P2] - Your world management plugin may be faulty (or non existent)"); - logger.warn("[P2] This message may also be a false positive and could be ignored."); + logger.warn( + "[P2] - Are you trying to delete this world? Remember to remove it from the worlds.yml, bukkit.yml and multiverse worlds.yml"); + logger.warn( + "[P2] - Your world management plugin may be faulty (or non existent)"); + logger.warn( + "[P2] This message may also be a false positive and could be ignored."); this.setGenerator(world); } } @@ -374,7 +384,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; } // Services are accessed in order - final CacheUUIDService cacheUUIDService = new CacheUUIDService(Settings.UUID.UUID_CACHE_SIZE); + final CacheUUIDService cacheUUIDService = + new CacheUUIDService(Settings.UUID.UUID_CACHE_SIZE); this.impromptuPipeline.registerService(cacheUUIDService); this.backgroundPipeline.registerService(cacheUUIDService); this.impromptuPipeline.registerConsumer(cacheUUIDService); @@ -390,7 +401,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; } if (Settings.UUID.SERVICE_BUKKIT) { - final OfflinePlayerUUIDService offlinePlayerUUIDService = new OfflinePlayerUUIDService(); + final OfflinePlayerUUIDService offlinePlayerUUIDService = + new OfflinePlayerUUIDService(); this.impromptuPipeline.registerService(offlinePlayerUUIDService); this.backgroundPipeline.registerService(offlinePlayerUUIDService); } @@ -406,8 +418,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; } final LuckPermsUUIDService luckPermsUUIDService; - if (Settings.UUID.SERVICE_LUCKPERMS && - Bukkit.getPluginManager().getPlugin("LuckPerms") != null) { + if (Settings.UUID.SERVICE_LUCKPERMS + && Bukkit.getPluginManager().getPlugin("LuckPerms") != null) { luckPermsUUIDService = new LuckPermsUUIDService(); logger.info("[P2] (UUID) Using LuckPerms as a complementary UUID service"); } else { @@ -415,8 +427,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; } final BungeePermsUUIDService bungeePermsUUIDService; - if (Settings.UUID.SERVICE_BUNGEE_PERMS && - Bukkit.getPluginManager().getPlugin("BungeePerms") != null) { + if (Settings.UUID.SERVICE_BUNGEE_PERMS + && Bukkit.getPluginManager().getPlugin("BungeePerms") != null) { bungeePermsUUIDService = new BungeePermsUUIDService(); logger.info("[P2] (UUID) Using BungeePerms as a complementary UUID service"); } else { @@ -424,7 +436,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; } final EssentialsUUIDService essentialsUUIDService; - if (Settings.UUID.SERVICE_ESSENTIALSX && Bukkit.getPluginManager().getPlugin("Essentials") != null) { + if (Settings.UUID.SERVICE_ESSENTIALSX + && Bukkit.getPluginManager().getPlugin("Essentials") != null) { essentialsUUIDService = new EssentialsUUIDService(); logger.info("[P2] (UUID) Using EssentialsX as a complementary UUID service"); } else { @@ -511,8 +524,10 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; // Clean up potential memory leak Bukkit.getScheduler().runTaskTimer(this, () -> { try { - for (final PlotPlayer player : this.getPlayerManager().getPlayers()) { - if (player.getPlatformPlayer() == null || !player.getPlatformPlayer().isOnline()) { + for (final PlotPlayer player : this.getPlayerManager() + .getPlayers()) { + if (player.getPlatformPlayer() == null || !player.getPlatformPlayer() + .isOnline()) { this.getPlayerManager().removePlayer(player); } } @@ -626,7 +641,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; // Now fetch names for all known UUIDs final int totalSize = uuidQueue.size(); int read = 0; - logger.info("[P2] (UUID) PlotSquared will fetch UUIDs in groups of {}", Settings.UUID.BACKGROUND_LIMIT); + logger.info("[P2] (UUID) PlotSquared will fetch UUIDs in groups of {}", + Settings.UUID.BACKGROUND_LIMIT); final List uuidList = new ArrayList<>(Settings.UUID.BACKGROUND_LIMIT); // Used to indicate that the second retrieval has been attempted @@ -659,7 +675,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; // Print progress final double percentage = ((double) read / (double) totalSize) * 100.0D; if (Settings.DEBUG) { - logger.info("[P2] (UUID) PlotSquared has cached {} of UUIDs", String.format("%.1f%%", percentage)); + logger.info("[P2] (UUID) PlotSquared has cached {} of UUIDs", + String.format("%.1f%%", percentage)); } } catch (final InterruptedException | ExecutionException e) { logger.error("[P2] (UUID) Failed to retrieve last batch. Will try again", e); @@ -845,7 +862,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; if (currentPlotId != null) { entity.setMetadata("shulkerPlot", new FixedMetadataValue( - (Plugin) PlotSquared.platform(), currentPlotId)); + (Plugin) PlotSquared.platform(), + currentPlotId)); } } } @@ -970,7 +988,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; if (id != null && id.equalsIgnoreCase("single")) { result = getInjector().getInstance(SingleWorldGenerator.class); } else { - result = getInjector().getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)); + result = getInjector() + .getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)); if (!PlotSquared.get().setupPlotWorld(worldName, id, result)) { return null; } @@ -992,7 +1011,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; return new BukkitPlotGenerator(world, gen, this.plotAreaManager); } else { return new BukkitPlotGenerator(world, getInjector() - .getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)), this.plotAreaManager); + .getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)), + this.plotAreaManager); } } @@ -1035,7 +1055,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; World world = BukkitUtil.getWorld(worldName); if (world == null) { // create world - ConfigurationSection worldConfig = this.worldConfiguration.getConfigurationSection("worlds." + worldName); + ConfigurationSection worldConfig = + this.worldConfiguration.getConfigurationSection("worlds." + worldName); String manager = worldConfig.getString("generator.plugin", getPluginName()); PlotAreaBuilder builder = PlotAreaBuilder.newBuilder().plotManager(manager) .generatorName(worldConfig.getString("generator.init", manager)) @@ -1061,7 +1082,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; if (gen instanceof BukkitPlotGenerator) { PlotSquared.get().loadWorld(worldName, (BukkitPlotGenerator) gen); } else if (gen != null) { - PlotSquared.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen, this.plotAreaManager)); + PlotSquared.get().loadWorld(worldName, + new BukkitPlotGenerator(worldName, gen, this.plotAreaManager)); } else if (this.worldConfiguration.contains("worlds." + worldName)) { PlotSquared.get().loadWorld(worldName, null); } @@ -1128,7 +1150,8 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; return names; } - @Override public com.plotsquared.core.location.World getPlatformWorld(@Nonnull final String worldName) { + @Override public com.plotsquared.core.location.World getPlatformWorld( + @Nonnull final String worldName) { return BukkitWorld.of(worldName); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java index 3e3b74938..c61e97e0f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java @@ -30,8 +30,8 @@ import com.plotsquared.core.generator.IndependentPlotGenerator; import com.plotsquared.core.location.ChunkWrapper; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.world.PlotAreaManager; -import com.plotsquared.core.queue.LocalBlockQueue; -import com.plotsquared.core.queue.ScopedLocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; +import com.plotsquared.core.queue.ScopedQueueCoordinator; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.generator.BlockPopulator; @@ -44,7 +44,7 @@ final class BlockStatePopulator extends BlockPopulator { private final IndependentPlotGenerator plotGenerator; private final PlotAreaManager plotAreaManager; - private LocalBlockQueue queue; + private QueueCoordinator queue; public BlockStatePopulator(@Nonnull final IndependentPlotGenerator plotGenerator, @Nonnull final PlotAreaManager plotAreaManager) { @@ -65,9 +65,9 @@ final class BlockStatePopulator extends BlockPopulator { } final ChunkWrapper wrap = new ChunkWrapper(area.getWorldName(), source.getX(), source.getZ()); - final ScopedLocalBlockQueue chunk = this.queue.getForChunk(wrap.x, wrap.z); + final ScopedQueueCoordinator chunk = this.queue.getForChunk(wrap.x, wrap.z); if (this.plotGenerator.populateChunk(chunk, area)) { - this.queue.flush(); + this.queue.enqueue(); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java index 60bb34b9a..4322eaec9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java @@ -34,7 +34,7 @@ import com.plotsquared.core.generator.SingleWorldGenerator; import com.plotsquared.core.location.ChunkWrapper; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.world.PlotAreaManager; -import com.plotsquared.core.queue.ScopedLocalBlockQueue; +import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.MainUtil; import com.sk89q.worldedit.math.BlockVector2; @@ -190,7 +190,7 @@ public class BukkitPlotGenerator extends ChunkGenerator return result.getChunkData(); } - private void generate(BlockVector2 loc, World world, ScopedLocalBlockQueue result) { + private void generate(BlockVector2 loc, World world, ScopedQueueCoordinator result) { // Load if improperly loaded if (!this.loaded) { String name = world.getName(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java index 6452941a2..e155f03bd 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java @@ -31,16 +31,16 @@ import com.plotsquared.core.generator.IndependentPlotGenerator; import com.plotsquared.core.location.Location; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotId; -import com.plotsquared.core.queue.ScopedLocalBlockQueue; +import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.MathMan; import com.sk89q.worldedit.bukkit.BukkitAdapter; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; -import javax.annotation.Nonnull; import org.jetbrains.annotations.Range; +import javax.annotation.Nonnull; import java.util.Random; final class DelegatePlotGenerator extends IndependentPlotGenerator { @@ -64,7 +64,7 @@ final class DelegatePlotGenerator extends IndependentPlotGenerator { return PlotSquared.platform().getDefaultGenerator().getNewPlotArea(world, id, min, max); } - @Override public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings) { + @Override public void generateChunk(final ScopedQueueCoordinator result, PlotArea settings) { World world = BukkitUtil.getWorld(this.world); Location min = result.getMin(); int chunkX = min.getX() >> 4; @@ -72,8 +72,7 @@ final class DelegatePlotGenerator extends IndependentPlotGenerator { Random random = new Random(MathMan.pair((short) chunkX, (short) chunkZ)); try { ChunkGenerator.BiomeGrid grid = new ChunkGenerator.BiomeGrid() { - @Override - public void setBiome(@Range(from = 0, to = 15) int x, + @Override public void setBiome(@Range(from = 0, to = 15) int x, @Range(from = 0, to = 15) int z, @Nonnull Biome biome) { result.setBiome(x, z, BukkitAdapter.adapt(biome)); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java index c6fe99ba7..b7eda2e6b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java @@ -30,7 +30,7 @@ import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.util.Providers; import com.plotsquared.bukkit.BukkitPlatform; import com.plotsquared.bukkit.player.BukkitPlayerManager; -import com.plotsquared.bukkit.queue.BukkitLocalQueue; +import com.plotsquared.bukkit.queue.BukkitQueueCoordinator; import com.plotsquared.bukkit.schematic.BukkitSchematicHandler; import com.plotsquared.bukkit.util.BukkitChunkManager; import com.plotsquared.bukkit.util.BukkitEconHandler; @@ -66,9 +66,11 @@ import lombok.RequiredArgsConstructor; import org.bukkit.Bukkit; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.plugin.java.JavaPlugin; + import javax.annotation.Nonnull; -@RequiredArgsConstructor public class BukkitModule extends AbstractModule { +@RequiredArgsConstructor +public class BukkitModule extends AbstractModule { private final BukkitPlatform bukkitPlatform; @@ -76,16 +78,19 @@ import javax.annotation.Nonnull; bind(PlayerManager.class).to(BukkitPlayerManager.class); bind(JavaPlugin.class).toInstance(bukkitPlatform); bind(PlotPlatform.class).toInstance(bukkitPlatform); - bind(IndependentPlotGenerator.class).annotatedWith(DefaultGenerator.class).to(HybridGen.class); + bind(IndependentPlotGenerator.class).annotatedWith(DefaultGenerator.class) + .to(HybridGen.class); // Console actor @Nonnull ConsoleCommandSender console = Bukkit.getServer().getConsoleSender(); - WorldEditPlugin wePlugin = ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit")); - bind(Actor.class).annotatedWith(ConsoleActor.class).toInstance(wePlugin.wrapCommandSender(console)); + WorldEditPlugin wePlugin = + ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit")); + bind(Actor.class).annotatedWith(ConsoleActor.class) + .toInstance(wePlugin.wrapCommandSender(console)); bind(InventoryUtil.class).to(BukkitInventoryUtil.class); bind(SetupUtils.class).to(BukkitSetupUtils.class); bind(WorldUtil.class).to(BukkitUtil.class); bind(GlobalBlockQueue.class).toInstance(new GlobalBlockQueue( - QueueProvider.of(BukkitLocalQueue.class, BukkitLocalQueue.class), 1, Settings.QUEUE.TARGET_TIME)); + QueueProvider.of(BukkitQueueCoordinator.class, BukkitQueueCoordinator.class))); bind(ChunkManager.class).to(BukkitChunkManager.class); bind(RegionManager.class).to(BukkitRegionManager.class); bind(SchematicHandler.class).to(BukkitSchematicHandler.class); @@ -108,7 +113,8 @@ import javax.annotation.Nonnull; bind(PermHandler.class).toProvider(Providers.of(null)); } try { - final BukkitEconHandler bukkitEconHandler = new BukkitEconHandler(bukkitPermHandler); + final BukkitEconHandler bukkitEconHandler = + new BukkitEconHandler(bukkitPermHandler); bind(EconHandler.class).toInstance(bukkitEconHandler); } catch (final Exception ignored) { bind(EconHandler.class).toProvider(Providers.of(null)); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index b356bea11..64fa07c0a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -53,6 +53,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { private final World world; private final SideEffectSet sideEffectSet; + private Runnable whenDone; public BukkitQueueCoordinator(World world) { super(world); @@ -74,91 +75,96 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { @Override public boolean enqueue() { BukkitChunkCoordinator.builder().inWorld(BukkitAdapter.adapt(world)) .withChunks(getBlockChunks().keySet()).withInitialBatchSize(3).withMaxIterationTime(40) - .withThrowableConsumer(Throwable::printStackTrace).withConsumer(chunk -> { - LocalChunk localChunk = - getBlockChunks().get(BlockVector2.at(chunk.getX(), chunk.getZ())); - if (localChunk == null) { - throw new NullPointerException( - "LocalChunk cannot be null when accessed from ChunkCoordinator"); - } - World worldObj = getWorld(); - int sx = chunk.getX() << 4; - int sz = chunk.getX() << 4; - for (int layer = 0; layer < localChunk.getBaseblocks().length; layer++) { - BaseBlock[] blocksLayer = localChunk.getBaseblocks()[layer]; - if (blocksLayer == null) { - continue; + .withThrowableConsumer(Throwable::printStackTrace).withFinalAction(whenDone) + .withConsumer(chunk -> { + LocalChunk localChunk = + getBlockChunks().get(BlockVector2.at(chunk.getX(), chunk.getZ())); + if (localChunk == null) { + throw new NullPointerException( + "LocalChunk cannot be null when accessed from ChunkCoordinator"); } - for (int j = 0; j < blocksLayer.length; j++) { - if (blocksLayer[j] == null) { + World worldObj = getWorld(); + int sx = chunk.getX() << 4; + int sz = chunk.getX() << 4; + for (int layer = 0; layer < localChunk.getBaseblocks().length; layer++) { + BaseBlock[] blocksLayer = localChunk.getBaseblocks()[layer]; + if (blocksLayer == null) { continue; } - BaseBlock block = blocksLayer[j]; - int x = sx + MainUtil.x_loc[layer][j]; - int y = MainUtil.y_loc[layer][j]; - int z = sz + MainUtil.z_loc[layer][j]; - try { - worldObj.setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); - } catch (WorldEditException ignored) { - // Fallback to not so nice method - BlockData blockData = BukkitAdapter.adapt(block); - - Block existing = chunk.getBlock(x, y, z); - final BlockState existingBaseBlock = - BukkitAdapter.adapt(existing.getBlockData()); - if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing - .getBlockData().matches(blockData)) { + for (int j = 0; j < blocksLayer.length; j++) { + if (blocksLayer[j] == null) { continue; } + BaseBlock block = blocksLayer[j]; + int x = sx + MainUtil.x_loc[layer][j]; + int y = MainUtil.y_loc[layer][j]; + int z = sz + MainUtil.z_loc[layer][j]; + try { + worldObj.setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); + } catch (WorldEditException ignored) { + // Fallback to not so nice method + BlockData blockData = BukkitAdapter.adapt(block); - if (existing.getState() instanceof Container) { - ((Container) existing.getState()).getInventory().clear(); - } + Block existing = chunk.getBlock(x, y, z); + final BlockState existingBaseBlock = + BukkitAdapter.adapt(existing.getBlockData()); + if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing + .getBlockData().matches(blockData)) { + continue; + } - existing.setType(BukkitAdapter.adapt(block.getBlockType()), false); - existing.setBlockData(blockData, false); - if (block.hasNbtData()) { - CompoundTag tag = block.getNbtData(); - StateWrapper sw = new StateWrapper(tag); + if (existing.getState() instanceof Container) { + ((Container) existing.getState()).getInventory().clear(); + } - sw.restoreTag(worldObj.getName(), existing.getX(), existing.getY(), - existing.getZ()); + existing.setType(BukkitAdapter.adapt(block.getBlockType()), false); + existing.setBlockData(blockData, false); + if (block.hasNbtData()) { + CompoundTag tag = block.getNbtData(); + StateWrapper sw = new StateWrapper(tag); + + sw.restoreTag(worldObj.getName(), existing.getX(), existing.getY(), + existing.getZ()); + } } } } - } - for (int layer = 0; layer < localChunk.getBaseblocks().length; layer++) { - BiomeType[] biomesLayer = localChunk.getBiomes()[layer]; - if (biomesLayer == null) { - continue; - } - for (int j = 0; j < biomesLayer.length; j++) { - if (biomesLayer[j] == null) { + for (int layer = 0; layer < localChunk.getBaseblocks().length; layer++) { + BiomeType[] biomesLayer = localChunk.getBiomes()[layer]; + if (biomesLayer == null) { continue; } - BiomeType biome = biomesLayer[j]; - int x = sx + MainUtil.x_loc[layer][j]; - int y = MainUtil.y_loc[layer][j]; - int z = sz + MainUtil.z_loc[layer][j]; - worldObj.setBiome(BlockVector3.at(x, y, z), biome); - } - } - if (localChunk.getTiles().size() > 0) { - localChunk.getTiles().forEach(((blockVector3, tag) -> { - try { - BaseBlock block = worldObj.getBlock(blockVector3).toBaseBlock(tag); - worldObj.setBlock(blockVector3, block, sideEffectSet); - } catch (WorldEditException ignored) { - StateWrapper sw = new StateWrapper(tag); - sw.restoreTag(worldObj.getName(), blockVector3.getX(), blockVector3.getY(), - blockVector3.getZ()); + for (int j = 0; j < biomesLayer.length; j++) { + if (biomesLayer[j] == null) { + continue; + } + BiomeType biome = biomesLayer[j]; + int x = sx + MainUtil.x_loc[layer][j]; + int y = MainUtil.y_loc[layer][j]; + int z = sz + MainUtil.z_loc[layer][j]; + worldObj.setBiome(BlockVector3.at(x, y, z), biome); } - })); - } - }); + } + if (localChunk.getTiles().size() > 0) { + localChunk.getTiles().forEach(((blockVector3, tag) -> { + try { + BaseBlock block = worldObj.getBlock(blockVector3).toBaseBlock(tag); + worldObj.setBlock(blockVector3, block, sideEffectSet); + } catch (WorldEditException ignored) { + StateWrapper sw = new StateWrapper(tag); + sw.restoreTag(worldObj.getName(), blockVector3.getX(), + blockVector3.getY(), blockVector3.getZ()); + } + })); + } + }); return super.enqueue(); } + @Override public void setCompleteTask(Runnable whenDone) { + this.whenDone = whenDone; + } + private void setMaterial(@Nonnull final BlockState plotBlock, @Nonnull final Block block) { Material material = BukkitAdapter.adapt(plotBlock.getBlockType()); block.setType(material, false); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java index 3a18ec355..6a67c83e1 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java @@ -30,7 +30,7 @@ import com.plotsquared.bukkit.util.BukkitBlockUtil; import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.core.location.ChunkWrapper; import com.plotsquared.core.location.Location; -import com.plotsquared.core.queue.ScopedLocalBlockQueue; +import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.PatternUtil; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -41,16 +41,17 @@ import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockTypes; import lombok.Getter; import lombok.Setter; +import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.ChunkGenerator.BiomeGrid; import org.bukkit.generator.ChunkGenerator.ChunkData; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; import java.util.Arrays; -public class GenChunk extends ScopedLocalBlockQueue { +public class GenChunk extends ScopedQueueCoordinator { public final Biome[] biomes; public BlockState[][] result; @@ -191,16 +192,18 @@ public class GenChunk extends ScopedLocalBlockQueue { return chunk == null ? chunkZ : chunk.getZ(); } - @Override public String getWorld() { - return chunk == null ? world : chunk.getWorld().getName(); + @Override public com.sk89q.worldedit.world.World getWorld() { + return chunk == null ? + BukkitAdapter.adapt(Bukkit.getWorld(world)) : + BukkitAdapter.adapt(chunk.getWorld()); } @Override public Location getMax() { - return Location.at(getWorld(), 15 + (getX() << 4), 255, 15 + (getZ() << 4)); + return Location.at(getWorld().getName(), 15 + (getX() << 4), 255, 15 + (getZ() << 4)); } @Override public Location getMin() { - return Location.at(getWorld(), getX() << 4, 0, getZ() << 4); + return Location.at(getWorld().getName(), getX() << 4, 0, getZ() << 4); } public GenChunk clone() { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/BukkitSchematicHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/BukkitSchematicHandler.java index e2e22ed3c..b3dff7e2d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/BukkitSchematicHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/BukkitSchematicHandler.java @@ -27,7 +27,7 @@ package com.plotsquared.bukkit.schematic; import com.google.inject.Inject; import com.google.inject.Singleton; -import com.plotsquared.core.queue.LocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.SchematicHandler; import com.plotsquared.core.util.WorldUtil; import com.sk89q.jnbt.CompoundTag; @@ -43,7 +43,7 @@ import javax.annotation.Nonnull; } @Override - public boolean restoreTile(LocalBlockQueue queue, CompoundTag ct, int x, int y, int z) { - return new StateWrapper(ct).restoreTag(queue.getWorld(), x, y, z); + public boolean restoreTile(QueueCoordinator queue, CompoundTag ct, int x, int y, int z) { + return new StateWrapper(ct).restoreTag(queue.getWorld().getName(), x, y, z); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java index 325d47544..24551aadb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java @@ -28,7 +28,7 @@ package com.plotsquared.bukkit.util; import com.google.inject.Singleton; import com.plotsquared.core.PlotSquared; import com.plotsquared.core.listener.WEExtent; -import com.plotsquared.core.queue.LocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.entity.EntityCategories; import com.plotsquared.core.util.task.TaskManager; @@ -54,7 +54,8 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_MOB; import static com.plotsquared.core.util.entity.EntityCategories.CAP_MONSTER; import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; -@Singleton public class BukkitChunkManager extends ChunkManager { +@Singleton +public class BukkitChunkManager extends ChunkManager { public static boolean isIn(CuboidRegion region, int x, int z) { return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX() @@ -79,8 +80,10 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; BukkitWorld bukkitWorld1 = new BukkitWorld(world1); BukkitWorld bukkitWorld2 = new BukkitWorld(world2); - LocalBlockQueue queue1 = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(worldName1, false); - LocalBlockQueue queue2 = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(worldName2, false); + QueueCoordinator queue1 = + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(worldName1, false); + QueueCoordinator queue2 = + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(worldName2, false); for (int x = Math.max(r1.getMinimumPoint().getX(), sx); x <= Math.min(r1.getMaximumPoint().getX(), sx + 15); x++) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java index 55dc45512..e95f469af 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java @@ -35,8 +35,8 @@ import com.plotsquared.core.location.PlotLoc; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotManager; -import com.plotsquared.core.queue.LocalBlockQueue; -import com.plotsquared.core.queue.ScopedLocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; +import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.RegionManager; @@ -78,9 +78,11 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_MOB; import static com.plotsquared.core.util.entity.EntityCategories.CAP_MONSTER; import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; -@Singleton public class BukkitRegionManager extends RegionManager { +@Singleton +public class BukkitRegionManager extends RegionManager { - private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitRegionManager.class.getSimpleName()); + private static final Logger logger = + LoggerFactory.getLogger("P2/" + BukkitRegionManager.class.getSimpleName()); @Inject public BukkitRegionManager(@Nonnull final ChunkManager chunkManager) { super(chunkManager); @@ -102,14 +104,16 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; final Semaphore semaphore = new Semaphore(1); try { semaphore.acquire(); - Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> { - for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)) - .getLoadedChunks()) { - BlockVector2 loc = BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5); - chunks.add(loc); - } - semaphore.release(); - }); + Bukkit.getScheduler() + .runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> { + for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)) + .getLoadedChunks()) { + BlockVector2 loc = + BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5); + chunks.add(loc); + } + semaphore.release(); + }); semaphore.acquireUninterruptibly(); } catch (final Exception e) { e.printStackTrace(); @@ -198,8 +202,7 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; return count; } - @Override - public boolean copyRegion(Location pos1, Location pos2, Location newPos, + @Override public boolean copyRegion(Location pos1, Location pos2, Location newPos, final Runnable whenDone) { final int relX = newPos.getX() - pos1.getX(); final int relZ = newPos.getZ() - pos1.getZ(); @@ -213,7 +216,8 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; assert oldWorld != null; final String newWorldName = newWorld.getName(); final ContentMap map = new ContentMap(); - final LocalBlockQueue queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(newWorldName, false); + final QueueCoordinator queue = + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(newWorldName, false); ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { @Override public void run(int[] value) { int bx = value[2]; @@ -243,18 +247,17 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; } } } - queue.enqueue(); - PlotSquared.platform().getGlobalBlockQueue().addEmptyTask(() -> { + queue.setCompleteTask(() -> { //map.restoreBlocks(newWorld, 0, 0); map.restoreEntities(newWorld, relX, relZ); TaskManager.runTask(whenDone); }); + queue.enqueue(); }, 5); return true; } - @Override - public boolean regenerateRegion(final Location pos1, final Location pos2, + @Override public boolean regenerateRegion(final Location pos1, final Location pos2, final boolean ignoreAugment, final Runnable whenDone) { final String world = pos1.getWorldName(); @@ -292,8 +295,8 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; if (chunkObj == null) { return; } - final LocalBlockQueue queue = PlotSquared.platform().getGlobalBlockQueue() - .getNewQueue(world, false); + final QueueCoordinator queue = + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false); if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) { AugmentedUtils.bypass(ignoreAugment, () -> queue.regenChunkSafe(chunk.getX(), chunk.getZ())); @@ -362,8 +365,8 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; .createRegion(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); map.saveEntitiesOut(chunkObj, currentPlotClear); AugmentedUtils.bypass(ignoreAugment, () -> ChunkManager - .setChunkInPlotArea(null, new RunnableVal() { - @Override public void run(ScopedLocalBlockQueue value) { + .setChunkInPlotArea(null, new RunnableVal() { + @Override public void run(ScopedQueueCoordinator value) { Location min = value.getMin(); int bx = min.getX(); int bz = min.getZ(); @@ -429,8 +432,7 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; } } - @Override - public void swap(Location bot1, Location top1, Location bot2, Location top2, + @Override public void swap(Location bot1, Location top1, Location bot2, Location top2, final Runnable whenDone) { CuboidRegion region1 = RegionUtil.createRegion(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); @@ -468,16 +470,17 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; region.getMinimumPoint().getY(), region.getMinimumPoint().getZ() - extendBiome); Location pos2 = Location.at(world, region.getMaximumPoint().getX() + extendBiome, region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome); - final LocalBlockQueue queue = PlotSquared.platform().getGlobalBlockQueue() - .getNewQueue(world, false); + final QueueCoordinator queue = + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false); ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { @Override public void run(int[] value) { BlockVector2 loc = BlockVector2.at(value[0], value[1]); - PlotSquared.platform().getChunkManager().loadChunk(world, loc, false).thenRun(() -> { - MainUtil.setBiome(world, value[2], value[3], value[4], value[5], biome); - queue.refreshChunk(value[0], value[1]); - }); + PlotSquared.platform().getChunkManager().loadChunk(world, loc, false) + .thenRun(() -> { + MainUtil.setBiome(world, value[2], value[3], value[4], value[5], biome); + queue.refreshChunk(value[0], value[1]); + }); } }, whenDone, 5); } diff --git a/Core/src/main/java/com/plotsquared/core/command/Relight.java b/Core/src/main/java/com/plotsquared/core/command/Relight.java index 4a2475b5f..308e7d451 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Relight.java +++ b/Core/src/main/java/com/plotsquared/core/command/Relight.java @@ -28,7 +28,7 @@ package com.plotsquared.core.command; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; -import com.plotsquared.core.queue.LocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.RunnableVal2; @@ -50,12 +50,13 @@ public class Relight extends Command { public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { - final Plot plot = player.getCurrentPlot(); + player.sendMessage("Not implemented."); +/* final Plot plot = player.getCurrentPlot(); if (plot == null) { Captions.NOT_IN_PLOT.send(player); return CompletableFuture.completedFuture(false); } - final LocalBlockQueue queue = plot.getArea().getQueue(false); + final QueueCoordinator queue = plot.getArea().getQueue(false); ChunkManager.chunkTask(plot, new RunnableVal() { @Override public void run(int[] value) { queue.fixChunkLighting(value[0], value[1]); @@ -63,7 +64,7 @@ public class Relight extends Command { }, () -> { plot.refreshChunks(); Captions.SET_BLOCK_ACTION_FINISHED.send(player); - }, 5); + }, 5);*/ return CompletableFuture.completedFuture(true); } diff --git a/Core/src/main/java/com/plotsquared/core/command/Trim.java b/Core/src/main/java/com/plotsquared/core/command/Trim.java index abdfb0a23..346eb17ab 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Trim.java +++ b/Core/src/main/java/com/plotsquared/core/command/Trim.java @@ -34,7 +34,7 @@ import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.expiration.ExpireManager; import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.queue.GlobalBlockQueue; -import com.plotsquared.core.queue.LocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.RegionUtil; @@ -188,7 +188,7 @@ public class Trim extends SubCommand { } } } - final LocalBlockQueue queue = blockQueue.getNewQueue(world, false); + final QueueCoordinator queue = blockQueue.getNewQueue(world, false); TaskManager.objectTask(chunks, new RunnableVal() { @Override public void run(BlockVector2 value) { queue.regenChunk(value.getX(), value.getZ()); diff --git a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java index e672a1fdf..b40e718af 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java @@ -31,17 +31,17 @@ import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotAreaTerrainType; import com.plotsquared.core.plot.PlotAreaType; import com.plotsquared.core.plot.PlotManager; -import com.plotsquared.core.queue.AreaBoundDelegateLocalBlockQueue; -import com.plotsquared.core.queue.LocalBlockQueue; -import com.plotsquared.core.queue.LocationOffsetDelegateLocalBlockQueue; -import com.plotsquared.core.queue.ScopedLocalBlockQueue; +import com.plotsquared.core.queue.AreaBoundDelegateQueueCoordinator; +import com.plotsquared.core.queue.LocationOffsetDelegateQueueCoordinator; +import com.plotsquared.core.queue.QueueCoordinator; +import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.RegionUtil; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockTypes; + import javax.annotation.Nonnull; import javax.annotation.Nullable; - import java.util.Set; public class AugmentedUtils { @@ -55,7 +55,7 @@ public class AugmentedUtils { } public static boolean generate(@Nullable Object chunkObject, @Nonnull final String world, - final int chunkX, final int chunkZ, LocalBlockQueue queue) { + final int chunkX, final int chunkZ, QueueCoordinator queue) { if (!enabled) { return false; } @@ -67,7 +67,8 @@ public class AugmentedUtils { // entire chunk CuboidRegion region = RegionUtil.createRegion(blockX, blockX + 15, blockZ, blockZ + 15); // Query for plot areas in the chunk - final Set areas = PlotSquared.get().getPlotAreaManager().getPlotAreasSet(world, region); + final Set areas = + PlotSquared.get().getPlotAreaManager().getPlotAreasSet(world, region); if (areas.isEmpty()) { return false; } @@ -89,7 +90,7 @@ public class AugmentedUtils { queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false); queue.setChunkObject(chunkObject); } - LocalBlockQueue primaryMask; + QueueCoordinator primaryMask; // coordinates int relativeBottomX; int relativeBottomZ; @@ -102,14 +103,14 @@ public class AugmentedUtils { relativeTopX = Math.min(15, area.getRegion().getMaximumPoint().getX() - blockX); relativeTopZ = Math.min(15, area.getRegion().getMaximumPoint().getZ() - blockZ); - primaryMask = new AreaBoundDelegateLocalBlockQueue(area, queue); + primaryMask = new AreaBoundDelegateQueueCoordinator(area, queue); } else { relativeBottomX = relativeBottomZ = 0; relativeTopX = relativeTopZ = 15; primaryMask = queue; } - LocalBlockQueue secondaryMask; + QueueCoordinator secondaryMask; BlockState air = BlockTypes.AIR.getDefaultState(); if (area.getTerrain() == PlotAreaTerrainType.ROAD) { PlotManager manager = area.getPlotManager(); @@ -133,7 +134,7 @@ public class AugmentedUtils { continue; } generationResult = true; - secondaryMask = new LocationOffsetDelegateLocalBlockQueue(canPlace, blockX, blockZ, + secondaryMask = new LocationOffsetDelegateQueueCoordinator(canPlace, blockX, blockZ, primaryMask); } else { secondaryMask = primaryMask; @@ -151,15 +152,15 @@ public class AugmentedUtils { secondaryMask.setChunkObject(chunkObject); secondaryMask.setForceSync(true); - ScopedLocalBlockQueue scoped = - new ScopedLocalBlockQueue(secondaryMask, Location.at(world, blockX, 0, blockZ), + ScopedQueueCoordinator scoped = + new ScopedQueueCoordinator(secondaryMask, Location.at(world, blockX, 0, blockZ), Location.at(world, blockX + 15, 255, blockZ + 15)); generator.generateChunk(scoped, area); generator.populateChunk(scoped, area); } if (queue != null) { queue.setForceSync(true); - queue.flush(); + queue.enqueue(); } return generationResult; } diff --git a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java index ac6aca214..b046da010 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java @@ -33,7 +33,7 @@ import com.plotsquared.core.plot.BlockBucket; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotAreaTerrainType; import com.plotsquared.core.plot.PlotId; -import com.plotsquared.core.queue.LocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.BlockUtil; import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.RegionManager; @@ -136,7 +136,7 @@ public class ClassicPlotManager extends SquarePlotManager { return false; } Location[] corners = plot.getCorners(); - LocalBlockQueue queue = classicPlotWorld.getQueue(false); + QueueCoordinator queue = classicPlotWorld.getQueue(false); int x = MathMan.average(corners[0].getX(), corners[1].getX()); int z = MathMan.average(corners[0].getZ(), corners[1].getZ()); @@ -157,7 +157,7 @@ public class ClassicPlotManager extends SquarePlotManager { Plot plot = classicPlotWorld.getPlotAbs(plotId); Location bottom = plot.getBottomAbs(); Location top = plot.getExtendedTopAbs(); - LocalBlockQueue queue = classicPlotWorld.getQueue(false); + QueueCoordinator queue = classicPlotWorld.getQueue(false); int maxY = classicPlotWorld.getPlotManager().getWorldHeight(); if (!plot.getMerged(Direction.NORTH)) { int z = bottom.getZ(); @@ -221,7 +221,7 @@ public class ClassicPlotManager extends SquarePlotManager { .subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1); - LocalBlockQueue queue = classicPlotWorld.getQueue(false); + QueueCoordinator queue = classicPlotWorld.getQueue(false); if (!plot.getMerged(Direction.NORTH)) { int z = bot.getZ(); for (int x = bot.getX(); x < top.getX(); x++) { @@ -274,7 +274,7 @@ public class ClassicPlotManager extends SquarePlotManager { .subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1); - LocalBlockQueue queue = classicPlotWorld.getQueue(false); + QueueCoordinator queue = classicPlotWorld.getQueue(false); int y = classicPlotWorld.WALL_HEIGHT + 1; if (!plot.getMerged(Direction.NORTH)) { int z = bot.getZ(); @@ -315,7 +315,7 @@ public class ClassicPlotManager extends SquarePlotManager { int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = pos1.getZ() - 2; int ez = pos2.getZ() + 2; - LocalBlockQueue queue = classicPlotWorld.getQueue(false); + QueueCoordinator queue = classicPlotWorld.getQueue(false); int maxY = getWorldHeight(); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz + 1), @@ -353,7 +353,7 @@ public class ClassicPlotManager extends SquarePlotManager { int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; int sx = pos1.getX() - 2; int ex = pos2.getX() + 2; - LocalBlockQueue queue = classicPlotWorld.getQueue(false); + QueueCoordinator queue = classicPlotWorld.getQueue(false); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location.at(classicPlotWorld.getWorldName(), ex - 1, @@ -390,7 +390,7 @@ public class ClassicPlotManager extends SquarePlotManager { int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = pos2.getZ() + 1; int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; - LocalBlockQueue queue = classicPlotWorld.getQueue(false); + QueueCoordinator queue = classicPlotWorld.getQueue(false); queue.setCuboid( Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.ROAD_HEIGHT + 1, sz + 1), Location.at(classicPlotWorld.getWorldName(), ex - 1, @@ -412,7 +412,7 @@ public class ClassicPlotManager extends SquarePlotManager { int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = pos1.getZ() - 1; int ez = pos2.getZ() + 1; - LocalBlockQueue queue = classicPlotWorld.getQueue(false); + QueueCoordinator queue = classicPlotWorld.getQueue(false); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location.at(classicPlotWorld.getWorldName(), ex, @@ -435,7 +435,7 @@ public class ClassicPlotManager extends SquarePlotManager { int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; int sx = pos1.getX() - 1; int ex = pos2.getX() + 1; - LocalBlockQueue queue = classicPlotWorld.getQueue(false); + QueueCoordinator queue = classicPlotWorld.getQueue(false); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location.at(classicPlotWorld.getWorldName(), ex, @@ -457,7 +457,7 @@ public class ClassicPlotManager extends SquarePlotManager { int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = location.getZ() + 1; int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; - LocalBlockQueue queue = classicPlotWorld.getQueue(false); + QueueCoordinator queue = classicPlotWorld.getQueue(false); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location.at(classicPlotWorld.getWorldName(), ex, diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridGen.java b/Core/src/main/java/com/plotsquared/core/generator/HybridGen.java index 2560981ab..e91d3104d 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridGen.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridGen.java @@ -33,7 +33,7 @@ import com.plotsquared.core.inject.factory.HybridPlotWorldFactory; import com.plotsquared.core.location.Location; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotId; -import com.plotsquared.core.queue.ScopedLocalBlockQueue; +import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.MathMan; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; @@ -52,7 +52,7 @@ public class HybridGen extends IndependentPlotGenerator { return PlotSquared.platform().getPluginName(); } - private void placeSchem(HybridPlotWorld world, ScopedLocalBlockQueue result, short relativeX, + private void placeSchem(HybridPlotWorld world, ScopedQueueCoordinator result, short relativeX, short relativeZ, int x, int z, boolean isRoad) { int minY; // Math.min(world.PLOT_HEIGHT, world.ROAD_HEIGHT); if ((isRoad && Settings.Schematics.PASTE_ROAD_ON_TOP) || (!isRoad @@ -76,7 +76,7 @@ public class HybridGen extends IndependentPlotGenerator { } @Override - public void generateChunk(@Nonnull ScopedLocalBlockQueue result, @Nonnull PlotArea settings) { + public void generateChunk(@Nonnull ScopedQueueCoordinator result, @Nonnull PlotArea settings) { Preconditions.checkNotNull(result, "result cannot be null"); Preconditions.checkNotNull(settings, "settings cannot be null"); diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java index e7fd298a0..93351b314 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java @@ -34,7 +34,7 @@ import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotAreaTerrainType; import com.plotsquared.core.plot.PlotAreaType; import com.plotsquared.core.plot.PlotId; -import com.plotsquared.core.queue.LocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.FileBytes; import com.plotsquared.core.util.MainUtil; @@ -47,8 +47,8 @@ import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockTypes; import lombok.Getter; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -62,7 +62,7 @@ public class HybridPlotManager extends ClassicPlotManager { private final RegionManager regionManager; public HybridPlotManager(@Nonnull final HybridPlotWorld hybridPlotWorld, - @Nonnull final RegionManager regionManager) { + @Nonnull final RegionManager regionManager) { super(hybridPlotWorld, regionManager); this.hybridPlotWorld = hybridPlotWorld; this.regionManager = regionManager; @@ -106,20 +106,22 @@ public class HybridPlotManager extends ClassicPlotManager { PlotId id2 = new PlotId(id.x + 1, id.y); Location bot = getPlotBottomLocAbs(id2); Location top = getPlotTopLocAbs(id); - Location pos1 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, 0, bot.getZ() - 1); - Location pos2 = Location.at(hybridPlotWorld.getWorldName(), bot.getX(), - Math.min(getWorldHeight(), 255), top.getZ() + 1); + Location pos1 = + Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, 0, bot.getZ() - 1); + Location pos2 = Location + .at(hybridPlotWorld.getWorldName(), bot.getX(), Math.min(getWorldHeight(), 255), + top.getZ() + 1); MainUtil.resetBiome(hybridPlotWorld, pos1, pos2); if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; } - LocalBlockQueue queue = hybridPlotWorld.getQueue(false); + QueueCoordinator queue = hybridPlotWorld.getQueue(false); createSchemAbs(queue, pos1, pos2, true); queue.enqueue(); return true; } - private void createSchemAbs(LocalBlockQueue queue, Location pos1, Location pos2, + private void createSchemAbs(QueueCoordinator queue, Location pos1, Location pos2, boolean isRoad) { int size = hybridPlotWorld.SIZE; int minY; @@ -167,14 +169,16 @@ public class HybridPlotManager extends ClassicPlotManager { PlotId id2 = new PlotId(id.x, id.y + 1); Location bot = getPlotBottomLocAbs(id2); Location top = getPlotTopLocAbs(id); - Location pos1 = Location.at(hybridPlotWorld.getWorldName(), bot.getX() - 1, 0, top.getZ() + 1); - Location pos2 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, - Math.min(getWorldHeight(), 255), bot.getZ()); + Location pos1 = + Location.at(hybridPlotWorld.getWorldName(), bot.getX() - 1, 0, top.getZ() + 1); + Location pos2 = Location + .at(hybridPlotWorld.getWorldName(), top.getX() + 1, Math.min(getWorldHeight(), 255), + bot.getZ()); MainUtil.resetBiome(hybridPlotWorld, pos1, pos2); if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; } - LocalBlockQueue queue = hybridPlotWorld.getQueue(false); + QueueCoordinator queue = hybridPlotWorld.getQueue(false); createSchemAbs(queue, pos1, pos2, true); queue.enqueue(); return true; @@ -186,7 +190,7 @@ public class HybridPlotManager extends ClassicPlotManager { PlotId id2 = new PlotId(id.x + 1, id.y + 1); Location pos1 = getPlotTopLocAbs(id).add(1, 0, 1).withY(0); Location pos2 = getPlotBottomLocAbs(id2).withY(Math.min(getWorldHeight(), 255)); - LocalBlockQueue queue = hybridPlotWorld.getQueue(false); + QueueCoordinator queue = hybridPlotWorld.getQueue(false); createSchemAbs(queue, pos1, pos2, true); if (hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { createSchemAbs(queue, pos1, pos2, true); @@ -228,7 +232,7 @@ public class HybridPlotManager extends ClassicPlotManager { } final BiomeType biome = hybridPlotWorld.getPlotBiome(); - final LocalBlockQueue queue = hybridPlotWorld.getQueue(false); + final QueueCoordinator queue = hybridPlotWorld.getQueue(false); ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { @Override public void run(int[] value) { // If the chunk isn't near the edge and it isn't an augmented world we can just regen the whole chunk @@ -257,14 +261,14 @@ public class HybridPlotManager extends ClassicPlotManager { pastePlotSchematic(queue, bot, top); } }, () -> { - queue.enqueue(); // And notify whatever called this when plot clearing is done - PlotSquared.platform().getGlobalBlockQueue().addEmptyTask(whenDone); + queue.setCompleteTask(whenDone); + queue.enqueue(); }, 10); return true; } - public void pastePlotSchematic(LocalBlockQueue queue, Location bottom, Location top) { + public void pastePlotSchematic(QueueCoordinator queue, Location bottom, Location top) { if (!hybridPlotWorld.PLOT_SCHEMATIC) { return; } diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index 30586db05..46ba52cf7 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -42,9 +42,9 @@ import com.plotsquared.core.plot.flag.GlobalFlagContainer; import com.plotsquared.core.plot.flag.PlotFlag; import com.plotsquared.core.plot.flag.implementations.AnalysisFlag; import com.plotsquared.core.plot.world.PlotAreaManager; -import com.plotsquared.core.queue.ChunkBlockQueue; +import com.plotsquared.core.queue.ChunkQueueCoordinator; import com.plotsquared.core.queue.GlobalBlockQueue; -import com.plotsquared.core.queue.LocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MathMan; @@ -128,7 +128,7 @@ public class HybridUtils { * */ TaskManager.runTaskAsync(() -> { - final LocalBlockQueue queue = blockQueue.getNewQueue(world, false); + final QueueCoordinator queue = blockQueue.getNewQueue(world, false); final BlockVector3 bot = region.getMinimumPoint(); final BlockVector3 top = region.getMaximumPoint(); @@ -152,7 +152,7 @@ public class HybridUtils { } HybridPlotWorld hpw = (HybridPlotWorld) area; - ChunkBlockQueue chunk = new ChunkBlockQueue(bot, top, false); + ChunkQueueCoordinator chunk = new ChunkQueueCoordinator(bot, top, false); hpw.getGenerator().generateChunk(chunk, hpw); final BlockState[][][] oldBlocks = chunk.getBlocks(); @@ -374,7 +374,7 @@ public class HybridUtils { run.run(); } - public int checkModified(LocalBlockQueue queue, int x1, int x2, int y1, int y2, int z1, int z2, + public int checkModified(QueueCoordinator queue, int x1, int x2, int y1, int y2, int z1, int z2, BlockState[] blocks) { int count = 0; for (int y = y1; y <= y2; y++) { @@ -521,7 +521,7 @@ public class HybridUtils { public boolean setupRoadSchematic(Plot plot) { final String world = plot.getWorldName(); - final LocalBlockQueue queue = blockQueue.getNewQueue(world, false); + final QueueCoordinator queue = blockQueue.getNewQueue(world, false); Location bot = plot.getBottomAbs().subtract(1, 0, 1); Location top = plot.getTopAbs(); final HybridPlotWorld plotworld = (HybridPlotWorld) plot.getArea(); @@ -564,7 +564,7 @@ public class HybridUtils { return true; } - public int get_ey(final PlotManager pm, LocalBlockQueue queue, int sx, int ex, int sz, int ez, + public int get_ey(final PlotManager pm, QueueCoordinator queue, int sx, int ex, int sz, int ez, int sy) { int ey = sy; for (int x = sx; x <= ex; x++) { @@ -608,7 +608,7 @@ public class HybridUtils { z -= plotWorld.ROAD_OFFSET_Z; final int finalX = x; final int finalZ = z; - LocalBlockQueue queue = this.blockQueue.getNewQueue(plotWorld.getWorldName(), false); + QueueCoordinator queue = this.blockQueue.getNewQueue(plotWorld.getWorldName(), false); if (id1 == null || id2 == null || id1 != id2) { this.chunkManager.loadChunk(area.getWorldName(), chunk, false).thenRun(() -> { if (id1 != null) { diff --git a/Core/src/main/java/com/plotsquared/core/generator/IndependentPlotGenerator.java b/Core/src/main/java/com/plotsquared/core/generator/IndependentPlotGenerator.java index c42e54546..f3675ab40 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/IndependentPlotGenerator.java +++ b/Core/src/main/java/com/plotsquared/core/generator/IndependentPlotGenerator.java @@ -29,7 +29,7 @@ import com.plotsquared.core.PlotSquared; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.plot.SetupObject; -import com.plotsquared.core.queue.ScopedLocalBlockQueue; +import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.setup.PlotAreaBuilder; /** @@ -52,9 +52,9 @@ public abstract class IndependentPlotGenerator { * @param result * @param settings */ - public abstract void generateChunk(ScopedLocalBlockQueue result, PlotArea settings); + public abstract void generateChunk(ScopedQueueCoordinator result, PlotArea settings); - public boolean populateChunk(ScopedLocalBlockQueue result, PlotArea setting) { + public boolean populateChunk(ScopedQueueCoordinator result, PlotArea setting) { return false; } @@ -75,8 +75,7 @@ public abstract class IndependentPlotGenerator { * * @param setup */ - @Deprecated - public void processSetup(SetupObject setup) { + @Deprecated public void processSetup(SetupObject setup) { } /** @@ -85,7 +84,8 @@ public abstract class IndependentPlotGenerator { * * @param builder the area builder to modify */ - public void processAreaSetup(PlotAreaBuilder builder) { } + public void processAreaSetup(PlotAreaBuilder builder) { + } /** * It is preferred for the PlotArea object to do most of the initialization necessary. diff --git a/Core/src/main/java/com/plotsquared/core/generator/SingleWorldGenerator.java b/Core/src/main/java/com/plotsquared/core/generator/SingleWorldGenerator.java index 7e2f164d3..60552ac74 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/SingleWorldGenerator.java +++ b/Core/src/main/java/com/plotsquared/core/generator/SingleWorldGenerator.java @@ -32,7 +32,7 @@ import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.plot.world.SinglePlotArea; import com.plotsquared.core.plot.world.SinglePlotAreaManager; -import com.plotsquared.core.queue.ScopedLocalBlockQueue; +import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.sk89q.worldedit.world.biome.BiomeTypes; import com.sk89q.worldedit.world.block.BlockTypes; import javax.annotation.Nonnull; @@ -56,7 +56,7 @@ public class SingleWorldGenerator extends IndependentPlotGenerator { return "PlotSquared:single"; } - @Override public void generateChunk(ScopedLocalBlockQueue result, PlotArea settings) { + @Override public void generateChunk(ScopedQueueCoordinator result, PlotArea settings) { SinglePlotArea area = (SinglePlotArea) settings; if (area.VOID) { Location min = result.getMin(); diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index 70f39aa08..3fa208228 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -56,7 +56,7 @@ import com.plotsquared.core.plot.flag.PlotFlag; import com.plotsquared.core.plot.flag.implementations.KeepFlag; import com.plotsquared.core.plot.schematic.Schematic; import com.plotsquared.core.queue.GlobalBlockQueue; -import com.plotsquared.core.queue.LocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MathMan; @@ -75,11 +75,11 @@ import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BlockTypes; import lombok.Getter; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.awt.geom.Area; import java.awt.geom.PathIterator; import java.awt.geom.Rectangle2D; @@ -123,24 +123,13 @@ import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; */ public class Plot { - private static final Logger logger = LoggerFactory.getLogger("P2/" + Plot.class.getSimpleName()); - public static final int MAX_HEIGHT = 256; - + private static final Logger logger = + LoggerFactory.getLogger("P2/" + Plot.class.getSimpleName()); private static Set connected_cache; private static Set regions_cache; @Nonnull private final PlotId id; - - // These will be injected - @Inject private EventDispatcher eventDispatcher; - @Inject private PlotListener plotListener; - @Inject private RegionManager regionManager; - @Inject private GlobalBlockQueue blockQueue; - @Inject private WorldUtil worldUtil; - @Inject private SchematicHandler schematicHandler; - @Inject @ImpromptuPipeline private UUIDPipeline impromptuPipeline; - /** * Plot flag container */ @@ -149,7 +138,6 @@ public class Plot { * Has the plot changed since the last save cycle? */ public boolean countsTowardsMax = true; - /** * Represents whatever the database manager needs it to:
* - A value of -1 usually indicates the plot will not be stored in the DB
@@ -158,6 +146,14 @@ public class Plot { * @deprecated magical */ @Deprecated public int temp; + // These will be injected + @Inject private EventDispatcher eventDispatcher; + @Inject private PlotListener plotListener; + @Inject private RegionManager regionManager; + @Inject private GlobalBlockQueue blockQueue; + @Inject private WorldUtil worldUtil; + @Inject private SchematicHandler schematicHandler; + @Inject @ImpromptuPipeline private UUIDPipeline impromptuPipeline; /** * plot owner * (Merged plots can have multiple owners) @@ -945,9 +941,8 @@ public class Plot { if (isDelete) { this.removeSign(); } - PlotUnlinkEvent event = this.eventDispatcher - .callUnlink(getArea(), this, true, !isDelete, - isDelete ? PlotUnlinkEvent.REASON.DELETE : PlotUnlinkEvent.REASON.CLEAR); + PlotUnlinkEvent event = this.eventDispatcher.callUnlink(getArea(), this, true, !isDelete, + isDelete ? PlotUnlinkEvent.REASON.DELETE : PlotUnlinkEvent.REASON.CLEAR); if (event.getEventResult() != Result.DENY) { this.unlinkPlot(event.isCreateRoad(), event.isCreateSign()); } @@ -975,7 +970,8 @@ public class Plot { Plot current = queue.poll(); if (Plot.this.area.getTerrain() != PlotAreaTerrainType.NONE) { try { - regionManager.regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, + regionManager + .regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, this); } catch (UnsupportedOperationException exception) { MainUtil.sendMessage(null, @@ -1099,7 +1095,8 @@ public class Plot { "%plr%", name), Captions.OWNER_SIGN_LINE_4.formatted().replaceAll("%id%", id).replaceAll( "%plr%", name)}; - this.worldUtil.setSign(this.getWorldName(), location.getX(), location.getY(), location.getZ(), + this.worldUtil + .setSign(this.getWorldName(), location.getX(), location.getY(), location.getZ(), lines); } } @@ -1348,8 +1345,8 @@ public class Plot { if (Settings.Backup.DELETE_ON_UNCLAIM) { // Destroy all backups when the plot is unclaimed - Objects.requireNonNull(PlotSquared.platform()).getBackupManager().getProfile(current) - .destroy(); + Objects.requireNonNull(PlotSquared.platform()).getBackupManager() + .getProfile(current).destroy(); } getArea().removePlot(getId()); @@ -1377,7 +1374,8 @@ public class Plot { Location[] corners = getCorners(); Location top = corners[0]; Location bot = corners[1]; - Location location = Location.at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), + Location location = Location + .at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ())); if (!isLoaded()) { result.accept(location); @@ -1399,12 +1397,14 @@ public class Plot { Location[] corners = getCorners(); Location top = corners[0]; Location bot = corners[1]; - Location location = Location.at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), - MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ())); + Location location = Location + .at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), + MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ())); if (!isLoaded()) { return location; } - int y = this.worldUtil.getHighestBlockSynchronous(getWorldName(), location.getX(), location.getZ()); + int y = this.worldUtil + .getHighestBlockSynchronous(getWorldName(), location.getX(), location.getZ()); if (area.allowSigns()) { y = Math.max(y, getManager().getSignLoc(this).getY()); } @@ -1459,14 +1459,16 @@ public class Plot { return this.getDefaultHomeSynchronous(true); } else { Location bottom = this.getBottomAbs(); - Location location = Location.at(bottom.getWorldName(), bottom.getX() + home.getX(), - bottom.getY() + home.getY(), bottom.getZ() + home.getZ(), home.getYaw(), - home.getPitch()); + Location location = Location + .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), + bottom.getZ() + home.getZ(), home.getYaw(), home.getPitch()); if (!isLoaded()) { return location; } - if (!this.worldUtil.getBlockSynchronous(location).getBlockType().getMaterial().isAir()) { - location = location.withY(Math.max(1 + this.worldUtil.getHighestBlockSynchronous(this.getWorldName(), location.getX(), + if (!this.worldUtil.getBlockSynchronous(location).getBlockType().getMaterial() + .isAir()) { + location = location.withY(Math.max(1 + this.worldUtil + .getHighestBlockSynchronous(this.getWorldName(), location.getX(), location.getZ()), bottom.getY())); } return location; @@ -1482,16 +1484,17 @@ public class Plot { this.getDefaultHome(result); } else { Location bottom = this.getBottomAbs(); - Location location = Location.at(bottom.getWorldName(), bottom.getX() + home.getX(), - bottom.getY() + home.getY(), bottom.getZ() + home.getZ(), home.getYaw(), - home.getPitch()); + Location location = Location + .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), + bottom.getZ() + home.getZ(), home.getYaw(), home.getPitch()); if (!isLoaded()) { result.accept(location); return; } this.worldUtil.getBlock(location, block -> { if (!block.getBlockType().getMaterial().isAir()) { - this.worldUtil.getHighestBlock(this.getWorldName(), location.getX(), location.getZ(), + this.worldUtil + .getHighestBlock(this.getWorldName(), location.getX(), location.getZ(), y -> result.accept(location.withY(Math.max(1 + y, bottom.getY())))); } else { result.accept(location); @@ -1683,7 +1686,7 @@ public class Plot { * This should not need to be called */ public void refreshChunks() { - LocalBlockQueue queue = this.blockQueue.getNewQueue(getWorldName(), false); + QueueCoordinator queue = this.blockQueue.getNewQueue(getWorldName(), false); HashSet chunks = new HashSet<>(); for (CuboidRegion region : Plot.this.getRegions()) { for (int x = region.getMinimumPoint().getX() >> 4; @@ -1707,10 +1710,10 @@ public class Plot { return; } Location location = manager.getSignLoc(this); - LocalBlockQueue queue = this.blockQueue.getNewQueue(getWorldName(), false); + QueueCoordinator queue = this.blockQueue.getNewQueue(getWorldName(), false); queue.setBlock(location.getX(), location.getY(), location.getZ(), BlockTypes.AIR.getDefaultState()); - queue.flush(); + queue.enqueue(); } /** @@ -1721,8 +1724,8 @@ public class Plot { this.setSign("unknown"); return; } - this.impromptuPipeline.getSingle(this.getOwnerAbs(), (username, sign) -> - this.setSign(username)); + this.impromptuPipeline + .getSingle(this.getOwnerAbs(), (username, sign) -> this.setSign(username)); } /** @@ -1749,7 +1752,8 @@ public class Plot { if (updateDB) { if (!create(player.getUUID(), true)) { - logger.error("[P2] Player {} attempted to claim plot {}, but the database failed to update", + logger.error( + "[P2] Player {} attempted to claim plot {}, but the database failed to update", player.getName(), this.getId().toCommaSeparatedString()); return false; } @@ -2919,13 +2923,16 @@ public class Plot { return; } final String string = - Captions.PLOT_DEBUG.getTranslated().replace("%plot%", this.toString()).replace("%message%", message); + Captions.PLOT_DEBUG.getTranslated().replace("%plot%", this.toString()) + .replace("%message%", message); for (final PlotPlayer player : players) { - if (isOwner(player.getUUID()) || Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_DEBUG_OTHER)) { + if (isOwner(player.getUUID()) || Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_DEBUG_OTHER)) { player.sendMessage(string); } } - } catch (final Exception ignored) {} + } catch (final Exception ignored) { + } } /** @@ -2977,8 +2984,7 @@ public class Plot { Consumer resultConsumer) { Plot plot = this.getBasePlot(false); Result result = - this.eventDispatcher.callTeleport(player, player.getLocation(), plot) - .getEventResult(); + this.eventDispatcher.callTeleport(player, player.getLocation(), plot).getEventResult(); if (result == Result.DENY) { sendMessage(player, Captions.EVENT_DENIED, "Teleport"); resultConsumer.accept(false); @@ -3214,8 +3220,10 @@ public class Plot { Location[] corners = MainUtil.getCorners(getWorldName(), region); Location pos1 = corners[0]; Location pos2 = corners[1]; - Location pos3 = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); - Location pos4 = pos2.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); + Location pos3 = + pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); + Location pos4 = + pos2.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); regionManager.swap(pos1, pos2, pos3, pos4, this); } } @@ -3246,7 +3254,8 @@ public class Plot { Location[] corners = MainUtil.getCorners(getWorldName(), region); final Location pos1 = corners[0]; final Location pos2 = corners[1]; - Location newPos = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); + Location newPos = + pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); regionManager.copyRegion(pos1, pos2, newPos, task); } }.run(); @@ -3340,7 +3349,8 @@ public class Plot { Location[] corners = MainUtil.getCorners(getWorldName(), region); Location pos1 = corners[0]; Location pos2 = corners[1]; - Location newPos = pos1 .add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); + Location newPos = + pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); regionManager.copyRegion(pos1, pos2, newPos, this); } }; diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java index 9ad26c0aa..4aecc38d9 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java @@ -27,7 +27,6 @@ package com.plotsquared.core.plot; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.plotsquared.core.PlotSquared; import com.plotsquared.core.collection.QuadMap; import com.plotsquared.core.configuration.CaptionUtility; import com.plotsquared.core.configuration.Captions; @@ -49,7 +48,7 @@ import com.plotsquared.core.plot.flag.GlobalFlagContainer; import com.plotsquared.core.plot.flag.PlotFlag; import com.plotsquared.core.plot.flag.implementations.DoneFlag; import com.plotsquared.core.queue.GlobalBlockQueue; -import com.plotsquared.core.queue.LocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.Expression; import com.plotsquared.core.util.MainUtil; @@ -172,7 +171,7 @@ public abstract class PlotArea { @Nonnull protected abstract PlotManager createManager(); - public LocalBlockQueue getQueue(final boolean autoQueue) { + public QueueCoordinator getQueue(final boolean autoQueue) { return this.globalBlockQueue.getNewQueue(worldName, autoQueue); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java index ac427471d..2d13a70e3 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java @@ -75,6 +75,13 @@ public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator return false; } + @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { + if (area.contains(x, z)) { + return super.setBiome(x, y, z, biome); + } + return false; + } + @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { if (area.contains(x, z)) { return super.setTile(x, y, z, tag); diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index 3b20d17c6..3e3e8c4cf 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -99,7 +99,16 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { @Override public final boolean setBiome(int x, int z, BiomeType biomeType) { LocalChunk chunk = getChunk(x >> 4, z >> 4); - chunk.setBiome(x & 15, z & 15, biomeType); + for (int y = 0; y < 256; y++) { + chunk.setBiome(x & 15, y, z & 15, biomeType); + } + settingBiomes = true; + return true; + } + + @Override public final boolean setBiome(int x, int y, int z, BiomeType biomeType) { + LocalChunk chunk = getChunk(x >> 4, z >> 4); + chunk.setBiome(x & 15, y, z & 15, biomeType); settingBiomes = true; return true; } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java index e221ee7ad..820cffa61 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java @@ -35,11 +35,10 @@ import com.sk89q.worldedit.world.block.BlockState; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.Arrays; public class ChunkQueueCoordinator extends ScopedQueueCoordinator { - public final BiomeType[] biomeGrid; + public final BiomeType[][][] biomeResult; public final BlockState[][][] result; private final int width; private final int length; @@ -51,7 +50,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { this.width = top.getX() - bot.getX() + 1; this.length = top.getZ() - bot.getZ() + 1; this.result = new BlockState[256][][]; - this.biomeGrid = biomes ? new BiomeType[width * length] : null; + this.biomeResult = biomes ? new BiomeType[256][][] : null; this.bot = bot; this.top = top; } @@ -60,16 +59,19 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { return result; } - @Override public void fillBiome(BiomeType biomeType) { - if (biomeGrid == null) { - return; + @Override public boolean setBiome(int x, int z, BiomeType biomeType) { + if (this.biomeResult != null) { + for (int y = 0; y < 256; y++) { + this.storeCacheBiome(x, y, z, biomeType); + } + return true; } - Arrays.fill(biomeGrid, biomeType); + return false; } - @Override public boolean setBiome(int x, int z, BiomeType biomeType) { - if (this.biomeGrid != null) { - biomeGrid[(z * width) + x] = biomeType; + @Override public boolean setBiome(int x, int y, int z, BiomeType biomeType) { + if (this.biomeResult != null) { + this.storeCacheBiome(x, y, z, biomeType); return true; } return false; @@ -97,6 +99,18 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { resultYZ[x] = id; } + private void storeCacheBiome(final int x, final int y, final int z, final BiomeType id) { + BiomeType[][] resultY = biomeResult[y]; + if (resultY == null) { + biomeResult[y] = resultY = new BiomeType[length][]; + } + BiomeType[] resultYZ = resultY[z]; + if (resultYZ == null) { + resultY[z] = resultYZ = new BiomeType[width]; + } + resultYZ[x] = id; + } + @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { this.storeCache(x, y, z, id.toImmutableState()); return true; diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index 9e4826f32..790ad2a51 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -81,6 +81,10 @@ public class DelegateQueueCoordinator extends QueueCoordinator { return parent.setBiome(x, z, biome); } + @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { + return parent.setBiome(x, y, z, biome); + } + @Override public boolean isSettingBiomes() { return parent.isSettingBiomes(); } @@ -103,4 +107,8 @@ public class DelegateQueueCoordinator extends QueueCoordinator { } return false; } + + @Override public void setCompleteTask(Runnable whenDone) { + parent.setCompleteTask(whenDone); + } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java index a450ef045..db80e90b1 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java @@ -25,6 +25,7 @@ */ package com.plotsquared.core.queue; +import com.plotsquared.core.PlotSquared; import lombok.Getter; import lombok.Setter; @@ -42,6 +43,16 @@ public class GlobalBlockQueue { this.activeQueues = new ConcurrentLinkedDeque<>(); } + public QueueCoordinator getNewQueue(String world, boolean autoQueue) { + QueueCoordinator queue = provider.getNewQueue(world); + // Auto-inject into the queue + PlotSquared.platform().getInjector().injectMembers(queue); + if (autoQueue) { + queue.enqueue(); + } + return queue; + } + /** * TODO Documentation needed. * diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java index 3b067e8ca..e9766a53c 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java @@ -31,16 +31,11 @@ import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import javax.annotation.Nullable; public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordinator { - private static final Logger logger = LoggerFactory - .getLogger("P2/" + LocationOffsetDelegateQueueCoordinator.class.getSimpleName()); - private final boolean[][] canPlace; private final int blockX; private final int blockZ; @@ -76,8 +71,12 @@ public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordin return this.setBlock(x, y, z, pattern.apply(blockVector3)); } - @Override public boolean setBiome(int x, int y, BiomeType biome) { - return super.setBiome(x, y, biome); + @Override public boolean setBiome(int x, int z, BiomeType biome) { + return super.setBiome(x, z, biome); + } + + @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { + return super.setBiome(x, y, z, biome); } @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { diff --git a/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java index 78b945c7b..e69ea308b 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java @@ -42,8 +42,12 @@ public class OffsetQueueCoordinator extends DelegateQueueCoordinator { this.oz = oz; } - @Override public boolean setBiome(int x, int y, BiomeType biome) { - return super.setBiome(ox + x, oy + y, biome); + @Override public boolean setBiome(int x, int z, BiomeType biome) { + return super.setBiome(ox + x, oz + z, biome); + } + + @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { + return super.setBiome(ox + x, oy + y, oz + z, biome); } @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index 7a2c8e86c..ca8b3a7c9 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -52,6 +52,13 @@ public abstract class QueueCoordinator { PlotSquared.platform().getInjector().injectMembers(this); } + public ScopedQueueCoordinator getForChunk(int x, int z) { + int bx = x << 4; + int bz = z << 4; + return new ScopedQueueCoordinator(this, Location.at(getWorld().getName(), bx, 0, bz), + Location.at(getWorld().getName(), bx + 15, 255, bz + 255)); + } + public abstract int size(); public abstract void setModified(long modified); @@ -78,7 +85,9 @@ public abstract class QueueCoordinator { public abstract BlockState getBlock(int x, int y, int z); - public abstract boolean setBiome(int x, int z, BiomeType biome); + @Deprecated public abstract boolean setBiome(int x, int z, BiomeType biome); + + public abstract boolean setBiome(int x, int y, int z, BiomeType biome); public abstract boolean isSettingBiomes(); @@ -92,6 +101,8 @@ public abstract class QueueCoordinator { return blockQueue.enqueue(this); } + public abstract void setCompleteTask(Runnable whenDone); + public void setCuboid(Location pos1, Location pos2, BlockState block) { int yMin = Math.min(pos1.getY(), pos2.getY()); int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); diff --git a/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java index f19b7caaf..6a4589b4f 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java @@ -64,10 +64,17 @@ public class ScopedQueueCoordinator extends DelegateQueueCoordinator { return x >= 0 && x <= dx && z >= 0 && z <= dz && super.setBiome(x + minX, z + minZ, biome); } + @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { + return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super + .setBiome(x + minX, y + minY, z + minZ, biome); + } + public void fillBiome(BiomeType biome) { - for (int x = 0; x <= dx; x++) { - for (int z = 0; z < dz; z++) { - setBiome(x, z, biome); + for (int y = 0; y <= dy; y++) { + for (int x = 0; x <= dx; x++) { + for (int z = 0; z < dz; z++) { + setBiome(x, y, z, biome); + } } } } diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java index f9809840f..7012b8fa6 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java @@ -28,8 +28,8 @@ package com.plotsquared.core.util; import com.plotsquared.core.PlotSquared; import com.plotsquared.core.location.Location; import com.plotsquared.core.plot.Plot; -import com.plotsquared.core.queue.LocalBlockQueue; -import com.plotsquared.core.queue.ScopedLocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; +import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.math.BlockVector2; @@ -42,19 +42,21 @@ import java.util.concurrent.ConcurrentHashMap; public abstract class ChunkManager { - private static final Map> forceChunks = + private static final Map> forceChunks = new ConcurrentHashMap<>(); - private static final Map> addChunks = + private static final Map> addChunks = new ConcurrentHashMap<>(); - public static void setChunkInPlotArea(RunnableVal force, - RunnableVal add, String world, BlockVector2 loc) { - LocalBlockQueue queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false); - if (PlotSquared.get().getPlotAreaManager().isAugmented(world) && PlotSquared.get().isNonStandardGeneration(world, loc)) { + public static void setChunkInPlotArea(RunnableVal force, + RunnableVal add, String world, BlockVector2 loc) { + QueueCoordinator queue = + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false); + if (PlotSquared.get().getPlotAreaManager().isAugmented(world) && PlotSquared.get() + .isNonStandardGeneration(world, loc)) { int blockX = loc.getX() << 4; int blockZ = loc.getZ() << 4; - ScopedLocalBlockQueue scoped = - new ScopedLocalBlockQueue(queue, Location.at(world, blockX, 0, blockZ), + ScopedQueueCoordinator scoped = + new ScopedQueueCoordinator(queue, Location.at(world, blockX, 0, blockZ), Location.at(world, blockX + 15, 255, blockZ + 15)); if (force != null) { force.run(scoped); @@ -64,7 +66,7 @@ public abstract class ChunkManager { add.run(scoped); } } - queue.flush(); + queue.enqueue(); } else { if (force != null) { forceChunks.put(loc, force); @@ -76,8 +78,8 @@ public abstract class ChunkManager { } } - public static boolean preProcessChunk(BlockVector2 loc, ScopedLocalBlockQueue queue) { - final RunnableVal forceChunk = forceChunks.get(loc); + public static boolean preProcessChunk(BlockVector2 loc, ScopedQueueCoordinator queue) { + final RunnableVal forceChunk = forceChunks.get(loc); if (forceChunk != null) { forceChunk.run(queue); forceChunks.remove(loc); @@ -86,8 +88,8 @@ public abstract class ChunkManager { return false; } - public static boolean postProcessChunk(BlockVector2 loc, ScopedLocalBlockQueue queue) { - final RunnableVal addChunk = forceChunks.get(loc); + public static boolean postProcessChunk(BlockVector2 loc, ScopedQueueCoordinator queue) { + final RunnableVal addChunk = forceChunks.get(loc); if (addChunk != null) { addChunk.run(queue); addChunks.remove(loc); diff --git a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java index 743395523..dd8a99c8d 100644 --- a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java @@ -30,7 +30,7 @@ import com.plotsquared.core.location.Location; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotManager; -import com.plotsquared.core.queue.LocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.function.pattern.Pattern; @@ -39,8 +39,8 @@ import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.biome.BiomeType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; import java.io.File; import java.util.Collection; import java.util.HashSet; @@ -48,9 +48,15 @@ import java.util.Set; public abstract class RegionManager { - private static final Logger logger = LoggerFactory.getLogger("P2/" + RegionManager.class.getSimpleName()); + private static final Logger logger = + LoggerFactory.getLogger("P2/" + RegionManager.class.getSimpleName()); public static RegionManager manager = null; + private final ChunkManager chunkManager; + + public RegionManager(@Nonnull final ChunkManager chunkManager) { + this.chunkManager = chunkManager; + } public static BlockVector2 getRegion(Location location) { int x = location.getX() >> 9; @@ -58,12 +64,6 @@ public abstract class RegionManager { return BlockVector2.at(x, z); } - private final ChunkManager chunkManager; - - public RegionManager(@Nonnull final ChunkManager chunkManager) { - this.chunkManager = chunkManager; - } - public void largeRegionTask(final String world, final CuboidRegion region, final RunnableVal task, final Runnable whenDone) { TaskManager.runTaskAsync(() -> { @@ -96,8 +96,7 @@ public abstract class RegionManager { } TaskManager.objectTask(chunks, new RunnableVal() { @Override public void run(BlockVector2 value) { - chunkManager.loadChunk(world, value, false) - .thenRun(() -> task.run(value)); + chunkManager.loadChunk(world, value, false).thenRun(() -> task.run(value)); } }, whenDone); }); @@ -164,7 +163,7 @@ public abstract class RegionManager { public boolean setCuboids(final PlotArea area, final Set regions, final Pattern blocks, int minY, int maxY) { - LocalBlockQueue queue = area.getQueue(false); + QueueCoordinator queue = area.getQueue(false); for (CuboidRegion region : regions) { Location pos1 = Location.at(area.getWorldName(), region.getMinimumPoint().getX(), minY, region.getMinimumPoint().getZ()); diff --git a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java index 7f933df24..07cc0c618 100644 --- a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java +++ b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java @@ -32,7 +32,7 @@ import com.plotsquared.core.location.Location; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.schematic.Schematic; -import com.plotsquared.core.queue.LocalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.TaskManager; import com.sk89q.jnbt.ByteArrayTag; @@ -58,12 +58,12 @@ import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; -import javax.annotation.Nonnull; import org.json.JSONArray; import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; @@ -96,12 +96,11 @@ import java.util.zip.GZIPOutputStream; public abstract class SchematicHandler { - private static final Logger logger = LoggerFactory.getLogger("P2/" + SchematicHandler.class.getSimpleName()); + private static final Logger logger = + LoggerFactory.getLogger("P2/" + SchematicHandler.class.getSimpleName()); public static SchematicHandler manager; - - private boolean exportAll = false; - private final WorldUtil worldUtil; + private boolean exportAll = false; public SchematicHandler(@Nonnull final WorldUtil worldUtil) { this.worldUtil = worldUtil; @@ -158,7 +157,8 @@ public abstract class SchematicHandler { @Override public void run(final CompoundTag value) { if (value != null) { TaskManager.runTaskAsync(() -> { - boolean result = save(value, directory + File.separator + name + ".schem"); + boolean result = + save(value, directory + File.separator + name + ".schem"); if (!result) { logger.error("[P2] Failed to save {}", plot.getId()); } @@ -193,7 +193,7 @@ public abstract class SchematicHandler { return; } try { - final LocalBlockQueue queue = plot.getArea().getQueue(false); + final QueueCoordinator queue = plot.getArea().getQueue(false); BlockVector3 dimension = schematic.getClipboard().getDimensions(); final int WIDTH = dimension.getX(); final int LENGTH = dimension.getZ(); @@ -219,7 +219,7 @@ public abstract class SchematicHandler { if (pw instanceof ClassicPlotWorld) { y_offset_actual = yOffset + ((ClassicPlotWorld) pw).PLOT_HEIGHT; } else { - y_offset_actual = yOffset + 1 + this.worldUtil + y_offset_actual = yOffset + 1 + this.worldUtil .getHighestBlockSynchronous(plot.getWorldName(), region.getMinimumPoint().getX() + 1, region.getMinimumPoint().getZ() + 1); @@ -229,8 +229,9 @@ public abstract class SchematicHandler { y_offset_actual = yOffset; } - final Location pos1 = Location.at(plot.getWorldName(), region.getMinimumPoint().getX() + xOffset, y_offset_actual, - region.getMinimumPoint().getZ() + zOffset); + final Location pos1 = Location + .at(plot.getWorldName(), region.getMinimumPoint().getX() + xOffset, + y_offset_actual, region.getMinimumPoint().getZ() + zOffset); final Location pos2 = pos1.add(WIDTH - 1, HEIGHT - 1, LENGTH - 1); final int p1x = pos1.getX(); @@ -300,7 +301,7 @@ public abstract class SchematicHandler { }); } - public abstract boolean restoreTile(LocalBlockQueue queue, CompoundTag tag, int x, int y, + public abstract boolean restoreTile(QueueCoordinator queue, CompoundTag tag, int x, int y, int z); /** From 66b94ab9f14cb5c10cea8034e8c1875700a28f5f Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 17 Jul 2020 17:21:32 +0100 Subject: [PATCH 24/49] Start switching to WorldEdit Worlds --- .../bukkit/util/BukkitChunkManager.java | 7 ++---- .../bukkit/util/BukkitRegionManager.java | 22 +++++++++---------- .../com/plotsquared/core/command/Trim.java | 2 +- .../core/generator/AugmentedUtils.java | 2 +- .../core/generator/HybridUtils.java | 6 ++--- .../java/com/plotsquared/core/plot/Plot.java | 2 +- .../com/plotsquared/core/plot/PlotArea.java | 3 ++- .../core/queue/GlobalBlockQueue.java | 8 ++----- .../plotsquared/core/queue/QueueProvider.java | 6 +++-- .../plotsquared/core/util/ChunkManager.java | 2 +- .../plotsquared/core/util/RegionManager.java | 2 +- 11 files changed, 29 insertions(+), 33 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java index 24551aadb..103bf21fc 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java @@ -74,16 +74,13 @@ public class BukkitChunkManager extends ChunkManager { int sx = pos1.getX() << 4; int sz = pos1.getZ() << 4; - String worldName1 = world1.getName(); - String worldName2 = world2.getName(); - BukkitWorld bukkitWorld1 = new BukkitWorld(world1); BukkitWorld bukkitWorld2 = new BukkitWorld(world2); QueueCoordinator queue1 = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(worldName1, false); + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(bukkitWorld1, false); QueueCoordinator queue2 = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(worldName2, false); + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(bukkitWorld2, false); for (int x = Math.max(r1.getMinimumPoint().getX(), sx); x <= Math.min(r1.getMaximumPoint().getX(), sx + 15); x++) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java index 6b6491a9d..c078fe174 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java @@ -41,6 +41,7 @@ import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.RegionUtil; +import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.entity.EntityCategories; import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.TaskManager; @@ -84,9 +85,12 @@ public class BukkitRegionManager extends RegionManager { private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitRegionManager.class.getSimpleName()); + private final WorldUtil worldUtil; - @Inject public BukkitRegionManager(@Nonnull final ChunkManager chunkManager) { - super(chunkManager); + @Inject public BukkitRegionManager(@Nonnull final ChunkManager chunkManager, + @Nonnull final WorldUtil worldUtil) { + super(chunkManager, worldUtil); + this.worldUtil = worldUtil; } public static boolean isIn(CuboidRegion region, int x, int z) { @@ -210,15 +214,11 @@ public class BukkitRegionManager extends RegionManager { final CuboidRegion region = RegionUtil.createRegion(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); - final World oldWorld = Bukkit.getWorld(pos1.getWorldName()); - final BukkitWorld oldBukkitWorld = new BukkitWorld(oldWorld); - final World newWorld = Bukkit.getWorld(newPos.getWorldName()); - assert newWorld != null; - assert oldWorld != null; - final String newWorldName = newWorld.getName(); + final BukkitWorld oldWorld = new BukkitWorld((World) pos1.getWorld()); + final BukkitWorld newWorld = new BukkitWorld((World) newPos.getWorld()); final ContentMap map = new ContentMap(); final QueueCoordinator queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(newWorldName, false); + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(newWorld, false); ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { @Override public void run(int[] value) { int bx = value[2]; @@ -232,7 +232,7 @@ public class BukkitRegionManager extends RegionManager { .thenAccept(chunk1 -> map.saveEntitiesIn(chunk1, region)).thenRun(() -> { for (int x = bx & 15; x <= (tx & 15); x++) { for (int z = bz & 15; z <= (tz & 15); z++) { - map.saveBlocks(oldBukkitWorld, 256, cxx + x, czz + z, relX, relZ); + map.saveBlocks(oldWorld, 256, cxx + x, czz + z, relX, relZ); } } }); @@ -250,7 +250,7 @@ public class BukkitRegionManager extends RegionManager { } queue.setCompleteTask(() -> { //map.restoreBlocks(newWorld, 0, 0); - map.restoreEntities(newWorld, relX, relZ); + map.restoreEntities((World) newPos.getWorld(), relX, relZ); TaskManager.runTask(whenDone); }); queue.enqueue(); diff --git a/Core/src/main/java/com/plotsquared/core/command/Trim.java b/Core/src/main/java/com/plotsquared/core/command/Trim.java index 4e2ec2a08..b40d6f03d 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Trim.java +++ b/Core/src/main/java/com/plotsquared/core/command/Trim.java @@ -190,7 +190,7 @@ public class Trim extends SubCommand { } } } - final QueueCoordinator queue = blockQueue.getNewQueue(world, false); + final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world), false); TaskManager.getPlatformImplementation().objectTask(chunks, new RunnableVal() { @Override public void run(BlockVector2 value) { queue.regenChunk(value.getX(), value.getZ()); diff --git a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java index b40e718af..16ded7334 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java @@ -87,7 +87,7 @@ public class AugmentedUtils { IndependentPlotGenerator generator = area.getGenerator(); // Mask if (queue == null) { - queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false); + queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world), false); queue.setChunkObject(chunkObject); } QueueCoordinator primaryMask; diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index 016a547ea..ef20a88b6 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -128,7 +128,7 @@ public class HybridUtils { * */ TaskManager.runTaskAsync(() -> { - final QueueCoordinator queue = blockQueue.getNewQueue(world, false); + final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world), false); final BlockVector3 bot = region.getMinimumPoint(); final BlockVector3 top = region.getMaximumPoint(); @@ -520,7 +520,7 @@ public class HybridUtils { public boolean setupRoadSchematic(Plot plot) { final String world = plot.getWorldName(); - final QueueCoordinator queue = blockQueue.getNewQueue(world, false); + final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world), false); Location bot = plot.getBottomAbs().subtract(1, 0, 1); Location top = plot.getTopAbs(); final HybridPlotWorld plotworld = (HybridPlotWorld) plot.getArea(); @@ -607,7 +607,7 @@ public class HybridUtils { z -= plotWorld.ROAD_OFFSET_Z; final int finalX = x; final int finalZ = z; - QueueCoordinator queue = this.blockQueue.getNewQueue(plotWorld.getWorldName(), false); + QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(plotWorld.getWorldName()), false); if (id1 == null || id2 == null || id1 != id2) { this.chunkManager.loadChunk(area.getWorldName(), chunk, false).thenRun(() -> { if (id1 != null) { diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index f661f6a29..827aa2c70 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -1687,7 +1687,7 @@ public class Plot { * This should not need to be called */ public void refreshChunks() { - QueueCoordinator queue = this.blockQueue.getNewQueue(getWorldName(), false); + QueueCoordinator queue = this.blockQueue.getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(getWorldName()), false); HashSet chunks = new HashSet<>(); for (CuboidRegion region : Plot.this.getRegions()) { for (int x = region.getMinimumPoint().getX() >> 4; diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java index 4aecc38d9..ab49691ca 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java @@ -27,6 +27,7 @@ package com.plotsquared.core.plot; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.plotsquared.core.PlotSquared; import com.plotsquared.core.collection.QuadMap; import com.plotsquared.core.configuration.CaptionUtility; import com.plotsquared.core.configuration.Captions; @@ -172,7 +173,7 @@ public abstract class PlotArea { @Nonnull protected abstract PlotManager createManager(); public QueueCoordinator getQueue(final boolean autoQueue) { - return this.globalBlockQueue.getNewQueue(worldName, autoQueue); + return this.globalBlockQueue.getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(worldName), autoQueue); } /** diff --git a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java index eb40df5b0..56437f0cd 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java @@ -26,13 +26,9 @@ package com.plotsquared.core.queue; import com.plotsquared.core.PlotSquared; -<<<<<<< HEAD +import com.sk89q.worldedit.world.World; import lombok.Getter; import lombok.Setter; -======= -import com.plotsquared.core.util.task.RunnableVal2; -import com.plotsquared.core.util.task.TaskManager; -import com.plotsquared.core.util.task.TaskTime; import java.util.ArrayList; import java.util.List; @@ -48,7 +44,7 @@ public class GlobalBlockQueue { this.activeQueues = new ConcurrentLinkedDeque<>(); } - public QueueCoordinator getNewQueue(String world, boolean autoQueue) { + public QueueCoordinator getNewQueue(World world, boolean autoQueue) { QueueCoordinator queue = provider.getNewQueue(world); // Auto-inject into the queue PlotSquared.platform().getInjector().injectMembers(queue); diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java index 207b29ee0..27c6a6866 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java @@ -25,6 +25,8 @@ */ package com.plotsquared.core.queue; +import com.sk89q.worldedit.world.World; + public abstract class QueueProvider { public static QueueProvider of(final Class primary, final Class fallback) { @@ -32,7 +34,7 @@ public abstract class QueueProvider { private boolean failed = false; - @Override public QueueCoordinator getNewQueue(String world) { + @Override public QueueCoordinator getNewQueue(World world) { if (!failed) { try { return (QueueCoordinator) primary.getConstructors()[0].newInstance(world); @@ -51,5 +53,5 @@ public abstract class QueueProvider { }; } - public abstract QueueCoordinator getNewQueue(String world); + public abstract QueueCoordinator getNewQueue(World world); } diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java index dce0f43ed..0a7bc6ccd 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java @@ -51,7 +51,7 @@ public abstract class ChunkManager { public static void setChunkInPlotArea(RunnableVal force, RunnableVal add, String world, BlockVector2 loc) { QueueCoordinator queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false); + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world), false); if (PlotSquared.get().getPlotAreaManager().isAugmented(world) && PlotSquared.get() .isNonStandardGeneration(world, loc)) { int blockX = loc.getX() << 4; diff --git a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java index bcf5fb58d..9b9bd9a7d 100644 --- a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java @@ -55,7 +55,7 @@ public abstract class RegionManager { public static RegionManager manager = null; private final ChunkManager chunkManager; - public RegionManager(@Nonnull final ChunkManager chunkManager) { + public RegionManager(@Nonnull final ChunkManager chunkManager, @Nonnull WorldUtil worldUtil) { this.chunkManager = chunkManager; } From 57af50ed4930c9ea08607f3775c14df27f072010 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Sat, 18 Jul 2020 12:07:56 +0100 Subject: [PATCH 25/49] Continue implementation of new queue system - Move ChunkCoordinatorBuild to Core - Add core ChunkCoordinator - Add Factories for ChunkCoordinator and its Builder - Reimplement refreshChunk but in WorldUtil - Allow custom Consumers to be used by the Queue when sent to the ChunkCoordinator - Start switching ChunkTasks to use the new ChunkCoordinator system - Replace GlobalBlockQueue's "empty task" system with normal sync TaskManager - Remove lombok from the queue system - Add back forceSync and chunkObject from LocalBlockQueue --- .../bukkit/inject/BukkitModule.java | 13 +- .../bukkit/queue/BukkitChunkCoordinator.java | 163 ++------- .../bukkit/queue/BukkitQueueCoordinator.java | 56 ++- .../plotsquared/bukkit/queue/GenChunk.java | 12 +- .../bukkit/util/BukkitRegionManager.java | 330 +++++++++--------- .../plotsquared/bukkit/util/BukkitUtil.java | 120 ++++--- .../com/plotsquared/core/command/Clear.java | 4 +- .../plotsquared/core/command/Template.java | 5 +- .../core/generator/ClassicPlotManager.java | 5 +- .../core/generator/HybridUtils.java | 2 +- ...va => ChunkCoordinatorBuilderFactory.java} | 10 +- .../factory/ChunkCoordinatorFactory.java | 48 +++ .../java/com/plotsquared/core/plot/Plot.java | 20 +- .../AreaBoundDelegateQueueCoordinator.java | 7 +- .../core/queue/BasicQueueCoordinator.java | 33 +- .../core/queue/ChunkCoordinator.java | 22 ++ .../core/queue/ChunkCoordinatorBuilder.java | 113 ++++++ .../core/queue/DelegateQueueCoordinator.java | 7 + .../core/queue/GlobalBlockQueue.java | 12 +- .../plotsquared/core/queue/LocalChunk.java | 37 +- .../core/queue/QueueCoordinator.java | 27 +- .../plotsquared/core/util/RegionManager.java | 18 +- .../com/plotsquared/core/util/WorldUtil.java | 2 + 23 files changed, 625 insertions(+), 441 deletions(-) rename Core/src/main/java/com/plotsquared/core/inject/factory/{QueueCoordinatorFactory.java => ChunkCoordinatorBuilderFactory.java} (79%) create mode 100644 Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java create mode 100644 Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java create mode 100644 Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java index 8f644dc25..3361add35 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java @@ -26,12 +26,11 @@ package com.plotsquared.bukkit.inject; import com.google.inject.AbstractModule; -import com.google.inject.Provides; -import com.google.inject.Singleton; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.util.Providers; import com.plotsquared.bukkit.BukkitPlatform; import com.plotsquared.bukkit.player.BukkitPlayerManager; +import com.plotsquared.bukkit.queue.BukkitChunkCoordinator; import com.plotsquared.bukkit.queue.BukkitQueueCoordinator; import com.plotsquared.bukkit.schematic.BukkitSchematicHandler; import com.plotsquared.bukkit.util.BukkitChunkManager; @@ -41,18 +40,20 @@ import com.plotsquared.bukkit.util.BukkitPermHandler; import com.plotsquared.bukkit.util.BukkitRegionManager; import com.plotsquared.bukkit.util.BukkitSetupUtils; import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.bukkit.util.task.PaperTimeConverter; -import com.plotsquared.bukkit.util.task.SpigotTimeConverter; import com.plotsquared.core.PlotPlatform; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.generator.HybridGen; import com.plotsquared.core.generator.IndependentPlotGenerator; import com.plotsquared.core.inject.annotations.ConsoleActor; import com.plotsquared.core.inject.annotations.DefaultGenerator; +import com.plotsquared.core.inject.factory.ChunkCoordinatorBuilderFactory; +import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory; import com.plotsquared.core.inject.factory.HybridPlotWorldFactory; import com.plotsquared.core.plot.world.DefaultPlotAreaManager; import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.plot.world.SinglePlotAreaManager; +import com.plotsquared.core.queue.ChunkCoordinator; +import com.plotsquared.core.queue.ChunkCoordinatorBuilder; import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.queue.QueueProvider; import com.plotsquared.core.util.ChunkManager; @@ -105,6 +106,10 @@ public class BukkitModule extends AbstractModule { bind(PlotAreaManager.class).to(DefaultPlotAreaManager.class); } install(new FactoryModuleBuilder().build(HybridPlotWorldFactory.class)); + install(new FactoryModuleBuilder() + .implement(ChunkCoordinator.class, BukkitChunkCoordinator.class) + .build(ChunkCoordinatorFactory.class)); + install(new FactoryModuleBuilder().build(ChunkCoordinatorBuilderFactory.class)); } private void setupVault() { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java index 5cc5de1b1..04f6083b4 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java @@ -25,17 +25,19 @@ */ package com.plotsquared.bukkit.queue; -import com.google.common.base.Preconditions; import com.plotsquared.bukkit.BukkitPlatform; +import com.plotsquared.core.queue.ChunkCoordinator; +import com.plotsquared.core.util.task.TaskManager; +import com.plotsquared.core.util.task.TaskTime; import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.world.World; import io.papermc.lib.PaperLib; +import org.bukkit.Bukkit; import org.bukkit.Chunk; -import org.bukkit.World; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitRunnable; -import org.jetbrains.annotations.NotNull; +import javax.annotation.Nonnull; import java.util.Collection; import java.util.LinkedList; import java.util.List; @@ -44,32 +46,7 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; -/** - * Utility that allows for the loading and coordination of chunk actions - *

- * The coordinator takes in collection of chunk coordinates, loads them - * and allows the caller to specify a sink for the loaded chunks. The - * coordinator will prevent the chunks from being unloaded until the sink - * has fully consumed the chunk - *

- * Usage: - *

{@code
- * final ChunkCoordinator chunkCoordinator = ChunkCoordinator.builder()
- *     .inWorld(Objects.requireNonNull(Bukkit.getWorld("world"))).withChunk(BlockVector2.at(0, 0))
- *     .withConsumer(chunk -> System.out.printf("Got chunk %d;%d", chunk.getX(), chunk.getZ()))
- *     .withFinalAction(() -> System.out.println("All chunks have been loaded"))
- *     .withThrowableConsumer(throwable -> System.err.println("Something went wrong... =("))
- *     .withMaxIterationTime(25L)
- *     .build();
- * chunkCoordinator.subscribeToProgress((coordinator, progress) ->
- *     System.out.printf("Progress: %.1f", progress * 100.0f));
- * chunkCoordinator.start();
- * }
- * - * @author Alexander Söderberg - * @see #builder() To create a new coordinator instance - */ -public final class BukkitChunkCoordinator extends BukkitRunnable { +public final class BukkitChunkCoordinator extends ChunkCoordinator { private final List progressSubscribers = new LinkedList<>(); @@ -77,52 +54,44 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { private final Queue availableChunks; private final long maxIterationTime; private final Plugin plugin; - private final Consumer chunkConsumer; - private final World world; + private final Consumer chunkConsumer; + private final org.bukkit.World bukkitWorld; private final Runnable whenDone; private final Consumer throwableConsumer; private final int totalSize; - private AtomicInteger expectedSize; + private final AtomicInteger expectedSize; private int batchSize; private BukkitChunkCoordinator(final long maxIterationTime, final int initialBatchSize, - @NotNull final Consumer chunkConsumer, @NotNull final World world, - @NotNull final Collection requestedChunks, @NotNull final Runnable whenDone, - @NotNull final Consumer throwableConsumer) { + @Nonnull final Consumer chunkConsumer, @Nonnull final World world, + @Nonnull final Collection requestedChunks, @Nonnull final Runnable whenDone, + @Nonnull final Consumer throwableConsumer) { this.requestedChunks = new LinkedBlockingQueue<>(requestedChunks); this.availableChunks = new LinkedBlockingQueue<>(); this.totalSize = requestedChunks.size(); this.expectedSize = new AtomicInteger(this.totalSize); - this.world = world; this.batchSize = initialBatchSize; this.chunkConsumer = chunkConsumer; this.maxIterationTime = maxIterationTime; this.whenDone = whenDone; this.throwableConsumer = throwableConsumer; this.plugin = JavaPlugin.getPlugin(BukkitPlatform.class); - } - - /** - * Create a new {@link BukkitChunkCoordinator} instance - * - * @return Coordinator builder instance - */ - @NotNull public static ChunkCoordinatorBuilder builder() { - return new ChunkCoordinatorBuilder(); + this.bukkitWorld = Bukkit.getWorld(world.getName()); } /** * Start the coordinator instance */ - public void start() { + @Override public void start() { // Request initial batch this.requestBatch(); // Wait until next tick to give the chunks a chance to be loaded - this.runTaskTimer(this.plugin, 1L, 1L); + TaskManager.runTaskLater(() -> TaskManager.runTaskRepeat(this, TaskTime.ticks(1)), + TaskTime.ticks(1)); } - @Override public void run() { + @Override public void runTask() { Chunk chunk = this.availableChunks.poll(); if (chunk == null) { return; @@ -132,7 +101,7 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { do { final long start = System.currentTimeMillis(); try { - this.chunkConsumer.accept(chunk); + this.chunkConsumer.accept(BlockVector2.at(chunk.getX(), chunk.getZ())); } catch (final Throwable throwable) { this.throwableConsumer.accept(throwable); } @@ -173,7 +142,7 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { BlockVector2 chunk; for (int i = 0; i < this.batchSize && (chunk = this.requestedChunks.poll()) != null; i++) { // This required PaperLib to be bumped to version 1.0.4 to mark the request as urgent - PaperLib.getChunkAtAsync(this.world, chunk.getX(), chunk.getZ(), true, true) + PaperLib.getChunkAtAsync(this.bukkitWorld, chunk.getX(), chunk.getZ(), true, true) .whenComplete((chunkObject, throwable) -> { if (throwable != null) { throwable.printStackTrace(); @@ -186,7 +155,7 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { } } - private void processChunk(@NotNull final Chunk chunk) { + private void processChunk(@Nonnull final Chunk chunk) { if (!chunk.isLoaded()) { throw new IllegalArgumentException( String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ())); @@ -195,7 +164,7 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { this.availableChunks.add(chunk); } - private void freeChunk(@NotNull final Chunk chunk) { + private void freeChunk(@Nonnull final Chunk chunk) { if (!chunk.isLoaded()) { throw new IllegalArgumentException( String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ())); @@ -208,7 +177,7 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { * * @return Snapshot view of remaining chunk count */ - public int getRemainingChunks() { + @Override public int getRemainingChunks() { return this.expectedSize.get(); } @@ -217,7 +186,7 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { * * @return Requested chunk count */ - public int getTotalChunks() { + @Override public int getTotalChunks() { return this.totalSize; } @@ -227,11 +196,10 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { * @param subscriber Subscriber */ public void subscribeToProgress( - @NotNull final BukkitChunkCoordinator.ProgressSubscriber subscriber) { + @Nonnull final BukkitChunkCoordinator.ProgressSubscriber subscriber) { this.progressSubscribers.add(subscriber); } - @FunctionalInterface public interface ProgressSubscriber { @@ -241,88 +209,9 @@ public final class BukkitChunkCoordinator extends BukkitRunnable { * @param coordinator Coordinator instance that triggered the notification * @param progress Progress in the range [0, 1] */ - void notifyProgress(@NotNull final BukkitChunkCoordinator coordinator, + void notifyProgress(@Nonnull final BukkitChunkCoordinator coordinator, final float progress); } - - public static final class ChunkCoordinatorBuilder { - - private final List requestedChunks = new LinkedList<>(); - private Consumer throwableConsumer = Throwable::printStackTrace; - private World world; - private Consumer chunkConsumer; - private Runnable whenDone = () -> { - }; - private long maxIterationTime = 60; // A little over 1 tick; - private int initialBatchSize = 4; - - private ChunkCoordinatorBuilder() { - } - - @NotNull public ChunkCoordinatorBuilder inWorld(@NotNull final World world) { - this.world = Preconditions.checkNotNull(world, "World may not be null"); - return this; - } - - @NotNull - public ChunkCoordinatorBuilder withChunk(@NotNull final BlockVector2 chunkLocation) { - this.requestedChunks - .add(Preconditions.checkNotNull(chunkLocation, "Chunk location may not be null")); - return this; - } - - @NotNull public ChunkCoordinatorBuilder withChunks( - @NotNull final Collection chunkLocations) { - chunkLocations.forEach(this::withChunk); - return this; - } - - @NotNull - public ChunkCoordinatorBuilder withConsumer(@NotNull final Consumer chunkConsumer) { - this.chunkConsumer = - Preconditions.checkNotNull(chunkConsumer, "Chunk consumer may not be null"); - return this; - } - - @NotNull public ChunkCoordinatorBuilder withFinalAction(@NotNull final Runnable whenDone) { - this.whenDone = Preconditions.checkNotNull(whenDone, "Final action may not be null"); - return this; - } - - @NotNull public ChunkCoordinatorBuilder withMaxIterationTime(final long maxIterationTime) { - Preconditions - .checkArgument(maxIterationTime > 0, "Max iteration time must be positive"); - this.maxIterationTime = maxIterationTime; - return this; - } - - @NotNull public ChunkCoordinatorBuilder withInitialBatchSize(final int initialBatchSize) { - Preconditions - .checkArgument(initialBatchSize > 0, "Initial batch size must be positive"); - this.initialBatchSize = initialBatchSize; - return this; - } - - @NotNull public ChunkCoordinatorBuilder withThrowableConsumer( - @NotNull final Consumer throwableConsumer) { - this.throwableConsumer = - Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null"); - return this; - } - - @NotNull public BukkitChunkCoordinator build() { - Preconditions.checkNotNull(this.world, "No world was supplied"); - Preconditions.checkNotNull(this.chunkConsumer, "No chunk consumer was supplied"); - Preconditions.checkNotNull(this.whenDone, "No final action was supplied"); - Preconditions - .checkNotNull(this.throwableConsumer, "No throwable consumer was supplied"); - return new BukkitChunkCoordinator(this.maxIterationTime, this.initialBatchSize, - this.chunkConsumer, this.world, this.requestedChunks, this.whenDone, - this.throwableConsumer); - } - - } - } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index 64fa07c0a..075359e26 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -25,8 +25,11 @@ */ package com.plotsquared.bukkit.queue; +import com.google.inject.Inject; import com.plotsquared.bukkit.schematic.StateWrapper; import com.plotsquared.bukkit.util.BukkitBlockUtil; +import com.plotsquared.core.inject.factory.ChunkCoordinatorBuilderFactory; +import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory; import com.plotsquared.core.queue.BasicQueueCoordinator; import com.plotsquared.core.queue.LocalChunk; import com.plotsquared.core.util.BlockUtil; @@ -42,20 +45,25 @@ import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Container; import org.bukkit.block.data.BlockData; import javax.annotation.Nonnull; +import java.util.function.Consumer; public class BukkitQueueCoordinator extends BasicQueueCoordinator { private final World world; private final SideEffectSet sideEffectSet; + @Inject private ChunkCoordinatorBuilderFactory chunkCoordinatorBuilderFactory; + @Inject private ChunkCoordinatorFactory chunkCoordinatorFactory; private Runnable whenDone; - public BukkitQueueCoordinator(World world) { + @Inject public BukkitQueueCoordinator(World world) { super(world); this.world = world; sideEffectSet = SideEffectSet.none().with(SideEffect.LIGHTING, SideEffect.State.OFF) @@ -73,19 +81,18 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { } @Override public boolean enqueue() { - BukkitChunkCoordinator.builder().inWorld(BukkitAdapter.adapt(world)) - .withChunks(getBlockChunks().keySet()).withInitialBatchSize(3).withMaxIterationTime(40) - .withThrowableConsumer(Throwable::printStackTrace).withFinalAction(whenDone) - .withConsumer(chunk -> { - LocalChunk localChunk = - getBlockChunks().get(BlockVector2.at(chunk.getX(), chunk.getZ())); + Consumer consumer = getChunkConsumer(); + if (consumer == null) { + consumer = blockVector2 -> { + LocalChunk localChunk = getBlockChunks().get(blockVector2); if (localChunk == null) { throw new NullPointerException( "LocalChunk cannot be null when accessed from ChunkCoordinator"); } - World worldObj = getWorld(); - int sx = chunk.getX() << 4; - int sz = chunk.getX() << 4; + org.bukkit.World bukkitWorld = null; + Chunk chunk = null; + int sx = blockVector2.getX() << 4; + int sz = blockVector2.getZ() << 4; for (int layer = 0; layer < localChunk.getBaseblocks().length; layer++) { BaseBlock[] blocksLayer = localChunk.getBaseblocks()[layer]; if (blocksLayer == null) { @@ -100,11 +107,19 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { int y = MainUtil.y_loc[layer][j]; int z = sz + MainUtil.z_loc[layer][j]; try { - worldObj.setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); + world.setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); } catch (WorldEditException ignored) { // Fallback to not so nice method BlockData blockData = BukkitAdapter.adapt(block); + if (bukkitWorld == null) { + bukkitWorld = Bukkit.getWorld(world.getName()); + } + if (chunk == null) { + chunk = bukkitWorld + .getChunkAt(blockVector2.getX(), blockVector2.getZ()); + } + Block existing = chunk.getBlock(x, y, z); final BlockState existingBaseBlock = BukkitAdapter.adapt(existing.getBlockData()); @@ -123,7 +138,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { CompoundTag tag = block.getNbtData(); StateWrapper sw = new StateWrapper(tag); - sw.restoreTag(worldObj.getName(), existing.getX(), existing.getY(), + sw.restoreTag(world.getName(), existing.getX(), existing.getY(), existing.getZ()); } } @@ -142,22 +157,27 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { int x = sx + MainUtil.x_loc[layer][j]; int y = MainUtil.y_loc[layer][j]; int z = sz + MainUtil.z_loc[layer][j]; - worldObj.setBiome(BlockVector3.at(x, y, z), biome); + world.setBiome(BlockVector3.at(x, y, z), biome); } } if (localChunk.getTiles().size() > 0) { localChunk.getTiles().forEach(((blockVector3, tag) -> { try { - BaseBlock block = worldObj.getBlock(blockVector3).toBaseBlock(tag); - worldObj.setBlock(blockVector3, block, sideEffectSet); + BaseBlock block = world.getBlock(blockVector3).toBaseBlock(tag); + world.setBlock(blockVector3, block, sideEffectSet); } catch (WorldEditException ignored) { StateWrapper sw = new StateWrapper(tag); - sw.restoreTag(worldObj.getName(), blockVector3.getX(), - blockVector3.getY(), blockVector3.getZ()); + sw.restoreTag(world.getName(), blockVector3.getX(), blockVector3.getY(), + blockVector3.getZ()); } })); } - }); + }; + } + chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(world) + .withChunks(getBlockChunks().keySet()).withInitialBatchSize(3).withMaxIterationTime(40) + .withThrowableConsumer(Throwable::printStackTrace).withFinalAction(whenDone) + .withConsumer(consumer); return super.enqueue(); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java index 6a67c83e1..e79545493 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java @@ -39,8 +39,6 @@ import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockTypes; -import lombok.Getter; -import lombok.Setter; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.World; @@ -60,13 +58,21 @@ public class GenChunk extends ScopedQueueCoordinator { public String world; public int chunkX; public int chunkZ; - @Getter @Setter private ChunkData chunkData = null; + private ChunkData chunkData = null; public GenChunk() { super(null, Location.at("", 0, 0, 0), Location.at("", 15, 255, 15)); this.biomes = Biome.values(); } + public ChunkData getChunkData() { + return this.chunkData; + } + + public void setChunkData(ChunkData chunkData) { + this.chunkData = chunkData; + } + public Chunk getChunk() { if (chunk == null) { World worldObj = BukkitUtil.getWorld(world); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java index c078fe174..2b3f72764 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java @@ -30,6 +30,8 @@ import com.google.inject.Singleton; import com.plotsquared.bukkit.BukkitPlatform; import com.plotsquared.core.PlotSquared; import com.plotsquared.core.generator.AugmentedUtils; +import com.plotsquared.core.inject.factory.ChunkCoordinatorBuilderFactory; +import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory; import com.plotsquared.core.location.Location; import com.plotsquared.core.location.PlotLoc; import com.plotsquared.core.plot.Plot; @@ -86,16 +88,17 @@ public class BukkitRegionManager extends RegionManager { private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitRegionManager.class.getSimpleName()); private final WorldUtil worldUtil; + private final ChunkCoordinatorFactory chunkCoordinatorFactory; + private final ChunkCoordinatorBuilderFactory chunkCoordinatorBuilderFactory; @Inject public BukkitRegionManager(@Nonnull final ChunkManager chunkManager, - @Nonnull final WorldUtil worldUtil) { - super(chunkManager, worldUtil); + @Nonnull final WorldUtil worldUtil, + @Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory, + @Nonnull ChunkCoordinatorBuilderFactory chunkCoordinatorBuilderFactory) { + super(chunkManager, worldUtil, chunkCoordinatorBuilderFactory); this.worldUtil = worldUtil; - } - - public static boolean isIn(CuboidRegion region, int x, int z) { - return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX() - && z >= region.getMinimumPoint().getZ() && z <= region.getMaximumPoint().getZ(); + this.chunkCoordinatorFactory = chunkCoordinatorFactory; + this.chunkCoordinatorBuilderFactory = chunkCoordinatorBuilderFactory; } @Override public Set getChunkChunks(String world) { @@ -207,37 +210,33 @@ public class BukkitRegionManager extends RegionManager { return count; } - @Override public boolean copyRegion(Location pos1, Location pos2, Location newPos, + @Override @Inject + public boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, final Runnable whenDone) { final int relX = newPos.getX() - pos1.getX(); final int relZ = newPos.getZ() - pos1.getZ(); - - final CuboidRegion region = - RegionUtil.createRegion(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); - final BukkitWorld oldWorld = new BukkitWorld((World) pos1.getWorld()); + final com.sk89q.worldedit.world.World oldWorld = worldUtil.getWeWorld(pos1.getWorldName()); final BukkitWorld newWorld = new BukkitWorld((World) newPos.getWorld()); + assert oldWorld.equals(newWorld); final ContentMap map = new ContentMap(); final QueueCoordinator queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(newWorld, false); - ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { - @Override public void run(int[] value) { - int bx = value[2]; - int bz = value[3]; - int tx = value[4]; - int tz = value[5]; - BlockVector2 loc = BlockVector2.at(value[0], value[1]); - int cxx = loc.getX() << 4; - int czz = loc.getZ() << 4; - PaperLib.getChunkAtAsync(oldWorld, loc.getX(), loc.getZ()) - .thenAccept(chunk1 -> map.saveEntitiesIn(chunk1, region)).thenRun(() -> { - for (int x = bx & 15; x <= (tx & 15); x++) { - for (int z = bz & 15; z <= (tz & 15); z++) { - map.saveBlocks(oldWorld, 256, cxx + x, czz + z, relX, relZ); - } + chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(newWorld) + .withRegion(pos1, pos2).withThrowableConsumer(Throwable::printStackTrace) + .withRegion(pos1, pos2).withInitialBatchSize(4).withMaxIterationTime(45) + .withConsumer(chunk -> { + int cbx = chunk.getX(); + int cbz = chunk.getZ(); + int bx = Math.max(pos1.getX() & 15, 0); + int bz = Math.max(pos1.getZ() & 15, 0); + int tx = Math.min(pos2.getX() & 15, 15); + int tz = Math.min(pos2.getZ() & 15, 15); + for (int x = bx; x <= tx; x++) { + for (int z = bz; z <= tz; z++) { + map.saveBlocks(newWorld, 256, cbx + x, cbz + z, relX, relZ); } - }); - } - }, () -> { + } + }).withFinalAction(() -> { for (Entry entry : map.allBlocks.entrySet()) { PlotLoc loc = entry.getKey(); BaseBlock[] blocks = entry.getValue(); @@ -250,17 +249,17 @@ public class BukkitRegionManager extends RegionManager { } queue.setCompleteTask(() -> { //map.restoreBlocks(newWorld, 0, 0); - map.restoreEntities((World) newPos.getWorld(), relX, relZ); + map.restoreEntities(Bukkit.getWorld(newPos.getWorldName()), relX, relZ); TaskManager.runTask(whenDone); }); queue.enqueue(); - }, 5); + }); return true; } - @Override public boolean regenerateRegion(final Location pos1, final Location pos2, + @Override @Inject public boolean regenerateRegion(final Location pos1, final Location pos2, final boolean ignoreAugment, final Runnable whenDone) { - final String world = pos1.getWorldName(); + final BukkitWorld world = new BukkitWorld((World) pos1.getWorld()); final int p1x = pos1.getX(); final int p1z = pos1.getZ(); @@ -278,137 +277,123 @@ public class BukkitRegionManager extends RegionManager { chunks.add(BlockVector2.at(x, z)); } } - final World worldObj = Bukkit.getWorld(world); - checkNotNull(worldObj, "Critical error during regeneration."); - final BukkitWorld bukkitWorldObj = new BukkitWorld(worldObj); - TaskManager.runTask(new Runnable() { - @Override public void run() { - long start = System.currentTimeMillis(); - while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) { - final BlockVector2 chunk = chunks.remove(0); - int x = chunk.getX(); - int z = chunk.getZ(); - int xxb = x << 4; - int zzb = z << 4; - int xxt = xxb + 15; - int zzt = zzb + 15; - PaperLib.getChunkAtAsync(worldObj, x, z, false).thenAccept(chunkObj -> { - if (chunkObj == null) { - return; - } - final QueueCoordinator queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false); - if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) { - AugmentedUtils.bypass(ignoreAugment, - () -> queue.regenChunkSafe(chunk.getX(), chunk.getZ())); - return; - } - boolean checkX1 = false; - int xxb2; + final QueueCoordinator queue = + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false); + chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(world) + .withRegion(pos1, pos2).withThrowableConsumer(Throwable::printStackTrace) + .withRegion(pos1, pos2).withInitialBatchSize(4).withMaxIterationTime(45) + .withConsumer(chunk -> { - if (x == bcx) { - xxb2 = p1x - 1; - checkX1 = true; - } else { - xxb2 = xxb; - } - boolean checkX2 = false; - int xxt2; - if (x == tcx) { - xxt2 = p2x + 1; - checkX2 = true; - } else { - xxt2 = xxt; - } - boolean checkZ1 = false; - int zzb2; - if (z == bcz) { - zzb2 = p1z - 1; - checkZ1 = true; - } else { - zzb2 = zzb; - } - boolean checkZ2 = false; - int zzt2; - if (z == tcz) { - zzt2 = p2z + 1; - checkZ2 = true; - } else { - zzt2 = zzt; - } - final ContentMap map = new ContentMap(); - if (checkX1) { - map.saveRegion(bukkitWorldObj, xxb, xxb2, zzb2, zzt2); // - } - if (checkX2) { - map.saveRegion(bukkitWorldObj, xxt2, xxt, zzb2, zzt2); // - } - if (checkZ1) { - map.saveRegion(bukkitWorldObj, xxb2, xxt2, zzb, zzb2); // - } - if (checkZ2) { - map.saveRegion(bukkitWorldObj, xxb2, xxt2, zzt2, zzt); // - } - if (checkX1 && checkZ1) { - map.saveRegion(bukkitWorldObj, xxb, xxb2, zzb, zzb2); // - } - if (checkX2 && checkZ1) { - map.saveRegion(bukkitWorldObj, xxt2, xxt, zzb, zzb2); // ? - } - if (checkX1 && checkZ2) { - map.saveRegion(bukkitWorldObj, xxb, xxb2, zzt2, zzt); // ? - } - if (checkX2 && checkZ2) { - map.saveRegion(bukkitWorldObj, xxt2, xxt, zzt2, zzt); // - } - CuboidRegion currentPlotClear = RegionUtil - .createRegion(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); - map.saveEntitiesOut(chunkObj, currentPlotClear); - AugmentedUtils.bypass(ignoreAugment, () -> ChunkManager - .setChunkInPlotArea(null, new RunnableVal() { - @Override public void run(ScopedQueueCoordinator value) { - Location min = value.getMin(); - int bx = min.getX(); - int bz = min.getZ(); - for (int x1 = 0; x1 < 16; x1++) { - for (int z1 = 0; z1 < 16; z1++) { - PlotLoc plotLoc = new PlotLoc(bx + x1, bz + z1); - BaseBlock[] ids = map.allBlocks.get(plotLoc); - if (ids != null) { - for (int y = 0; - y < Math.min(128, ids.length); y++) { - BaseBlock id = ids[y]; - if (id != null) { - value.setBlock(x1, y, z1, id); - } else { - value.setBlock(x1, y, z1, - BlockTypes.AIR.getDefaultState()); - } - } - for (int y = Math.min(128, ids.length); - y < ids.length; y++) { - BaseBlock id = ids[y]; - if (id != null) { - value.setBlock(x1, y, z1, id); - } - } + int x = chunk.getX(); + int z = chunk.getZ(); + int xxb = x << 4; + int zzb = z << 4; + int xxt = xxb + 15; + int zzt = zzb + 15; + if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) { + AugmentedUtils.bypass(ignoreAugment, + () -> queue.regenChunkSafe(chunk.getX(), chunk.getZ())); + return; + } + boolean checkX1 = false; + + int xxb2; + + if (x == bcx) { + xxb2 = p1x - 1; + checkX1 = true; + } else { + xxb2 = xxb; + } + boolean checkX2 = false; + int xxt2; + if (x == tcx) { + xxt2 = p2x + 1; + checkX2 = true; + } else { + xxt2 = xxt; + } + boolean checkZ1 = false; + int zzb2; + if (z == bcz) { + zzb2 = p1z - 1; + checkZ1 = true; + } else { + zzb2 = zzb; + } + boolean checkZ2 = false; + int zzt2; + if (z == tcz) { + zzt2 = p2z + 1; + checkZ2 = true; + } else { + zzt2 = zzt; + } + final ContentMap map = new ContentMap(); + if (checkX1) { + map.saveRegion(world, xxb, xxb2, zzb2, zzt2); // + } + if (checkX2) { + map.saveRegion(world, xxt2, xxt, zzb2, zzt2); // + } + if (checkZ1) { + map.saveRegion(world, xxb2, xxt2, zzb, zzb2); // + } + if (checkZ2) { + map.saveRegion(world, xxb2, xxt2, zzt2, zzt); // + } + if (checkX1 && checkZ1) { + map.saveRegion(world, xxb, xxb2, zzb, zzb2); // + } + if (checkX2 && checkZ1) { + map.saveRegion(world, xxt2, xxt, zzb, zzb2); // ? + } + if (checkX1 && checkZ2) { + map.saveRegion(world, xxb, xxb2, zzt2, zzt); // ? + } + if (checkX2 && checkZ2) { + map.saveRegion(world, xxt2, xxt, zzt2, zzt); // + } + CuboidRegion currentPlotClear = + RegionUtil.createRegion(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); + map.saveEntitiesOut(Bukkit.getWorld(world.getName()).getChunkAt(x, z), + currentPlotClear); + AugmentedUtils.bypass(ignoreAugment, () -> ChunkManager + .setChunkInPlotArea(null, new RunnableVal() { + @Override public void run(ScopedQueueCoordinator value) { + Location min = value.getMin(); + int bx = min.getX(); + int bz = min.getZ(); + for (int x1 = 0; x1 < 16; x1++) { + for (int z1 = 0; z1 < 16; z1++) { + PlotLoc plotLoc = new PlotLoc(bx + x1, bz + z1); + BaseBlock[] ids = map.allBlocks.get(plotLoc); + if (ids != null) { + for (int y = 0; y < Math.min(128, ids.length); y++) { + BaseBlock id = ids[y]; + if (id != null) { + value.setBlock(x1, y, z1, id); + } else { + value.setBlock(x1, y, z1, + BlockTypes.AIR.getDefaultState()); + } + } + for (int y = Math.min(128, ids.length); + y < ids.length; y++) { + BaseBlock id = ids[y]; + if (id != null) { + value.setBlock(x1, y, z1, id); } } } } - }, world, chunk)); - //map.restoreBlocks(worldObj, 0, 0); - map.restoreEntities(worldObj, 0, 0); - }); - } - if (!chunks.isEmpty()) { - TaskManager.runTaskLater(this, TaskTime.ticks(1L)); - } else { - TaskManager.runTaskLater(whenDone, TaskTime.ticks(1L)); - } - } - }); + } + } + }, world.getName(), chunk)); + //map.restoreBlocks(worldObj, 0, 0); + map.restoreEntities(Bukkit.getWorld(world.getName()), 0, 0); + }).withFinalAction(whenDone); return true; } @@ -471,19 +456,22 @@ public class BukkitRegionManager extends RegionManager { region.getMinimumPoint().getY(), region.getMinimumPoint().getZ() - extendBiome); Location pos2 = Location.at(world, region.getMaximumPoint().getX() + extendBiome, region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome); - final QueueCoordinator queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false); + final QueueCoordinator queue = PlotSquared.platform().getGlobalBlockQueue() + .getNewQueue(worldUtil.getWeWorld(world), false); - ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { - @Override public void run(int[] value) { - BlockVector2 loc = BlockVector2.at(value[0], value[1]); - PlotSquared.platform().getChunkManager().loadChunk(world, loc, false) - .thenRun(() -> { - MainUtil.setBiome(world, value[2], value[3], value[4], value[5], biome); - queue.refreshChunk(value[0], value[1]); - }); - } - }, whenDone, 5); + final int minX = pos1.getX(); + final int minZ = pos1.getZ(); + final int maxX = pos2.getX(); + final int maxZ = pos2.getZ(); + queue.setChunkConsumer(blockVector2 -> { + final int cx = blockVector2.getX() << 4; + final int cz = blockVector2.getZ() << 4; + MainUtil + .setBiome(world, Math.max(minX, cx), Math.max(minZ, cz), Math.min(maxX, cx + 15), + Math.min(maxZ, cz + 15), biome); + worldUtil.refreshChunk(blockVector2.getBlockX(), blockVector2.getBlockZ(), world); + }); + queue.enqueue(); } private void count(int[] count, Entity entity) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 75ac9a1be..393a88982 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -111,15 +111,18 @@ import java.util.function.IntConsumer; import java.util.stream.Stream; @SuppressWarnings({"unused", "WeakerAccess"}) -@Singleton public class BukkitUtil extends WorldUtil { +@Singleton +public class BukkitUtil extends WorldUtil { - private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitUtil.class.getSimpleName()); + private static final Logger logger = + LoggerFactory.getLogger("P2/" + BukkitUtil.class.getSimpleName()); private static String lastString = null; private static World lastWorld = null; private static Player lastPlayer = null; private static BukkitPlayer lastPlotPlayer = null; + private final Collection tileEntityTypes = new HashSet<>(); @Inject public BukkitUtil(@Nonnull final RegionManager regionManager) { super(regionManager); @@ -139,7 +142,8 @@ import java.util.stream.Stream; final Player player = OfflinePlayerUtil.loadPlayer(op); player.loadData(); return new BukkitPlayer(PlotSquared.get().getPlotAreaManager(), - PlotSquared.get().getEventDispatcher(), player, true, PlotSquared.platform().getEconHandler()); + PlotSquared.get().getEventDispatcher(), player, true, + PlotSquared.platform().getEconHandler()); } /** @@ -194,18 +198,6 @@ import java.util.stream.Stream; return PlotPlayer.wrap(player); } - /** - * Gets the PlotPlayer for a UUID. The PlotPlayer is usually cached and - * will provide useful functions relating to players. - * - * @param uuid the uuid to wrap - * @return a {@code PlotPlayer} - * @see PlotPlayer#wrap(Object) - */ - @Override public PlotPlayer wrapPlayer(UUID uuid) { - return PlotPlayer.wrap(Bukkit.getOfflinePlayer(uuid)); - } - /** * Gets the number of plots, which the player is able to build in. * @@ -287,18 +279,19 @@ import java.util.stream.Stream; public static Location getLocation(final org.bukkit.Location location) { return Location.at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), - MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ())); + MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), + MathMan.roundInt(location.getZ())); } public static Location getLocationFull(final org.bukkit.Location location) { return Location.at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), - MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), location.getYaw(), - location.getPitch()); + MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), + MathMan.roundInt(location.getZ()), location.getYaw(), location.getPitch()); } public static org.bukkit.Location getLocation(@Nonnull final Location location) { - return new org.bukkit.Location((World) location.getWorld().getPlatformWorld(), location.getX(), - location.getY(), location.getZ()); + return new org.bukkit.Location((World) location.getWorld().getPlatformWorld(), + location.getX(), location.getY(), location.getZ()); } public static World getWorld(@Nonnull final String string) { @@ -321,8 +314,7 @@ import java.util.stream.Stream; public static Location getLocation(@Nonnull final Entity entity) { final org.bukkit.Location location = entity.getLocation(); String world = location.getWorld().getName(); - return Location.at(world, location.getBlockX(), location.getBlockY(), - location.getBlockZ()); + return Location.at(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Nonnull public static Location getLocationFull(@Nonnull final Entity entity) { @@ -336,6 +328,38 @@ import java.util.stream.Stream; return BukkitAdapter.adapt(plotBlock.getBlockType()); } + private static void ensureLoaded(final String world, final int x, final int z, + final Consumer chunkConsumer) { + PaperLib.getChunkAtAsync(getWorld(world), x >> 4, z >> 4, true) + .thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); + } + + private static void ensureLoaded(final Location location, final Consumer chunkConsumer) { + PaperLib.getChunkAtAsync(getLocation(location), true) + .thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); + } + + private static void ensureMainThread(final Consumer consumer, final T value) { + if (Bukkit.isPrimaryThread()) { + consumer.accept(value); + } else { + Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), + () -> consumer.accept(value)); + } + } + + /** + * Gets the PlotPlayer for a UUID. The PlotPlayer is usually cached and + * will provide useful functions relating to players. + * + * @param uuid the uuid to wrap + * @return a {@code PlotPlayer} + * @see PlotPlayer#wrap(Object) + */ + @Override public PlotPlayer wrapPlayer(UUID uuid) { + return PlotPlayer.wrap(Bukkit.getOfflinePlayer(uuid)); + } + @Override public boolean isBlockSame(BlockState block1, BlockState block2) { if (block1.equals(block2)) { return true; @@ -357,8 +381,7 @@ import java.util.stream.Stream; return BukkitAdapter.adapt(getWorld(world).getBiome(x, z)); } - @Override - public void getHighestBlock(@Nonnull final String world, final int x, final int z, + @Override public void getHighestBlock(@Nonnull final String world, final int x, final int z, final IntConsumer result) { ensureLoaded(world, x, z, chunk -> { final World bukkitWorld = getWorld(world); @@ -437,8 +460,9 @@ import java.util.stream.Stream; @Override public Location getSpawn(@Nonnull final String world) { final org.bukkit.Location temp = getWorld(world).getSpawnLocation(); - return Location.at(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), - temp.getYaw(), temp.getPitch()); + return Location + .at(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), + temp.getPitch()); } @Override public void setSpawn(@Nonnull final Location location) { @@ -518,7 +542,8 @@ import java.util.stream.Stream; @Nonnull final BiomeType biomeType) { final World world = getWorld(worldName); if (world == null) { - logger.warn("[P2] An error occured while setting the biome because the world was null", new RuntimeException()); + logger.warn("[P2] An error occured while setting the biome because the world was null", + new RuntimeException()); return; } final Biome biome = BukkitAdapter.adapt(biomeType); @@ -536,6 +561,10 @@ import java.util.stream.Stream; return new BukkitWorld(Bukkit.getWorld(world)); } + @Override public void refreshChunk(int x, int z, String world) { + Bukkit.getWorld(world).refreshChunk(x, z); + } + @Override public void getBlock(@Nonnull final Location location, final Consumer result) { ensureLoaded(location, chunk -> { @@ -571,8 +600,7 @@ import java.util.stream.Stream; Bukkit.getPlayer(player.getUUID()).setFoodLevel(foodLevel); } - @Override - public Set getTypesInCategory( + @Override public Set getTypesInCategory( final String category) { final Collection> allowedInterfaces = new HashSet<>(); switch (category) { @@ -653,7 +681,6 @@ import java.util.stream.Stream; return types; } - private final Collection tileEntityTypes = new HashSet<>(); @Override public Collection getTileEntityTypes() { if (this.tileEntityTypes.isEmpty()) { // Categories @@ -665,44 +692,21 @@ import java.util.stream.Stream; // Add these from strings Stream.of("barrel", "beacon", "beehive", "bee_nest", "bell", "blast_furnace", "brewing_stand", "campfire", "chest", "ender_chest", "trapped_chest", - "command_block", "end_gateway", "hopper", "jigsaw", "jubekox", - "lectern", "note_block", "black_shulker_box", "blue_shulker_box", - "brown_shulker_box", "cyan_shulker_box", "gray_shulker_box", "green_shulker_box", + "command_block", "end_gateway", "hopper", "jigsaw", "jubekox", "lectern", + "note_block", "black_shulker_box", "blue_shulker_box", "brown_shulker_box", + "cyan_shulker_box", "gray_shulker_box", "green_shulker_box", "light_blue_shulker_box", "light_gray_shulker_box", "lime_shulker_box", "magenta_shulker_box", "orange_shulker_box", "pink_shulker_box", "purple_shulker_box", "red_shulker_box", "shulker_box", "white_shulker_box", "yellow_shulker_box", "smoker", "structure_block", "structure_void") - .map(BlockTypes::get) - .filter(Objects::nonNull) - .forEach(tileEntityTypes::add); + .map(BlockTypes::get).filter(Objects::nonNull).forEach(tileEntityTypes::add); } return this.tileEntityTypes; } - @Override - public int getTileEntityCount(String world, BlockVector2 chunk) { + @Override public int getTileEntityCount(String world, BlockVector2 chunk) { return Bukkit.getWorld(world).getChunkAt(chunk.getBlockX(), chunk.getBlockZ()) .getTileEntities().length; } - private static void ensureLoaded(final String world, final int x, final int z, - final Consumer chunkConsumer) { - PaperLib.getChunkAtAsync(getWorld(world), x >> 4, z >> 4, true) - .thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); - } - - private static void ensureLoaded(final Location location, final Consumer chunkConsumer) { - PaperLib.getChunkAtAsync(getLocation(location), true) - .thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); - } - - private static void ensureMainThread(final Consumer consumer, final T value) { - if (Bukkit.isPrimaryThread()) { - consumer.accept(value); - } else { - Bukkit.getScheduler() - .runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> consumer.accept(value)); - } - } - } diff --git a/Core/src/main/java/com/plotsquared/core/command/Clear.java b/Core/src/main/java/com/plotsquared/core/command/Clear.java index 1eee3a26c..2f7c48bcd 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Clear.java +++ b/Core/src/main/java/com/plotsquared/core/command/Clear.java @@ -42,6 +42,8 @@ import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.task.RunnableVal2; import com.plotsquared.core.util.task.RunnableVal3; +import com.plotsquared.core.util.task.TaskManager; + import javax.annotation.Nonnull; import java.util.concurrent.CompletableFuture; @@ -91,7 +93,7 @@ public class Clear extends Command { final long start = System.currentTimeMillis(); boolean result = plot.clear(true, false, () -> { plot.unlink(); - this.blockQueue.addEmptyTask(() -> { + TaskManager.runTask(() -> { plot.removeRunning(); // If the state changes, then mark it as no longer done if (DoneFlag.isDone(plot)) { diff --git a/Core/src/main/java/com/plotsquared/core/command/Template.java b/Core/src/main/java/com/plotsquared/core/command/Template.java index 5e90d5a90..3dd97eecb 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Template.java +++ b/Core/src/main/java/com/plotsquared/core/command/Template.java @@ -70,20 +70,17 @@ public class Template extends SubCommand { private final YamlConfiguration worldConfiguration; private final File worldFile; private final SetupUtils setupUtils; - private final GlobalBlockQueue globalBlockQueue; private final WorldUtil worldUtil; @Inject public Template(@Nonnull final PlotAreaManager plotAreaManager, @WorldConfig @Nonnull final YamlConfiguration worldConfiguration, @WorldFile @Nonnull final File worldFile, @Nonnull final SetupUtils setupUtils, - @Nonnull final GlobalBlockQueue globalBlockQueue, @Nonnull final WorldUtil worldUtil) { this.plotAreaManager = plotAreaManager; this.worldConfiguration = worldConfiguration; this.worldFile = worldFile; this.setupUtils = setupUtils; - this.globalBlockQueue = globalBlockQueue; this.worldUtil = worldUtil; } @@ -216,7 +213,7 @@ public class Template extends SubCommand { .worldName(world); this.setupUtils.setupWorld(builder); - this.globalBlockQueue.addEmptyTask(() -> { + TaskManager.runTask(() -> { MainUtil.sendMessage(player, "Done!"); player.teleport(this.worldUtil.getSpawn(world), TeleportCause.COMMAND); }); diff --git a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java index b046da010..c6dfe69e3 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java @@ -25,7 +25,6 @@ */ package com.plotsquared.core.generator; -import com.plotsquared.core.PlotSquared; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.location.Direction; import com.plotsquared.core.location.Location; @@ -37,6 +36,7 @@ import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.BlockUtil; import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.RegionManager; +import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.block.BlockTypes; @@ -92,7 +92,8 @@ public class ClassicPlotManager extends SquarePlotManager { .equals(classicPlotWorld.CLAIMED_WALL_BLOCK)) { setWall(plot.getId(), classicPlotWorld.WALL_BLOCK.toPattern()); } - return PlotSquared.platform().getGlobalBlockQueue().addEmptyTask(whenDone); + TaskManager.runTask(whenDone); + return true; } public boolean setFloor(PlotId plotId, Pattern blocks) { diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index ef20a88b6..ba2576395 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -510,7 +510,7 @@ public class HybridUtils { } } } - blockQueue.addEmptyTask(() -> TaskManager.runTaskLater(task, TaskTime.seconds(1L))); + TaskManager.runTaskLater(task, TaskTime.seconds(1L)); }); } } diff --git a/Core/src/main/java/com/plotsquared/core/inject/factory/QueueCoordinatorFactory.java b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorBuilderFactory.java similarity index 79% rename from Core/src/main/java/com/plotsquared/core/inject/factory/QueueCoordinatorFactory.java rename to Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorBuilderFactory.java index 969ceed3b..bfcbe206d 100644 --- a/Core/src/main/java/com/plotsquared/core/inject/factory/QueueCoordinatorFactory.java +++ b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorBuilderFactory.java @@ -25,12 +25,16 @@ */ package com.plotsquared.core.inject.factory; -import com.plotsquared.core.queue.QueueCoordinator; +import com.google.inject.Inject; +import com.google.inject.assistedinject.Assisted; +import com.plotsquared.core.queue.ChunkCoordinatorBuilder; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; -public interface QueueCoordinatorFactory { +public interface ChunkCoordinatorBuilderFactory { - @Nonnull QueueCoordinator create(); + @Inject @Nonnull ChunkCoordinatorBuilder create( + @Assisted @NotNull ChunkCoordinatorFactory chunkCoordinatorFactory); } diff --git a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java new file mode 100644 index 000000000..463f58bb1 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java @@ -0,0 +1,48 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ +package com.plotsquared.core.inject.factory; + +import com.google.inject.assistedinject.Assisted; +import com.plotsquared.core.queue.ChunkCoordinator; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.world.World; +import org.jetbrains.annotations.NotNull; + +import javax.annotation.Nonnull; +import java.util.Collection; +import java.util.function.Consumer; + +public interface ChunkCoordinatorFactory { + + @Nonnull ChunkCoordinator create(@Assisted final long maxIterationTime, + @Assisted final int initialBatchSize, + @NotNull @Assisted final Consumer chunkConsumer, + @NotNull @Assisted final World world, + @NotNull @Assisted final Collection requestedChunks, + @NotNull @Assisted final Runnable whenDone, + @NotNull @Assisted final Consumer throwableConsumer); + +} diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index 827aa2c70..22b57da4d 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -965,7 +965,7 @@ public class Plot { manager.claimPlot(current); } } - blockQueue.addEmptyTask(run); + TaskManager.runTask(run); return; } Plot current = queue.poll(); @@ -1061,12 +1061,10 @@ public class Plot { current.setMerged(merged); } if (createSign) { - blockQueue.addEmptyTask(() -> { - TaskManager.runTaskAsync(() -> { - for (Plot current : plots) { - current.setSign(MainUtil.getName(current.getOwnerAbs())); - } - }); + TaskManager.runTaskAsync(() -> { + for (Plot current : plots) { + current.setSign(MainUtil.getName(current.getOwnerAbs())); + } }); } if (createRoad) { @@ -1687,7 +1685,8 @@ public class Plot { * This should not need to be called */ public void refreshChunks() { - QueueCoordinator queue = this.blockQueue.getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(getWorldName()), false); + QueueCoordinator queue = this.blockQueue + .getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(getWorldName()), false); HashSet chunks = new HashSet<>(); for (CuboidRegion region : Plot.this.getRegions()) { for (int x = region.getMinimumPoint().getX() >> 4; @@ -1695,7 +1694,7 @@ public class Plot { for (int z = region.getMinimumPoint().getZ() >> 4; z <= region.getMaximumPoint().getZ() >> 4; z++) { if (chunks.add(BlockVector2.at(x, z))) { - queue.refreshChunk(x, z); + worldUtil.refreshChunk(x, z, getWorldName()); } } } @@ -1711,7 +1710,8 @@ public class Plot { return; } Location location = manager.getSignLoc(this); - QueueCoordinator queue = this.blockQueue.getNewQueue(getWorldName(), false); + QueueCoordinator queue = + this.blockQueue.getNewQueue(worldUtil.getWeWorld(getWorldName()), false); queue.setBlock(location.getX(), location.getY(), location.getZ(), BlockTypes.AIR.getDefaultState()); queue.enqueue(); diff --git a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java index 2d13a70e3..87fe6d634 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java @@ -31,7 +31,6 @@ import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import lombok.Getter; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -39,7 +38,7 @@ import java.util.Objects; public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator { - @Getter private final PlotArea area; + private final PlotArea area; public AreaBoundDelegateQueueCoordinator(@Nonnull final PlotArea area, @Nullable final QueueCoordinator parent) { @@ -47,6 +46,10 @@ public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator this.area = Objects.requireNonNull(area); } + public PlotArea getArea() { + return this.area; + } + @Override public boolean setBlock(int x, int y, int z, BlockState id) { if (area.contains(x, z)) { return super.setBlock(x, y, z, id); diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index 3e3e8c4cf..7abc64bc4 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -33,22 +33,23 @@ import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import lombok.Getter; import javax.annotation.Nonnull; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; public abstract class BasicQueueCoordinator extends QueueCoordinator { private final World world; - @Getter private final ConcurrentHashMap blockChunks = + private final ConcurrentHashMap blockChunks = new ConcurrentHashMap<>(); private long modified; private LocalChunk lastWrappedChunk; private int lastX = Integer.MIN_VALUE; private int lastZ = Integer.MIN_VALUE; - @Getter private boolean settingBiomes = false; - @Getter private boolean settingTiles = false; + private boolean settingBiomes = false; + private boolean settingTiles = false; + private Consumer consumer = null; private GlobalBlockQueue globalBlockQueue; @@ -97,7 +98,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return setBlock(x, y, z, id.toBaseBlock()); } - @Override public final boolean setBiome(int x, int z, BiomeType biomeType) { + @Override public boolean setBiome(int x, int z, BiomeType biomeType) { LocalChunk chunk = getChunk(x >> 4, z >> 4); for (int y = 0; y < 256; y++) { chunk.setBiome(x & 15, y, z & 15, biomeType); @@ -113,17 +114,37 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return true; } - @Override public final boolean setTile(int x, int y, int z, CompoundTag tag) { + @Override public boolean isSettingBiomes() { + return this.settingBiomes; + } + + @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { LocalChunk chunk = getChunk(x >> 4, z >> 4); chunk.setTile(x, y, z, tag); settingTiles = true; return true; } + @Override public boolean isSettingTiles() { + return this.settingTiles; + } + + public ConcurrentHashMap getBlockChunks() { + return this.blockChunks; + } + public final void setChunk(LocalChunk chunk) { this.blockChunks.put(BlockVector2.at(chunk.getX(), chunk.getZ()), chunk); } + public final Consumer getChunkConsumer() { + return this.consumer; + } + + public final void setChunkConsumer(Consumer consumer) { + this.consumer = consumer; + } + private LocalChunk getChunk(final int chunkX, final int chunkZ) { if (chunkX != lastX || chunkZ != lastZ) { lastX = chunkX; diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java new file mode 100644 index 000000000..d596d27dc --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java @@ -0,0 +1,22 @@ +package com.plotsquared.core.queue; + +import com.plotsquared.core.util.task.PlotSquaredTask; + +public abstract class ChunkCoordinator implements PlotSquaredTask { + + @Override public abstract void runTask(); + + @Override public boolean isCancelled() { + return false; + } + + @Override public void cancel() { + // Do nothing + } + + public abstract void start(); + + public abstract int getRemainingChunks(); + + public abstract int getTotalChunks(); +} diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java new file mode 100644 index 000000000..a968e1992 --- /dev/null +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java @@ -0,0 +1,113 @@ +package com.plotsquared.core.queue; + +import com.google.common.base.Preconditions; +import com.google.inject.Inject; +import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory; +import com.plotsquared.core.location.Location; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.world.World; +import org.jetbrains.annotations.NotNull; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.function.Consumer; + +public class ChunkCoordinatorBuilder { + + private final List requestedChunks = new LinkedList<>(); + private Consumer throwableConsumer = Throwable::printStackTrace; + private World world; + private Consumer chunkConsumer; + private Runnable whenDone = () -> { + }; + private long maxIterationTime = 60; // A little over 1 tick; + private int initialBatchSize = 4; + private final ChunkCoordinatorFactory chunkCoordinatorFactory; + + @Inject public ChunkCoordinatorBuilder(@Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory) { + this.chunkCoordinatorFactory = chunkCoordinatorFactory; + } + + @NotNull public ChunkCoordinatorBuilder inWorld(@NotNull final World world) { + this.world = Preconditions.checkNotNull(world, "World may not be null"); + return this; + } + + @NotNull public ChunkCoordinatorBuilder withChunk(@NotNull final BlockVector2 chunkLocation) { + this.requestedChunks + .add(Preconditions.checkNotNull(chunkLocation, "Chunk location may not be null")); + return this; + } + + @NotNull public ChunkCoordinatorBuilder withChunks( + @NotNull final Collection chunkLocations) { + chunkLocations.forEach(this::withChunk); + return this; + } + + @NotNull public ChunkCoordinatorBuilder withRegion(Location pos1, Location pos2) { + 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 ArrayList chunks = new ArrayList<>(); + + for (int x = bcx; x <= tcx; x++) { + for (int z = bcz; z <= tcz; z++) { + chunks.add(BlockVector2.at(x, z)); + } + } + + chunks.forEach(this::withChunk); + return this; + } + + @NotNull public ChunkCoordinatorBuilder withConsumer( + @NotNull final Consumer chunkConsumer) { + this.chunkConsumer = + Preconditions.checkNotNull(chunkConsumer, "Chunk consumer may not be null"); + return this; + } + + @NotNull public ChunkCoordinatorBuilder withFinalAction(@NotNull final Runnable whenDone) { + this.whenDone = Preconditions.checkNotNull(whenDone, "Final action may not be null"); + return this; + } + + @NotNull public ChunkCoordinatorBuilder withMaxIterationTime(final long maxIterationTime) { + Preconditions.checkArgument(maxIterationTime > 0, "Max iteration time must be positive"); + this.maxIterationTime = maxIterationTime; + return this; + } + + @NotNull public ChunkCoordinatorBuilder withInitialBatchSize(final int initialBatchSize) { + Preconditions.checkArgument(initialBatchSize > 0, "Initial batch size must be positive"); + this.initialBatchSize = initialBatchSize; + return this; + } + + @NotNull public ChunkCoordinatorBuilder withThrowableConsumer( + @NotNull final Consumer throwableConsumer) { + this.throwableConsumer = + Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null"); + return this; + } + + @NotNull public ChunkCoordinator build() { + Preconditions.checkNotNull(this.world, "No world was supplied"); + Preconditions.checkNotNull(this.chunkConsumer, "No chunk consumer was supplied"); + Preconditions.checkNotNull(this.whenDone, "No final action was supplied"); + Preconditions.checkNotNull(this.throwableConsumer, "No throwable consumer was supplied"); + return chunkCoordinatorFactory.create(this.maxIterationTime, this.initialBatchSize, + this.chunkConsumer, this.world, this.requestedChunks, this.whenDone, + this.throwableConsumer); + } + +} diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index 790ad2a51..76cffc3be 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -27,11 +27,14 @@ package com.plotsquared.core.queue; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import java.util.function.Consumer; + public class DelegateQueueCoordinator extends QueueCoordinator { private final QueueCoordinator parent; @@ -111,4 +114,8 @@ public class DelegateQueueCoordinator extends QueueCoordinator { @Override public void setCompleteTask(Runnable whenDone) { parent.setCompleteTask(whenDone); } + + @Override public void setChunkConsumer(Consumer consumer) { + parent.setChunkConsumer(consumer); + } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java index 56437f0cd..0e2775b6d 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java @@ -27,8 +27,6 @@ package com.plotsquared.core.queue; import com.plotsquared.core.PlotSquared; import com.sk89q.worldedit.world.World; -import lombok.Getter; -import lombok.Setter; import java.util.ArrayList; import java.util.List; @@ -37,7 +35,7 @@ import java.util.concurrent.ConcurrentLinkedDeque; public class GlobalBlockQueue { private final ConcurrentLinkedDeque activeQueues; - @Getter @Setter private QueueProvider provider; + private QueueProvider provider; public GlobalBlockQueue(QueueProvider provider) { this.provider = provider; @@ -54,6 +52,14 @@ public class GlobalBlockQueue { return queue; } + public QueueProvider getProvider() { + return this.provider; + } + + public void setQueueProvider(QueueProvider provider) { + this.provider = provider; + } + /** * TODO Documentation needed. * diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java index e638fe4ef..af6a30fe3 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java @@ -6,18 +6,17 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; -import lombok.Getter; import java.util.HashMap; public class LocalChunk { - @Getter private final BasicQueueCoordinator parent; - @Getter private final int z; - @Getter private final int x; + private final BasicQueueCoordinator parent; + private final int x; + private final int z; - @Getter private final BaseBlock[][] baseblocks; - @Getter private final BiomeType[][] biomes; - @Getter private final HashMap tiles = new HashMap<>(); + private final BaseBlock[][] baseblocks; + private final BiomeType[][] biomes; + private final HashMap tiles = new HashMap<>(); public LocalChunk(BasicQueueCoordinator parent, int x, int z) { this.parent = parent; @@ -27,6 +26,30 @@ public class LocalChunk { biomes = new BiomeType[16][]; } + public BasicQueueCoordinator getParent() { + return this.parent; + } + + public int getX() { + return this.x; + } + + public int getZ() { + return this.z; + } + + public BaseBlock[][] getBaseblocks() { + return this.baseblocks; + } + + public BiomeType[][] getBiomes() { + return this.biomes; + } + + public HashMap getTiles() { + return this.tiles; + } + public void setBiome(final int x, final int y, final int z, final BiomeType biomeType) { final int i = MainUtil.CACHE_I[y][x][z]; final int j = MainUtil.CACHE_J[y][x][z]; diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index ca8b3a7c9..91194e25f 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -31,20 +31,21 @@ import com.plotsquared.core.location.Location; import com.plotsquared.core.util.PatternUtil; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import lombok.Getter; -import lombok.Setter; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import java.util.function.Consumer; public abstract class QueueCoordinator { - @Getter @Setter private boolean forceSync = false; - @Getter @Setter @Nullable private Object chunkObject; + private boolean forceSync = false; + @Nullable private Object chunkObject; @Inject private GlobalBlockQueue blockQueue; @@ -63,6 +64,22 @@ public abstract class QueueCoordinator { public abstract void setModified(long modified); + public boolean isForceSync() { + return forceSync; + } + + public void setForceSync(boolean forceSync) { + this.forceSync = forceSync; + } + + @Nullable public Object getChunkObject() { + return chunkObject; + } + + public void setChunkObject(@NotNull Object chunkObject) { + this.chunkObject = chunkObject; + } + /** * Sets the block at the coordinates provided to the given id. * @@ -103,6 +120,8 @@ public abstract class QueueCoordinator { public abstract void setCompleteTask(Runnable whenDone); + public abstract void setChunkConsumer(Consumer consumer); + public void setCuboid(Location pos1, Location pos2, BlockState block) { int yMin = Math.min(pos1.getY(), pos2.getY()); int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); diff --git a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java index 9b9bd9a7d..e94548d0e 100644 --- a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java @@ -26,10 +26,12 @@ package com.plotsquared.core.util; import com.plotsquared.core.PlotSquared; +import com.plotsquared.core.inject.factory.ChunkCoordinatorBuilderFactory; import com.plotsquared.core.location.Location; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotManager; +import com.plotsquared.core.queue.ChunkCoordinatorBuilder; import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.TaskManager; @@ -55,7 +57,8 @@ public abstract class RegionManager { public static RegionManager manager = null; private final ChunkManager chunkManager; - public RegionManager(@Nonnull final ChunkManager chunkManager, @Nonnull WorldUtil worldUtil) { + public RegionManager(@Nonnull final ChunkManager chunkManager, @Nonnull WorldUtil worldUtil, + @Nonnull ChunkCoordinatorBuilderFactory chunkCoordinatorBuilderFactory) { this.chunkManager = chunkManager; } @@ -95,12 +98,13 @@ public abstract class RegionManager { } } } - TaskManager.getPlatformImplementation().objectTask(chunks, new RunnableVal() { - @Override public void run(BlockVector2 value) { - chunkManager.loadChunk(world, value, false).thenRun(() -> task.run(value)); - } - }).thenAccept(ignore -> - TaskManager.getPlatformImplementation().taskLater(whenDone, TaskTime.ticks(1L))); + TaskManager.getPlatformImplementation() + .objectTask(chunks, new RunnableVal() { + @Override public void run(BlockVector2 value) { + chunkManager.loadChunk(world, value, false).thenRun(() -> task.run(value)); + } + }).thenAccept(ignore -> TaskManager.getPlatformImplementation() + .taskLater(whenDone, TaskTime.ticks(1L))); }); } diff --git a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java index 5d58c1c19..2b2f091bc 100644 --- a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java @@ -118,6 +118,8 @@ public abstract class WorldUtil { public abstract com.sk89q.worldedit.world.World getWeWorld(String world); + public abstract void refreshChunk(int x, int z, String world); + public void upload(@Nonnull final Plot plot, UUID uuid, String file, RunnableVal whenDone) { plot.getHome(home -> MainUtil.upload(uuid, file, "zip", new RunnableVal() { From 03983e888622f115e2fdac183caa817cae801d05 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Sat, 18 Jul 2020 13:55:54 +0100 Subject: [PATCH 26/49] Allow forcing of queues down pipelines to ensure whenDone runnables are called correctly Also remove autoQueue since it's never used and would be a bad idea --- .../bukkit/generator/BlockStatePopulator.java | 2 +- .../bukkit/queue/BukkitChunkCoordinator.java | 9 + .../bukkit/util/BukkitChunkManager.java | 4 +- .../bukkit/util/BukkitRegionManager.java | 6 +- .../com/plotsquared/core/command/Set.java | 7 +- .../com/plotsquared/core/command/Trim.java | 2 +- .../components/ComponentPresetManager.java | 138 ++++---- .../core/generator/AugmentedUtils.java | 2 +- .../core/generator/ClassicPlotManager.java | 330 +++++++++++------- .../core/generator/HybridPlotManager.java | 8 +- .../core/generator/HybridUtils.java | 6 +- .../core/generator/SquarePlotManager.java | 20 +- .../java/com/plotsquared/core/plot/Plot.java | 33 +- .../com/plotsquared/core/plot/PlotArea.java | 4 +- .../plotsquared/core/plot/PlotManager.java | 100 +++++- .../core/plot/world/SinglePlotManager.java | 44 ++- .../core/queue/GlobalBlockQueue.java | 5 +- .../plotsquared/core/util/ChunkManager.java | 2 +- .../plotsquared/core/util/RegionManager.java | 16 +- .../core/util/SchematicHandler.java | 2 +- 20 files changed, 468 insertions(+), 272 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java index c61e97e0f..e8cb8d533 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java @@ -57,7 +57,7 @@ final class BlockStatePopulator extends BlockPopulator { @Nonnull final Chunk source) { if (this.queue == null) { this.queue = PlotSquared.platform().getGlobalBlockQueue() - .getNewQueue(world.getName(), false); + .getNewQueue(world.getName()); } final PlotArea area = this.plotAreaManager.getPlotArea(world.getName(), null); if (area == null) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java index 04f6083b4..ff4d73f8f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java @@ -46,6 +46,15 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; +/** + * Utility that allows for the loading and coordination of chunk actions + *

+ * The coordinator takes in collection of chunk coordinates, loads them + * and allows the caller to specify a sink for the loaded chunks. The + * coordinator will prevent the chunks from being unloaded until the sink + * has fully consumed the chunk + *

+ **/ public final class BukkitChunkCoordinator extends ChunkCoordinator { private final List progressSubscribers = new LinkedList<>(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java index 103bf21fc..ed2898c65 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java @@ -78,9 +78,9 @@ public class BukkitChunkManager extends ChunkManager { BukkitWorld bukkitWorld2 = new BukkitWorld(world2); QueueCoordinator queue1 = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(bukkitWorld1, false); + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(bukkitWorld1); QueueCoordinator queue2 = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(bukkitWorld2, false); + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(bukkitWorld2); for (int x = Math.max(r1.getMinimumPoint().getX(), sx); x <= Math.min(r1.getMaximumPoint().getX(), sx + 15); x++) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java index 2b3f72764..7aa8af878 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java @@ -220,7 +220,7 @@ public class BukkitRegionManager extends RegionManager { assert oldWorld.equals(newWorld); final ContentMap map = new ContentMap(); final QueueCoordinator queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(newWorld, false); + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(newWorld); chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(newWorld) .withRegion(pos1, pos2).withThrowableConsumer(Throwable::printStackTrace) .withRegion(pos1, pos2).withInitialBatchSize(4).withMaxIterationTime(45) @@ -279,7 +279,7 @@ public class BukkitRegionManager extends RegionManager { } final QueueCoordinator queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world, false); + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world); chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(world) .withRegion(pos1, pos2).withThrowableConsumer(Throwable::printStackTrace) .withRegion(pos1, pos2).withInitialBatchSize(4).withMaxIterationTime(45) @@ -457,7 +457,7 @@ public class BukkitRegionManager extends RegionManager { Location pos2 = Location.at(world, region.getMaximumPoint().getX() + extendBiome, region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome); final QueueCoordinator queue = PlotSquared.platform().getGlobalBlockQueue() - .getNewQueue(worldUtil.getWeWorld(world), false); + .getNewQueue(worldUtil.getWeWorld(world)); final int minX = pos1.getX(); final int minZ = pos1.getZ(); diff --git a/Core/src/main/java/com/plotsquared/core/command/Set.java b/Core/src/main/java/com/plotsquared/core/command/Set.java index 743433ad2..ec3600e1b 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Set.java +++ b/Core/src/main/java/com/plotsquared/core/command/Set.java @@ -35,6 +35,7 @@ import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotManager; import com.plotsquared.core.queue.GlobalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.PatternUtil; import com.plotsquared.core.util.Permissions; @@ -157,11 +158,13 @@ public class Set extends SubCommand { BackupManager.backup(player, plot, () -> { plot.addRunning(); + QueueCoordinator queue = plotArea.getQueue(); for (Plot current : plot.getConnectedPlots()) { - current.setComponent(component, pattern); + current.setComponent(component, pattern, queue); } + queue.setCompleteTask(plot::removeRunning); + queue.enqueue(); MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); - blockQueue.addEmptyTask(plot::removeRunning); }); return true; } diff --git a/Core/src/main/java/com/plotsquared/core/command/Trim.java b/Core/src/main/java/com/plotsquared/core/command/Trim.java index b40d6f03d..1852e10e4 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Trim.java +++ b/Core/src/main/java/com/plotsquared/core/command/Trim.java @@ -190,7 +190,7 @@ public class Trim extends SubCommand { } } } - final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world), false); + final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world)); TaskManager.getPlatformImplementation().objectTask(chunks, new RunnableVal() { @Override public void run(BlockVector2 value) { queue.regenChunk(value.getX(), value.getZ()); diff --git a/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java b/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java index d856944e0..9c620c148 100644 --- a/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java +++ b/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java @@ -37,6 +37,7 @@ import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotInventory; import com.plotsquared.core.plot.PlotItemStack; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.InventoryUtil; import com.plotsquared.core.util.MainUtil; @@ -44,11 +45,11 @@ import com.plotsquared.core.util.PatternUtil; import com.plotsquared.core.util.Permissions; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.item.ItemTypes; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -61,18 +62,20 @@ import java.util.stream.Collectors; public class ComponentPresetManager { - private static final Logger logger = LoggerFactory.getLogger("P2/" + ComponentPresetManager.class.getSimpleName()); + private static final Logger logger = + LoggerFactory.getLogger("P2/" + ComponentPresetManager.class.getSimpleName()); private final List presets; private final String guiName; private final EconHandler econHandler; private final InventoryUtil inventoryUtil; - @Inject public ComponentPresetManager(@Nullable final EconHandler econHandler, @Nonnull final - InventoryUtil inventoryUtil) { + @Inject public ComponentPresetManager(@Nullable final EconHandler econHandler, + @Nonnull final InventoryUtil inventoryUtil) { this.econHandler = econHandler; this.inventoryUtil = inventoryUtil; - final File file = new File(Objects.requireNonNull(PlotSquared.platform()).getDirectory(), "components.yml"); + final File file = new File(Objects.requireNonNull(PlotSquared.platform()).getDirectory(), + "components.yml"); if (!file.exists()) { boolean created = false; try { @@ -103,13 +106,14 @@ public class ComponentPresetManager { this.guiName = yamlConfiguration.getString("title", "&6Plot Components"); if (yamlConfiguration.contains("presets")) { - this.presets = yamlConfiguration.getMapList("presets").stream().map(o -> (Map) o) - .map(ComponentPreset::deserialize).collect(Collectors.toList()); + this.presets = + yamlConfiguration.getMapList("presets").stream().map(o -> (Map) o) + .map(ComponentPreset::deserialize).collect(Collectors.toList()); } else { - final List defaultPreset = - Collections.singletonList(new ComponentPreset(ClassicPlotManagerComponent.FLOOR, - "##wool", 0, "", "&6D&ai&cs&ec&bo &2F&3l&do&9o&4r", - Arrays.asList("&6Spice up your plot floor"), ItemTypes.YELLOW_WOOL)); + final List defaultPreset = Collections.singletonList( + new ComponentPreset(ClassicPlotManagerComponent.FLOOR, "##wool", 0, "", + "&6D&ai&cs&ec&bo &2F&3l&do&9o&4r", Arrays.asList("&6Spice up your plot floor"), + ItemTypes.YELLOW_WOOL)); yamlConfiguration.set("presets", defaultPreset.stream().map(ComponentPreset::serialize) .collect(Collectors.toList())); try { @@ -139,7 +143,8 @@ public class ComponentPresetManager { } else if (!plot.hasOwner()) { Captions.PLOT_UNOWNED.send(player); return null; - } else if (!plot.isOwner(player.getUUID()) && !plot.getTrusted().contains(player.getUUID())) { + } else if (!plot.isOwner(player.getUUID()) && !plot.getTrusted() + .contains(player.getUUID())) { Captions.NO_PLOT_PERMS.send(player); return null; } @@ -153,71 +158,78 @@ public class ComponentPresetManager { allowedPresets.add(componentPreset); } final int size = (int) Math.ceil((double) allowedPresets.size() / 9.0D); - final PlotInventory plotInventory = new PlotInventory(this.inventoryUtil, player, size, this.guiName) { - @Override public boolean onClick(final int index) { - if (!player.getCurrentPlot().equals(plot)) { - return false; - } - - if (index < 0 || index >= allowedPresets.size()) { - return false; - } - - final ComponentPreset componentPreset = allowedPresets.get(index); - if (componentPreset == null) { - return false; - } - - if (plot.getRunning() > 0) { - Captions.WAIT_FOR_TIMER.send(player); - return false; - } - - final Pattern pattern = PatternUtil.parse(null, componentPreset.getPattern(), false); - if (pattern == null) { - Captions.PRESET_INVALID.send(player); - return false; - } - - if (componentPreset.getCost() > 0.0D && econHandler != null && plot.getArea().useEconomy()) { - if (econHandler.getMoney(player) < componentPreset.getCost()) { - Captions.PRESET_CANNOT_AFFORD.send(player); + final PlotInventory plotInventory = + new PlotInventory(this.inventoryUtil, player, size, this.guiName) { + @Override public boolean onClick(final int index) { + if (!player.getCurrentPlot().equals(plot)) { return false; - } else { - econHandler.withdrawMoney(player, componentPreset.getCost()); - Captions.REMOVED_BALANCE.send(player, componentPreset.getCost() + ""); } - } - BackupManager.backup(player, plot, () -> { - plot.addRunning(); - for (Plot current : plot.getConnectedPlots()) { - current.setComponent(componentPreset.getComponent().name(), pattern); + if (index < 0 || index >= allowedPresets.size()) { + return false; } - MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); - PlotSquared.platform().getGlobalBlockQueue().addEmptyTask(plot::removeRunning); - }); - return false; - } - }; + + final ComponentPreset componentPreset = allowedPresets.get(index); + if (componentPreset == null) { + return false; + } + + if (plot.getRunning() > 0) { + Captions.WAIT_FOR_TIMER.send(player); + return false; + } + + final Pattern pattern = + PatternUtil.parse(null, componentPreset.getPattern(), false); + if (pattern == null) { + Captions.PRESET_INVALID.send(player); + return false; + } + + if (componentPreset.getCost() > 0.0D && econHandler != null && plot.getArea() + .useEconomy()) { + if (econHandler.getMoney(player) < componentPreset.getCost()) { + Captions.PRESET_CANNOT_AFFORD.send(player); + return false; + } else { + econHandler.withdrawMoney(player, componentPreset.getCost()); + Captions.REMOVED_BALANCE.send(player, componentPreset.getCost() + ""); + } + } + + BackupManager.backup(player, plot, () -> { + plot.addRunning(); + QueueCoordinator queue = plot.getArea().getQueue(); + for (Plot current : plot.getConnectedPlots()) { + current.setComponent(componentPreset.getComponent().name(), pattern, + queue); + } + queue.setCompleteTask(plot::removeRunning); + queue.enqueue(); + MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); + }); + return false; + } + }; for (int i = 0; i < allowedPresets.size(); i++) { final ComponentPreset preset = allowedPresets.get(i); final List lore = new ArrayList<>(); - if (preset.getCost() > 0 && this.econHandler != null && plot.getArea().useEconomy()){ - lore.add(Captions.PRESET_LORE_COST.getTranslated().replace("%cost%", - String.format("%.2f", preset.getCost()))); + if (preset.getCost() > 0 && this.econHandler != null && plot.getArea().useEconomy()) { + lore.add(Captions.PRESET_LORE_COST.getTranslated() + .replace("%cost%", String.format("%.2f", preset.getCost()))); } - lore.add(Captions.PRESET_LORE_COMPONENT.getTranslated().replace("%component%", - preset.getComponent().name().toLowerCase())); + lore.add(Captions.PRESET_LORE_COMPONENT.getTranslated() + .replace("%component%", preset.getComponent().name().toLowerCase())); lore.removeIf(String::isEmpty); if (!lore.isEmpty()) { lore.add("&6"); } lore.addAll(preset.getDescription()); - plotInventory.setItem(i, new PlotItemStack(preset.getIcon().getId().replace("minecraft:", ""), - 1, preset.getDisplayName(), lore.toArray(new String[0]))); + plotInventory.setItem(i, + new PlotItemStack(preset.getIcon().getId().replace("minecraft:", ""), 1, + preset.getDisplayName(), lore.toArray(new String[0]))); } return plotInventory; diff --git a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java index 16ded7334..1a06a412d 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java @@ -87,7 +87,7 @@ public class AugmentedUtils { IndependentPlotGenerator generator = area.getGenerator(); // Mask if (queue == null) { - queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world), false); + queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); queue.setChunkObject(chunkObject); } QueueCoordinator primaryMask; diff --git a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java index c6dfe69e3..c1de3c0c5 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java @@ -40,8 +40,9 @@ import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.block.BlockTypes; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.List; import java.util.Optional; @@ -54,98 +55,107 @@ public class ClassicPlotManager extends SquarePlotManager { private final RegionManager regionManager; public ClassicPlotManager(@Nonnull final ClassicPlotWorld classicPlotWorld, - @Nonnull final RegionManager regionManager) { + @Nonnull final RegionManager regionManager) { super(classicPlotWorld, regionManager); this.classicPlotWorld = classicPlotWorld; this.regionManager = regionManager; } - @Override public boolean setComponent(PlotId plotId, String component, Pattern blocks) { + @Override public boolean setComponent(PlotId plotId, String component, Pattern blocks, + @Nullable QueueCoordinator queue) { final Optional componentOptional = ClassicPlotManagerComponent.fromString(component); if (componentOptional.isPresent()) { switch (componentOptional.get()) { case FLOOR: - return setFloor(plotId, blocks); + return setFloor(plotId, blocks, queue); case WALL: - return setWallFilling(plotId, blocks); + return setWallFilling(plotId, blocks, queue); case AIR: - return setAir(plotId, blocks); + return setAir(plotId, blocks, queue); case MAIN: - return setMain(plotId, blocks); + return setMain(plotId, blocks, queue); case MIDDLE: - return setMiddle(plotId, blocks); + return setMiddle(plotId, blocks, queue); case OUTLINE: - return setOutline(plotId, blocks); + return setOutline(plotId, blocks, queue); case BORDER: - return setWall(plotId, blocks); + return setWall(plotId, blocks, queue); case ALL: - return setAll(plotId, blocks); + return setAll(plotId, blocks, queue); } } return false; } - @Override public boolean unClaimPlot(Plot plot, Runnable whenDone) { - setWallFilling(plot.getId(), classicPlotWorld.WALL_FILLING.toPattern()); + @Override public boolean unClaimPlot(Plot plot, @Nullable Runnable whenDone, + @Nullable QueueCoordinator queue) { + setWallFilling(plot.getId(), classicPlotWorld.WALL_FILLING.toPattern(), queue); if (!classicPlotWorld.WALL_BLOCK.isAir() || !classicPlotWorld.WALL_BLOCK .equals(classicPlotWorld.CLAIMED_WALL_BLOCK)) { - setWall(plot.getId(), classicPlotWorld.WALL_BLOCK.toPattern()); + setWall(plot.getId(), classicPlotWorld.WALL_BLOCK.toPattern(), queue); } TaskManager.runTask(whenDone); return true; } - public boolean setFloor(PlotId plotId, Pattern blocks) { + public boolean setFloor(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); - if (plot.isBasePlot()) { + if (plot != null && plot.isBasePlot()) { return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, - classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.PLOT_HEIGHT); + classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.PLOT_HEIGHT, queue); } return false; } - public boolean setAll(PlotId plotId, Pattern blocks) { + public boolean setAll(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); - if (plot.isBasePlot()) { - return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, getWorldHeight()); + if (plot != null && plot.isBasePlot()) { + return this.regionManager + .setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, getWorldHeight(), + queue); } return false; } - public boolean setAir(PlotId plotId, Pattern blocks) { + public boolean setAir(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); - if (plot.isBasePlot()) { + if (plot != null && plot.isBasePlot()) { return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, - classicPlotWorld.PLOT_HEIGHT + 1, getWorldHeight()); + classicPlotWorld.PLOT_HEIGHT + 1, getWorldHeight(), queue); } return false; } - public boolean setMain(PlotId plotId, Pattern blocks) { + public boolean setMain(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); - if (plot.isBasePlot()) { + if (plot == null || plot.isBasePlot()) { return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, - classicPlotWorld.PLOT_HEIGHT - 1); + classicPlotWorld.PLOT_HEIGHT - 1, queue); } return false; } - public boolean setMiddle(PlotId plotId, Pattern blocks) { + public boolean setMiddle(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); - if (!plot.isBasePlot()) { + if (plot == null || !plot.isBasePlot()) { return false; } Location[] corners = plot.getCorners(); - QueueCoordinator queue = classicPlotWorld.getQueue(false); + + boolean enqueue = false; + if (queue == null) { + queue = classicPlotWorld.getQueue(); + enqueue = true; + } int x = MathMan.average(corners[0].getX(), corners[1].getX()); int z = MathMan.average(corners[0].getZ(), corners[1].getZ()); queue.setBlock(x, classicPlotWorld.PLOT_HEIGHT, z, blocks); - return queue.enqueue(); + return !enqueue || queue.enqueue(); } - public boolean setOutline(PlotId plotId, Pattern blocks) { + public boolean setOutline(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { if (classicPlotWorld.ROAD_WIDTH == 0) { return false; } @@ -156,9 +166,18 @@ public class ClassicPlotManager extends SquarePlotManager { return true; } Plot plot = classicPlotWorld.getPlotAbs(plotId); + if (plot == null) { + return false; + } Location bottom = plot.getBottomAbs(); Location top = plot.getExtendedTopAbs(); - QueueCoordinator queue = classicPlotWorld.getQueue(false); + + boolean enqueue = false; + if (queue == null) { + queue = classicPlotWorld.getQueue(); + enqueue = true; + } + int maxY = classicPlotWorld.getPlotManager().getWorldHeight(); if (!plot.getMerged(Direction.NORTH)) { int z = bottom.getZ(); @@ -195,19 +214,19 @@ public class ClassicPlotManager extends SquarePlotManager { } if (plot.isBasePlot()) { for (CuboidRegion region : plot.getRegions()) { - Location pos1 = - Location.at(classicPlotWorld.getWorldName(), region.getMinimumPoint().getX(), - maxY, region.getMinimumPoint().getZ()); - Location pos2 = - Location.at(classicPlotWorld.getWorldName(), region.getMaximumPoint().getX(), - maxY, region.getMaximumPoint().getZ()); + Location pos1 = Location + .at(classicPlotWorld.getWorldName(), region.getMinimumPoint().getX(), maxY, + region.getMinimumPoint().getZ()); + Location pos2 = Location + .at(classicPlotWorld.getWorldName(), region.getMaximumPoint().getX(), maxY, + region.getMaximumPoint().getZ()); queue.setCuboid(pos1, pos2, blocks); } } - return queue.enqueue(); + return !enqueue || queue.enqueue(); } - public boolean setWallFilling(PlotId plotId, Pattern blocks) { + public boolean setWallFilling(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { if (classicPlotWorld.ROAD_WIDTH == 0) { return false; } @@ -218,11 +237,20 @@ public class ClassicPlotManager extends SquarePlotManager { return true; } Plot plot = classicPlotWorld.getPlotAbs(plotId); + if (plot == null) { + return false; + } Location bot = plot.getExtendedBottomAbs() .subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1); - QueueCoordinator queue = classicPlotWorld.getQueue(false); + + boolean enqueue = false; + if (queue == null) { + queue = classicPlotWorld.getQueue(); + enqueue = true; + } + if (!plot.getMerged(Direction.NORTH)) { int z = bot.getZ(); for (int x = bot.getX(); x < top.getX(); x++) { @@ -257,10 +285,10 @@ public class ClassicPlotManager extends SquarePlotManager { } } } - return queue.enqueue(); + return !enqueue || queue.enqueue(); } - public boolean setWall(PlotId plotId, Pattern blocks) { + public boolean setWall(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { if (classicPlotWorld.ROAD_WIDTH == 0) { return false; } @@ -271,11 +299,20 @@ public class ClassicPlotManager extends SquarePlotManager { return true; } Plot plot = classicPlotWorld.getPlotAbs(plotId); + if (plot == null) { + return false; + } Location bot = plot.getExtendedBottomAbs() .subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1); - QueueCoordinator queue = classicPlotWorld.getQueue(false); + + boolean enqueue = false; + if (queue == null) { + enqueue = true; + queue = classicPlotWorld.getQueue(); + } + int y = classicPlotWorld.WALL_HEIGHT + 1; if (!plot.getMerged(Direction.NORTH)) { int z = bot.getZ(); @@ -303,23 +340,29 @@ public class ClassicPlotManager extends SquarePlotManager { queue.setBlock(x, y, z, blocks); } } - return queue.enqueue(); + return !enqueue || queue.enqueue(); } /** * PLOT MERGING. */ - @Override public boolean createRoadEast(Plot plot) { + @Override public boolean createRoadEast(Plot plot, @Nullable QueueCoordinator queue) { Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = pos1.getZ() - 2; int ez = pos2.getZ() + 2; - QueueCoordinator queue = classicPlotWorld.getQueue(false); + + boolean enqueue = false; + if (queue == null) { + queue = classicPlotWorld.getQueue(); + enqueue = true; + } + int maxY = getWorldHeight(); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz + 1), + Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz + 1), Location.at(classicPlotWorld.getWorldName(), ex, maxY, ez - 1), BlockTypes.AIR.getDefaultState()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 0, sz + 1), @@ -328,37 +371,43 @@ public class ClassicPlotManager extends SquarePlotManager { queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1), Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid( - Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, - sz + 1), - Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, - ez - 1), classicPlotWorld.WALL_BLOCK.toPattern()); + queue.setCuboid(Location + .at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, sz + 1), + Location + .at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, ez - 1), + classicPlotWorld.WALL_BLOCK.toPattern()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), ex, 1, sz + 1), Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid( - Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, - sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, - ez - 1), classicPlotWorld.WALL_BLOCK.toPattern()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, - ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); - return queue.enqueue(); + queue.setCuboid(Location + .at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, sz + 1), + Location + .at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, ez - 1), + classicPlotWorld.WALL_BLOCK.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), Location + .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), + classicPlotWorld.ROAD_BLOCK.toPattern()); + return !enqueue || queue.enqueue(); } - @Override public boolean createRoadSouth(Plot plot) { + @Override public boolean createRoadSouth(Plot plot, @Nullable QueueCoordinator queue) { Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId()); int sz = pos2.getZ() + 1; int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; int sx = pos1.getX() - 2; int ex = pos2.getX() + 2; - QueueCoordinator queue = classicPlotWorld.getQueue(false); + + boolean enqueue = false; + if (queue == null) { + queue = classicPlotWorld.getQueue(); + enqueue = true; + } + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, - Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), - Location.at(classicPlotWorld.getWorldName(), ex - 1, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), + Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location + .at(classicPlotWorld.getWorldName(), ex - 1, + classicPlotWorld.getPlotManager().getWorldHeight(), ez), BlockTypes.AIR.getDefaultState()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz), Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez), @@ -366,104 +415,128 @@ public class ClassicPlotManager extends SquarePlotManager { queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz), Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, sz), classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid( - Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, - sz), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, - sz), classicPlotWorld.WALL_BLOCK.toPattern()); + queue.setCuboid(Location + .at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, sz), + Location + .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, sz), + classicPlotWorld.WALL_BLOCK.toPattern()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, ez), Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, ez), classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid( - Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, - ez), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, - ez), classicPlotWorld.WALL_BLOCK.toPattern()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, - ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); - return queue.enqueue(); + queue.setCuboid(Location + .at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, ez), + Location + .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, ez), + classicPlotWorld.WALL_BLOCK.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), Location + .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), + classicPlotWorld.ROAD_BLOCK.toPattern()); + return !enqueue || queue.enqueue(); } - @Override public boolean createRoadSouthEast(Plot plot) { + @Override public boolean createRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { Location pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = pos2.getZ() + 1; int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; - QueueCoordinator queue = classicPlotWorld.getQueue(false); - queue.setCuboid( - Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.ROAD_HEIGHT + 1, - sz + 1), Location.at(classicPlotWorld.getWorldName(), ex - 1, + + boolean enqueue = false; + if (queue == null) { + queue = classicPlotWorld.getQueue(); + enqueue = true; + } + + queue.setCuboid(Location + .at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.ROAD_HEIGHT + 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.getPlotManager().getWorldHeight(), ez - 1), BlockTypes.AIR.getDefaultState()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz + 1), Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez - 1), BlockUtil.get((short) 7, (byte) 0)); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, - ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); - return queue.enqueue(); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), Location + .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), + classicPlotWorld.ROAD_BLOCK.toPattern()); + return !enqueue || queue.enqueue(); } - @Override public boolean removeRoadEast(Plot plot) { + @Override public boolean removeRoadEast(Plot plot, @Nullable QueueCoordinator queue) { Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = pos1.getZ() - 1; int ez = pos2.getZ() + 1; - QueueCoordinator queue = classicPlotWorld.getQueue(false); + + boolean enqueue = false; + if (queue == null) { + queue = classicPlotWorld.getQueue(); + enqueue = true; + } + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), - Location.at(classicPlotWorld.getWorldName(), ex, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), + Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location + .at(classicPlotWorld.getWorldName(), ex, + classicPlotWorld.getPlotManager().getWorldHeight(), ez), BlockTypes.AIR.getDefaultState()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, - ez - 1), classicPlotWorld.MAIN_BLOCK.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1), Location + .at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez - 1), + classicPlotWorld.MAIN_BLOCK.toPattern()); queue.setCuboid( Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz + 1), Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez - 1), classicPlotWorld.TOP_BLOCK.toPattern()); - return queue.enqueue(); + return !enqueue || queue.enqueue(); } - @Override public boolean removeRoadSouth(Plot plot) { + @Override public boolean removeRoadSouth(Plot plot, @Nullable QueueCoordinator queue) { Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId()); int sz = pos2.getZ() + 1; int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; int sx = pos1.getX() - 1; int ex = pos2.getX() + 1; - QueueCoordinator queue = classicPlotWorld.getQueue(false); + + boolean enqueue = false; + if (queue == null) { + queue = classicPlotWorld.getQueue(); + enqueue = true; + } + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), - Location.at(classicPlotWorld.getWorldName(), ex, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), + Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location + .at(classicPlotWorld.getWorldName(), ex, + classicPlotWorld.getPlotManager().getWorldHeight(), ez), BlockTypes.AIR.getDefaultState()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT - 1, - ez), classicPlotWorld.MAIN_BLOCK.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz), Location + .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT - 1, ez), + classicPlotWorld.MAIN_BLOCK.toPattern()); queue.setCuboid( Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.PLOT_HEIGHT, sz), Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT, ez), classicPlotWorld.TOP_BLOCK.toPattern()); - return queue.enqueue(); + return !enqueue || queue.enqueue(); } - @Override public boolean removeRoadSouthEast(Plot plot) { + @Override public boolean removeRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { Location location = getPlotTopLocAbs(plot.getId()); int sx = location.getX() + 1; int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; int sz = location.getZ() + 1; int ez = sz + classicPlotWorld.ROAD_WIDTH - 1; - QueueCoordinator queue = classicPlotWorld.getQueue(false); + + boolean enqueue = false; + if (queue == null) { + queue = classicPlotWorld.getQueue(); + enqueue = true; + } + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), - Location.at(classicPlotWorld.getWorldName(), ex, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), - BlockTypes.AIR.getDefaultState()); + Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location + .at(classicPlotWorld.getWorldName(), ex, + classicPlotWorld.getPlotManager().getWorldHeight(), ez), + BlockTypes.AIR.getDefaultState()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz), Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez), classicPlotWorld.MAIN_BLOCK.toPattern()); @@ -471,7 +544,7 @@ public class ClassicPlotManager extends SquarePlotManager { Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz), Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez), classicPlotWorld.TOP_BLOCK.toPattern()); - return queue.enqueue(); + return !enqueue || queue.enqueue(); } /** @@ -479,44 +552,48 @@ public class ClassicPlotManager extends SquarePlotManager { * * @return false if part of the merge failed, otherwise true if successful. */ - @Override public boolean finishPlotMerge(List plotIds) { + @Override public boolean finishPlotMerge(List plotIds, + @Nullable QueueCoordinator queue) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { for (PlotId plotId : plotIds) { - setWall(plotId, claim.toPattern()); + setWall(plotId, claim.toPattern(), queue); } } if (Settings.General.MERGE_REPLACE_WALL) { final BlockBucket wallBlock = classicPlotWorld.WALL_FILLING; for (PlotId id : plotIds) { - setWallFilling(id, wallBlock.toPattern()); + setWallFilling(id, wallBlock.toPattern(), queue); } } return true; } - @Override public boolean finishPlotUnlink(List plotIds) { + @Override + public boolean finishPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { for (PlotId id : plotIds) { - setWall(id, claim.toPattern()); + setWall(id, claim.toPattern(), queue); } } return true; // return false if unlink has been denied } - @Override public boolean startPlotMerge(List plotIds) { + @Override + public boolean startPlotMerge(List plotIds, @Nullable QueueCoordinator queue) { return true; } - @Override public boolean startPlotUnlink(List plotIds) { + @Override + public boolean startPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { return true; } - @Override public boolean claimPlot(Plot plot) { + @Override public boolean claimPlot(Plot plot, @Nullable QueueCoordinator queue) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { - return setWall(plot.getId(), claim.toPattern()); + return setWall(plot.getId(), claim.toPattern(), queue); } return true; } @@ -534,8 +611,9 @@ public class ClassicPlotManager extends SquarePlotManager { @Override public Location getSignLoc(Plot plot) { plot = plot.getBasePlot(false); final Location bot = plot.getBottomAbs(); - return Location.at(classicPlotWorld.getWorldName(), bot.getX() - 1, - classicPlotWorld.ROAD_HEIGHT + 1, bot.getZ() - 2); + return Location + .at(classicPlotWorld.getWorldName(), bot.getX() - 1, classicPlotWorld.ROAD_HEIGHT + 1, + bot.getZ() - 2); } } diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java index 93351b314..5a847643a 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java @@ -115,7 +115,7 @@ public class HybridPlotManager extends ClassicPlotManager { if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; } - QueueCoordinator queue = hybridPlotWorld.getQueue(false); + QueueCoordinator queue = hybridPlotWorld.getQueue(); createSchemAbs(queue, pos1, pos2, true); queue.enqueue(); return true; @@ -178,7 +178,7 @@ public class HybridPlotManager extends ClassicPlotManager { if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; } - QueueCoordinator queue = hybridPlotWorld.getQueue(false); + QueueCoordinator queue = hybridPlotWorld.getQueue(); createSchemAbs(queue, pos1, pos2, true); queue.enqueue(); return true; @@ -190,7 +190,7 @@ public class HybridPlotManager extends ClassicPlotManager { PlotId id2 = new PlotId(id.x + 1, id.y + 1); Location pos1 = getPlotTopLocAbs(id).add(1, 0, 1).withY(0); Location pos2 = getPlotBottomLocAbs(id2).withY(Math.min(getWorldHeight(), 255)); - QueueCoordinator queue = hybridPlotWorld.getQueue(false); + QueueCoordinator queue = hybridPlotWorld.getQueue(); createSchemAbs(queue, pos1, pos2, true); if (hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { createSchemAbs(queue, pos1, pos2, true); @@ -232,7 +232,7 @@ public class HybridPlotManager extends ClassicPlotManager { } final BiomeType biome = hybridPlotWorld.getPlotBiome(); - final QueueCoordinator queue = hybridPlotWorld.getQueue(false); + final QueueCoordinator queue = hybridPlotWorld.getQueue(); ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { @Override public void run(int[] value) { // If the chunk isn't near the edge and it isn't an augmented world we can just regen the whole chunk diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index ba2576395..cd9e718b7 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -128,7 +128,7 @@ public class HybridUtils { * */ TaskManager.runTaskAsync(() -> { - final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world), false); + final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world)); final BlockVector3 bot = region.getMinimumPoint(); final BlockVector3 top = region.getMaximumPoint(); @@ -520,7 +520,7 @@ public class HybridUtils { public boolean setupRoadSchematic(Plot plot) { final String world = plot.getWorldName(); - final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world), false); + final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world)); Location bot = plot.getBottomAbs().subtract(1, 0, 1); Location top = plot.getTopAbs(); final HybridPlotWorld plotworld = (HybridPlotWorld) plot.getArea(); @@ -607,7 +607,7 @@ public class HybridUtils { z -= plotWorld.ROAD_OFFSET_Z; final int finalX = x; final int finalZ = z; - QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(plotWorld.getWorldName()), false); + QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(plotWorld.getWorldName())); if (id1 == null || id2 == null || id1 != id2) { this.chunkManager.loadChunk(area.getWorldName(), chunk, false).thenRun(() -> { if (id1 != null) { diff --git a/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java index 27e093f1b..d71a47c41 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java @@ -30,13 +30,15 @@ import com.plotsquared.core.location.Location; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotId; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.RegionManager; import com.sk89q.worldedit.regions.CuboidRegion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Iterator; import java.util.Set; @@ -45,18 +47,21 @@ import java.util.Set; */ public abstract class SquarePlotManager extends GridPlotManager { - private static final Logger logger = LoggerFactory.getLogger("P2/" + SquarePlotManager.class.getSimpleName()); + private static final Logger logger = + LoggerFactory.getLogger("P2/" + SquarePlotManager.class.getSimpleName()); private final SquarePlotWorld squarePlotWorld; private final RegionManager regionManager; - public SquarePlotManager(@Nonnull final SquarePlotWorld squarePlotWorld, @Nonnull final RegionManager regionManager) { + public SquarePlotManager(@Nonnull final SquarePlotWorld squarePlotWorld, + @Nonnull final RegionManager regionManager) { super(squarePlotWorld); this.squarePlotWorld = squarePlotWorld; this.regionManager = regionManager; } - @Override public boolean clearPlot(final Plot plot, final Runnable whenDone) { + @Override public boolean clearPlot(final Plot plot, final Runnable whenDone, + @Nullable QueueCoordinator queue) { final Set regions = plot.getRegions(); Runnable run = new Runnable() { @Override public void run() { @@ -230,8 +235,8 @@ public abstract class SquarePlotManager extends GridPlotManager { return plot.getMerged(Direction.NORTHWEST) ? id : null; } } catch (Exception ignored) { - logger.error( "Invalid plot / road width in settings.yml for world: {}", squarePlotWorld - .getWorldName()); + logger.error("Invalid plot / road width in settings.yml for world: {}", + squarePlotWorld.getWorldName()); } return null; } @@ -248,6 +253,7 @@ public abstract class SquarePlotManager extends GridPlotManager { int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH - (int) Math .floor(squarePlotWorld.ROAD_WIDTH / 2); - return Location.at(squarePlotWorld.getWorldName(), x, squarePlotWorld.getMinBuildHeight(), z); + return Location + .at(squarePlotWorld.getWorldName(), x, squarePlotWorld.getMinBuildHeight(), z); } } diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index 22b57da4d..175d1b6be 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -1033,26 +1033,28 @@ public class Plot { ids.add(current.getId()); } this.clearRatings(); + QueueCoordinator queue = null; if (createSign) { this.removeSign(); + queue = getArea().getQueue(); } PlotManager manager = this.area.getPlotManager(); if (createRoad) { - manager.startPlotUnlink(ids); + manager.startPlotUnlink(ids, queue); } if (this.area.getTerrain() != PlotAreaTerrainType.ALL && createRoad) { for (Plot current : plots) { if (current.getMerged(Direction.EAST)) { - manager.createRoadEast(current); + manager.createRoadEast(current, queue); if (current.getMerged(Direction.SOUTH)) { - manager.createRoadSouth(current); + manager.createRoadSouth(current, queue); if (current.getMerged(Direction.SOUTHEAST)) { - manager.createRoadSouthEast(current); + manager.createRoadSouthEast(current, queue); } } } if (current.getMerged(Direction.SOUTH)) { - manager.createRoadSouth(current); + manager.createRoadSouth(current, queue); } } } @@ -1061,14 +1063,14 @@ public class Plot { current.setMerged(merged); } if (createSign) { - TaskManager.runTaskAsync(() -> { + queue.setCompleteTask(() -> TaskManager.runTaskAsync(() -> { for (Plot current : plots) { current.setSign(MainUtil.getName(current.getOwnerAbs())); } - }); + })); } if (createRoad) { - manager.finishPlotUnlink(ids); + manager.finishPlotUnlink(ids, queue); } return true; } @@ -1686,7 +1688,7 @@ public class Plot { */ public void refreshChunks() { QueueCoordinator queue = this.blockQueue - .getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(getWorldName()), false); + .getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(getWorldName())); HashSet chunks = new HashSet<>(); for (CuboidRegion region : Plot.this.getRegions()) { for (int x = region.getMinimumPoint().getX() >> 4; @@ -1710,8 +1712,7 @@ public class Plot { return; } Location location = manager.getSignLoc(this); - QueueCoordinator queue = - this.blockQueue.getNewQueue(worldUtil.getWeWorld(getWorldName()), false); + QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(getWorldName())); queue.setBlock(location.getX(), location.getY(), location.getZ(), BlockTypes.AIR.getDefaultState()); queue.enqueue(); @@ -1852,12 +1853,13 @@ public class Plot { * Sets components such as border, wall, floor. * (components are generator specific) */ - @Deprecated public boolean setComponent(String component, String blocks) { + @Deprecated public boolean setComponent(String component, String blocks, + QueueCoordinator queue) { BlockBucket parsed = ConfigurationUtil.BLOCK_BUCKET.parseString(blocks); if (parsed != null && parsed.isEmpty()) { return false; } - return this.setComponent(component, parsed.toPattern()); + return this.setComponent(component, parsed.toPattern(), queue); } /** @@ -3052,12 +3054,13 @@ public class Plot { * @param blocks Pattern to use the generation * @return True if the component was set successfully */ - public boolean setComponent(String component, Pattern blocks) { + public boolean setComponent(String component, Pattern blocks, + @Nullable QueueCoordinator queue) { PlotComponentSetEvent event = this.eventDispatcher.callComponentSet(this, component, blocks); component = event.getComponent(); blocks = event.getPattern(); - return this.getManager().setComponent(this.getId(), component, blocks); + return this.getManager().setComponent(this.getId(), component, blocks, queue); } public int getDistanceFromOrigin() { diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java index ab49691ca..1c2b8c7a1 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java @@ -172,8 +172,8 @@ public abstract class PlotArea { @Nonnull protected abstract PlotManager createManager(); - public QueueCoordinator getQueue(final boolean autoQueue) { - return this.globalBlockQueue.getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(worldName), autoQueue); + public QueueCoordinator getQueue() { + return this.globalBlockQueue.getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(worldName)); } /** diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java b/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java index 236eeee0f..b42c66e19 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java @@ -28,9 +28,11 @@ package com.plotsquared.core.plot; import com.plotsquared.core.command.Template; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.location.Location; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.FileBytes; import com.sk89q.worldedit.function.pattern.Pattern; +import javax.annotation.Nullable; import java.io.IOException; import java.util.Collections; import java.util.HashSet; @@ -61,11 +63,27 @@ public abstract class PlotManager { /* * Plot clearing (return false if you do not support some method) */ - public abstract boolean clearPlot(Plot plot, Runnable whenDone); + public boolean clearPlot(Plot plot, Runnable whenDone) { + return clearPlot(plot, whenDone, null); + } - public abstract boolean claimPlot(Plot plot); + public boolean claimPlot(Plot plot) { + return claimPlot(plot, null); - public abstract boolean unClaimPlot(Plot plot, Runnable whenDone); + } + + public boolean unClaimPlot(Plot plot, Runnable whenDone) { + return unClaimPlot(plot, whenDone, null); + + } + + public abstract boolean clearPlot(Plot plot, Runnable whenDone, + @Nullable QueueCoordinator queue); + + public abstract boolean claimPlot(Plot plot, @Nullable QueueCoordinator queue); + + public abstract boolean unClaimPlot(Plot plot, Runnable whenDone, + @Nullable QueueCoordinator queue); /** * Retrieves the location of where a sign should be for a plot. @@ -81,31 +99,77 @@ public abstract class PlotManager { */ public abstract String[] getPlotComponents(PlotId plotId); - public abstract boolean setComponent(PlotId plotId, String component, Pattern blocks); + public boolean setComponent(PlotId plotId, String component, Pattern blocks) { + return setComponent(plotId, component, blocks, null); + } + + public abstract boolean setComponent(PlotId plotId, String component, Pattern blocks, + @Nullable QueueCoordinator queue); /* * PLOT MERGING (return false if your generator does not support plot * merging). */ - public abstract boolean createRoadEast(Plot plot); + public boolean createRoadEast(Plot plot) { + return createRoadEast(plot, null); + } - public abstract boolean createRoadSouth(Plot plot); + public boolean createRoadSouth(Plot plot) { + return createRoadSouth(plot, null); + } - public abstract boolean createRoadSouthEast(Plot plot); + public boolean createRoadSouthEast(Plot plot) { + return createRoadSouthEast(plot, null); + } - public abstract boolean removeRoadEast(Plot plot); + public boolean removeRoadEast(Plot plot) { + return removeRoadEast(plot, null); + } - public abstract boolean removeRoadSouth(Plot plot); + public boolean removeRoadSouth(Plot plot) { + return removeRoadSouth(plot, null); + } - public abstract boolean removeRoadSouthEast(Plot plot); + public boolean removeRoadSouthEast(Plot plot) { + return removeRoadSouthEast(plot, null); + } - public abstract boolean startPlotMerge(List plotIds); + public boolean startPlotMerge(List plotIds) { + return startPlotMerge(plotIds, null); + } - public abstract boolean startPlotUnlink(List plotIds); + public boolean startPlotUnlink(List plotIds) { + return startPlotUnlink(plotIds, null); + } - public abstract boolean finishPlotMerge(List plotIds); + public boolean finishPlotMerge(List plotIds) { + return finishPlotMerge(plotIds, null); + } - public abstract boolean finishPlotUnlink(List plotIds); + public boolean finishPlotUnlink(List plotIds) { + return finishPlotUnlink(plotIds, null); + } + + public abstract boolean createRoadEast(Plot plot, @Nullable QueueCoordinator queue); + + public abstract boolean createRoadSouth(Plot plot, @Nullable QueueCoordinator queue); + + public abstract boolean createRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue); + + public abstract boolean removeRoadEast(Plot plot, @Nullable QueueCoordinator queue); + + public abstract boolean removeRoadSouth(Plot plot, @Nullable QueueCoordinator queue); + + public abstract boolean removeRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue); + + public abstract boolean startPlotMerge(List plotIds, @Nullable QueueCoordinator queue); + + public abstract boolean startPlotUnlink(List plotIds, @Nullable QueueCoordinator queue); + + public abstract boolean finishPlotMerge(List plotIds, @Nullable QueueCoordinator queue); + + public abstract boolean finishPlotUnlink(List plotIds, + @Nullable QueueCoordinator queue); public void exportTemplate() throws IOException { HashSet files = new HashSet<>(Collections.singletonList( @@ -124,12 +188,16 @@ public abstract class PlotManager { * @return true if the wall blocks were successfully set */ public boolean regenerateAllPlotWalls() { + return regenerateAllPlotWalls(null); + } + + public boolean regenerateAllPlotWalls(@Nullable QueueCoordinator queue) { boolean success = true; for (Plot plot : plotArea.getPlots()) { if (plot.hasOwner()) { - success &= claimPlot(plot); + success &= claimPlot(plot, queue); } else { - success &= unClaimPlot(plot, null); + success &= unClaimPlot(plot, null, queue); } } return success; diff --git a/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java b/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java index a386022a3..bb36e3219 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java @@ -31,11 +31,13 @@ import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.plot.PlotManager; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.function.pattern.Pattern; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.File; import java.util.List; @@ -61,9 +63,11 @@ public class SinglePlotManager extends PlotManager { return Location.at(plotId.toCommaSeparatedString(), 30000000, 0, 30000000); } - @Override public boolean clearPlot(Plot plot, final Runnable whenDone) { + @Override + public boolean clearPlot(Plot plot, final Runnable whenDone, @Nullable QueueCoordinator queue) { PlotSquared.platform().getSetupUtils().unload(plot.getWorldName(), false); - final File worldFolder = new File(PlotSquared.platform().getWorldContainer(), plot.getWorldName()); + final File worldFolder = + new File(PlotSquared.platform().getWorldContainer(), plot.getWorldName()); TaskManager.getPlatformImplementation().taskAsync(() -> { MainUtil.deleteDirectory(worldFolder); if (whenDone != null) { @@ -73,12 +77,13 @@ public class SinglePlotManager extends PlotManager { return true; } - @Override public boolean claimPlot(Plot plot) { + @Override public boolean claimPlot(Plot plot, @Nullable QueueCoordinator queue) { // TODO return true; } - @Override public boolean unClaimPlot(Plot plot, Runnable whenDone) { + @Override + public boolean unClaimPlot(Plot plot, Runnable whenDone, @Nullable QueueCoordinator queue) { if (whenDone != null) { whenDone.run(); } @@ -93,51 +98,56 @@ public class SinglePlotManager extends PlotManager { return new String[0]; } - @Override public boolean setComponent(PlotId plotId, String component, Pattern blocks) { + @Override public boolean setComponent(PlotId plotId, String component, Pattern blocks, + @Nullable QueueCoordinator queue) { return false; } - @Override public boolean createRoadEast(Plot plot) { + @Override public boolean createRoadEast(Plot plot, @Nullable QueueCoordinator queue) { return false; } - @Override public boolean createRoadSouth(Plot plot) { + @Override public boolean createRoadSouth(Plot plot, @Nullable QueueCoordinator queue) { return false; } - @Override public boolean createRoadSouthEast(Plot plot) { + @Override public boolean createRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { return false; } - @Override public boolean removeRoadEast(Plot plot) { + @Override public boolean removeRoadEast(Plot plot, @Nullable QueueCoordinator queue) { return false; } - @Override public boolean removeRoadSouth(Plot plot) { + @Override public boolean removeRoadSouth(Plot plot, @Nullable QueueCoordinator queue) { return false; } - @Override public boolean removeRoadSouthEast(Plot plot) { + @Override public boolean removeRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { return false; } - @Override public boolean startPlotMerge(List plotIds) { + @Override + public boolean startPlotMerge(List plotIds, @Nullable QueueCoordinator queue) { return false; } - @Override public boolean startPlotUnlink(List plotIds) { + @Override + public boolean startPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { return false; } - @Override public boolean finishPlotMerge(List plotIds) { + @Override + public boolean finishPlotMerge(List plotIds, @Nullable QueueCoordinator queue) { return false; } - @Override public boolean finishPlotUnlink(List plotIds) { + @Override + public boolean finishPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { return false; } - @Override public boolean regenerateAllPlotWalls() { + @Override public boolean regenerateAllPlotWalls(@Nullable QueueCoordinator queue) { return false; } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java index 0e2775b6d..cd18fd0f0 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java @@ -42,13 +42,10 @@ public class GlobalBlockQueue { this.activeQueues = new ConcurrentLinkedDeque<>(); } - public QueueCoordinator getNewQueue(World world, boolean autoQueue) { + public QueueCoordinator getNewQueue(World world) { QueueCoordinator queue = provider.getNewQueue(world); // Auto-inject into the queue PlotSquared.platform().getInjector().injectMembers(queue); - if (autoQueue) { - queue.enqueue(); - } return queue; } diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java index 0a7bc6ccd..2d5b2371e 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java @@ -51,7 +51,7 @@ public abstract class ChunkManager { public static void setChunkInPlotArea(RunnableVal force, RunnableVal add, String world, BlockVector2 loc) { QueueCoordinator queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world), false); + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); if (PlotSquared.get().getPlotAreaManager().isAugmented(world) && PlotSquared.get() .isNonStandardGeneration(world, loc)) { int blockX = loc.getX() << 4; diff --git a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java index e94548d0e..228b62a51 100644 --- a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java @@ -31,7 +31,6 @@ import com.plotsquared.core.location.Location; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotManager; -import com.plotsquared.core.queue.ChunkCoordinatorBuilder; import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.TaskManager; @@ -44,6 +43,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.File; import java.util.Collection; import java.util.HashSet; @@ -169,7 +169,17 @@ public abstract class RegionManager { public boolean setCuboids(final PlotArea area, final Set regions, final Pattern blocks, int minY, int maxY) { - QueueCoordinator queue = area.getQueue(false); + return setCuboids(area, regions, blocks, minY, maxY, null); + } + + + public boolean setCuboids(final PlotArea area, final Set regions, + final Pattern blocks, int minY, int maxY, @Nullable QueueCoordinator queue) { + boolean enqueue = false; + if(queue == null) { + queue = area.getQueue(); + enqueue = true; + } for (CuboidRegion region : regions) { Location pos1 = Location.at(area.getWorldName(), region.getMinimumPoint().getX(), minY, region.getMinimumPoint().getZ()); @@ -177,7 +187,7 @@ public abstract class RegionManager { region.getMaximumPoint().getZ()); queue.setCuboid(pos1, pos2, blocks); } - return queue.enqueue(); + return !enqueue || queue.enqueue(); } /** diff --git a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java index 59da4a707..684a6f345 100644 --- a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java +++ b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java @@ -194,7 +194,7 @@ public abstract class SchematicHandler { return; } try { - final QueueCoordinator queue = plot.getArea().getQueue(false); + final QueueCoordinator queue = plot.getArea().getQueue(); BlockVector3 dimension = schematic.getClipboard().getDimensions(); final int WIDTH = dimension.getX(); final int LENGTH = dimension.getZ(); From 656700b5beaa31e0a0f0c8faa4ae073b3c4873f7 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Sun, 19 Jul 2020 13:12:27 +0100 Subject: [PATCH 27/49] Start reimplementing chunk generation. This would either need to be one WorldEdit operation or (preferable) WorldEdit allows Extents (including EditSessions) into the regenerate adapter method --- .../bukkit/generator/BlockStatePopulator.java | 10 +- .../bukkit/queue/BukkitChunkCoordinator.java | 13 +- .../bukkit/queue/BukkitQueueCoordinator.java | 127 ++++++++++++------ .../bukkit/util/BukkitRegionManager.java | 2 +- .../factory/ChunkCoordinatorFactory.java | 12 +- .../com/plotsquared/core/plot/PlotArea.java | 1 + .../core/queue/BasicQueueCoordinator.java | 37 +++++ .../core/queue/ChunkCoordinatorBuilder.java | 12 +- .../core/queue/DelegateQueueCoordinator.java | 76 +++++++++-- .../core/queue/GlobalBlockQueue.java | 7 +- .../core/queue/QueueCoordinator.java | 6 + 11 files changed, 223 insertions(+), 80 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java index e8cb8d533..935ef3fde 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java @@ -32,11 +32,12 @@ import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.queue.ScopedQueueCoordinator; +import com.sk89q.worldedit.bukkit.BukkitWorld; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.generator.BlockPopulator; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; import java.util.Random; final class BlockStatePopulator extends BlockPopulator { @@ -52,12 +53,11 @@ final class BlockStatePopulator extends BlockPopulator { this.plotAreaManager = plotAreaManager; } - @Override - public void populate(@Nonnull final World world, @Nonnull final Random random, + @Override public void populate(@Nonnull final World world, @Nonnull final Random random, @Nonnull final Chunk source) { if (this.queue == null) { - this.queue = PlotSquared.platform().getGlobalBlockQueue() - .getNewQueue(world.getName()); + this.queue = + PlotSquared.platform().getGlobalBlockQueue().getNewQueue(new BukkitWorld(world)); } final PlotArea area = this.plotAreaManager.getPlotArea(world.getName(), null); if (area == null) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java index ff4d73f8f..41ebeef24 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java @@ -25,6 +25,8 @@ */ package com.plotsquared.bukkit.queue; +import com.google.inject.Inject; +import com.google.inject.assistedinject.Assisted; import com.plotsquared.bukkit.BukkitPlatform; import com.plotsquared.core.queue.ChunkCoordinator; import com.plotsquared.core.util.task.TaskManager; @@ -72,10 +74,13 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { private final AtomicInteger expectedSize; private int batchSize; - private BukkitChunkCoordinator(final long maxIterationTime, final int initialBatchSize, - @Nonnull final Consumer chunkConsumer, @Nonnull final World world, - @Nonnull final Collection requestedChunks, @Nonnull final Runnable whenDone, - @Nonnull final Consumer throwableConsumer) { + @Inject private BukkitChunkCoordinator(@Assisted final long maxIterationTime, + @Assisted final int initialBatchSize, + @Assisted @Nonnull final Consumer chunkConsumer, + @Assisted @Nonnull final World world, + @Assisted @Nonnull final Collection requestedChunks, + @Assisted @Nonnull final Runnable whenDone, + @Assisted @Nonnull final Consumer throwableConsumer) { this.requestedChunks = new LinkedBlockingQueue<>(requestedChunks); this.availableChunks = new LinkedBlockingQueue<>(); this.totalSize = requestedChunks.size(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index 075359e26..3b8e6ce27 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -31,14 +31,18 @@ import com.plotsquared.bukkit.util.BukkitBlockUtil; import com.plotsquared.core.inject.factory.ChunkCoordinatorBuilderFactory; import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory; import com.plotsquared.core.queue.BasicQueueCoordinator; +import com.plotsquared.core.queue.ChunkCoordinator; import com.plotsquared.core.queue.LocalChunk; import com.plotsquared.core.util.BlockUtil; import com.plotsquared.core.util.MainUtil; import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.util.SideEffect; import com.sk89q.worldedit.util.SideEffectSet; import com.sk89q.worldedit.world.World; @@ -59,9 +63,11 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { private final World world; private final SideEffectSet sideEffectSet; + private org.bukkit.World bukkitWorld; @Inject private ChunkCoordinatorBuilderFactory chunkCoordinatorBuilderFactory; @Inject private ChunkCoordinatorFactory chunkCoordinatorFactory; private Runnable whenDone; + private ChunkCoordinator chunkCoordinator; @Inject public BukkitQueueCoordinator(World world) { super(world); @@ -80,17 +86,52 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { } } + @Override public void start() { + chunkCoordinator.start(); + } + + //TODO: implement cancellation + @Override public void cancel() { + chunkCoordinator.cancel(); + } + @Override public boolean enqueue() { + final EditSession editSession; + if (isRegen()) { + editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(world, -1); + world.regenerate(new CuboidRegion( + BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4), + BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15)), + editSession); + } else { + editSession = null; + } Consumer consumer = getChunkConsumer(); if (consumer == null) { consumer = blockVector2 -> { LocalChunk localChunk = getBlockChunks().get(blockVector2); - if (localChunk == null) { + boolean isRegenChunk = + editSession != null && blockVector2.getBlockX() > getRegenStart()[0] + && blockVector2.getBlockZ() > getRegenStart()[1] + && blockVector2.getBlockX() < getRegenEnd()[0] + && blockVector2.getBlockZ() < getRegenEnd()[1]; + if (isRegenChunk) { + for (int layer = 0; layer < 16; layer++) { + for (int y = layer << 4; y < 16; y++) { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + BaseBlock block = + editSession.getFullBlock(BlockVector3.at(x, y, z)); + setWorldBlock(x, y, z, block, blockVector2); + } + } + } + } + return; + } else if (localChunk == null) { throw new NullPointerException( "LocalChunk cannot be null when accessed from ChunkCoordinator"); } - org.bukkit.World bukkitWorld = null; - Chunk chunk = null; int sx = blockVector2.getX() << 4; int sz = blockVector2.getZ() << 4; for (int layer = 0; layer < localChunk.getBaseblocks().length; layer++) { @@ -106,42 +147,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { int x = sx + MainUtil.x_loc[layer][j]; int y = MainUtil.y_loc[layer][j]; int z = sz + MainUtil.z_loc[layer][j]; - try { - world.setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); - } catch (WorldEditException ignored) { - // Fallback to not so nice method - BlockData blockData = BukkitAdapter.adapt(block); - - if (bukkitWorld == null) { - bukkitWorld = Bukkit.getWorld(world.getName()); - } - if (chunk == null) { - chunk = bukkitWorld - .getChunkAt(blockVector2.getX(), blockVector2.getZ()); - } - - Block existing = chunk.getBlock(x, y, z); - final BlockState existingBaseBlock = - BukkitAdapter.adapt(existing.getBlockData()); - if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing - .getBlockData().matches(blockData)) { - continue; - } - - if (existing.getState() instanceof Container) { - ((Container) existing.getState()).getInventory().clear(); - } - - existing.setType(BukkitAdapter.adapt(block.getBlockType()), false); - existing.setBlockData(blockData, false); - if (block.hasNbtData()) { - CompoundTag tag = block.getNbtData(); - StateWrapper sw = new StateWrapper(tag); - - sw.restoreTag(world.getName(), existing.getX(), existing.getY(), - existing.getZ()); - } - } + setWorldBlock(x, y, z, block, blockVector2); } } for (int layer = 0; layer < localChunk.getBaseblocks().length; layer++) { @@ -174,13 +180,48 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { } }; } - chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(world) - .withChunks(getBlockChunks().keySet()).withInitialBatchSize(3).withMaxIterationTime(40) - .withThrowableConsumer(Throwable::printStackTrace).withFinalAction(whenDone) - .withConsumer(consumer); + chunkCoordinator = + chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(world) + .withChunks(getBlockChunks().keySet()).withInitialBatchSize(3) + .withMaxIterationTime(40).withThrowableConsumer(Throwable::printStackTrace) + .withFinalAction(whenDone).withConsumer(consumer).build(); return super.enqueue(); } + private void setWorldBlock(int x, int y, int z, BaseBlock block, BlockVector2 blockVector2) { + try { + world.setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); + } catch (WorldEditException ignored) { + // Fallback to not so nice method + BlockData blockData = BukkitAdapter.adapt(block); + + if (bukkitWorld == null) { + bukkitWorld = Bukkit.getWorld(world.getName()); + } + Chunk chunk = bukkitWorld.getChunkAt(blockVector2.getX(), blockVector2.getZ()); + + Block existing = chunk.getBlock(x, y, z); + final BlockState existingBaseBlock = BukkitAdapter.adapt(existing.getBlockData()); + if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing.getBlockData() + .matches(blockData)) { + return; + } + + if (existing.getState() instanceof Container) { + ((Container) existing.getState()).getInventory().clear(); + } + + existing.setType(BukkitAdapter.adapt(block.getBlockType()), false); + existing.setBlockData(blockData, false); + if (block.hasNbtData()) { + CompoundTag tag = block.getNbtData(); + StateWrapper sw = new StateWrapper(tag); + + sw.restoreTag(world.getName(), existing.getX(), existing.getY(), existing.getZ()); + } + } + } + @Override public void setCompleteTask(Runnable whenDone) { this.whenDone = whenDone; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java index a3e9b4611..a01106c55 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java @@ -293,7 +293,7 @@ public class BukkitRegionManager extends RegionManager { int zzt = zzb + 15; if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) { AugmentedUtils.bypass(ignoreAugment, - () -> queue.regenChunkSafe(chunk.getX(), chunk.getZ())); + () -> queue.regenChunk(chunk.getX(), chunk.getZ())); return; } boolean checkX1 = false; diff --git a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java index 463f58bb1..26b30b0c4 100644 --- a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java +++ b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java @@ -25,7 +25,6 @@ */ package com.plotsquared.core.inject.factory; -import com.google.inject.assistedinject.Assisted; import com.plotsquared.core.queue.ChunkCoordinator; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.world.World; @@ -37,12 +36,9 @@ import java.util.function.Consumer; public interface ChunkCoordinatorFactory { - @Nonnull ChunkCoordinator create(@Assisted final long maxIterationTime, - @Assisted final int initialBatchSize, - @NotNull @Assisted final Consumer chunkConsumer, - @NotNull @Assisted final World world, - @NotNull @Assisted final Collection requestedChunks, - @NotNull @Assisted final Runnable whenDone, - @NotNull @Assisted final Consumer throwableConsumer); + @Nonnull ChunkCoordinator create(final long maxIterationTime, final int initialBatchSize, + @NotNull final Consumer chunkConsumer, @NotNull final World world, + @NotNull final Collection requestedChunks, @NotNull final Runnable whenDone, + @NotNull final Consumer throwableConsumer); } diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java index 620ea670e..7e4ed4a31 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java @@ -27,6 +27,7 @@ package com.plotsquared.core.plot; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.plotsquared.core.PlotSquared; import com.plotsquared.core.collection.QuadMap; import com.plotsquared.core.configuration.CaptionUtility; import com.plotsquared.core.configuration.Captions; diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index 7abc64bc4..f60f43efa 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -49,6 +49,9 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { private int lastZ = Integer.MIN_VALUE; private boolean settingBiomes = false; private boolean settingTiles = false; + private boolean regen = false; + private int[] regenStart; + private int[] regenEnd; private Consumer consumer = null; private GlobalBlockQueue globalBlockQueue; @@ -129,6 +132,40 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return this.settingTiles; } + @Override public void regenChunk(int x, int z) { + regen = true; + // There will never only be one nullified coordinate pair + if (regenStart == null) { + regenStart = new int[]{x, z}; + regenEnd = new int[]{x, z}; + return; + } + if (x < regenStart[0]) { + regenStart[0] = x; + } + if (z < regenStart[1]) { + regenStart[1] = z; + } + if (x > regenEnd[0]) { + regenEnd[0] = x; + } + if (z > regenEnd[1]) { + regenEnd[1] = z; + } + } + + public int[] getRegenStart() { + return regenStart; + } + + public int[] getRegenEnd() { + return regenEnd; + } + + public boolean isRegen() { + return regen; + } + public ConcurrentHashMap getBlockChunks() { return this.blockChunks; } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java index a968e1992..7bb9178d0 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java @@ -4,6 +4,7 @@ import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory; import com.plotsquared.core.location.Location; +import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.world.World; import org.jetbrains.annotations.NotNull; @@ -18,6 +19,7 @@ import java.util.function.Consumer; public class ChunkCoordinatorBuilder { private final List requestedChunks = new LinkedList<>(); + private final ChunkCoordinatorFactory chunkCoordinatorFactory; private Consumer throwableConsumer = Throwable::printStackTrace; private World world; private Consumer chunkConsumer; @@ -25,9 +27,9 @@ public class ChunkCoordinatorBuilder { }; private long maxIterationTime = 60; // A little over 1 tick; private int initialBatchSize = 4; - private final ChunkCoordinatorFactory chunkCoordinatorFactory; - @Inject public ChunkCoordinatorBuilder(@Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory) { + @Inject + public ChunkCoordinatorBuilder(@Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory) { this.chunkCoordinatorFactory = chunkCoordinatorFactory; } @@ -105,9 +107,9 @@ public class ChunkCoordinatorBuilder { Preconditions.checkNotNull(this.chunkConsumer, "No chunk consumer was supplied"); Preconditions.checkNotNull(this.whenDone, "No final action was supplied"); Preconditions.checkNotNull(this.throwableConsumer, "No throwable consumer was supplied"); - return chunkCoordinatorFactory.create(this.maxIterationTime, this.initialBatchSize, - this.chunkConsumer, this.world, this.requestedChunks, this.whenDone, - this.throwableConsumer); + return chunkCoordinatorFactory + .create(this.maxIterationTime, this.initialBatchSize, this.chunkConsumer, this.world, + this.requestedChunks, this.whenDone, this.throwableConsumer); } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index 76cffc3be..d63773ddd 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -65,43 +65,79 @@ public class DelegateQueueCoordinator extends QueueCoordinator { } @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { - return parent.setBlock(x, y, z, pattern); + if (parent != null) { + return parent.setBlock(x, y, z, pattern); + } + return false; } @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { - return parent.setBlock(x, y, z, id); + if (parent != null) { + return parent.setBlock(x, y, z, id); + } + return false; } @Override public boolean setBlock(int x, int y, int z, BlockState id) { - return parent.setBlock(x, y, z, id); + if (parent != null) { + return parent.setBlock(x, y, z, id); + } + return false; } @Override public BlockState getBlock(int x, int y, int z) { - return parent.getBlock(x, y, z); + if (parent != null) { + return parent.getBlock(x, y, z); + } + return null; } @Override public boolean setBiome(int x, int z, BiomeType biome) { - return parent.setBiome(x, z, biome); + if (parent != null) { + return parent.setBiome(x, z, biome); + } + return false; } @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { - return parent.setBiome(x, y, z, biome); + if (parent != null) { + return parent.setBiome(x, y, z, biome); + } + return false; } @Override public boolean isSettingBiomes() { - return parent.isSettingBiomes(); + if (parent != null) { + return parent.isSettingBiomes(); + } + return false; + } + + @Override public void regenChunk(int x, int z) { + if (parent != null) { + parent.regenChunk(x, z); + } } @Override public World getWorld() { - return parent.getWorld(); + if (parent != null) { + return parent.getWorld(); + } + return null; } @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { - return parent.setTile(x, y, z, tag); + if (parent != null) { + return parent.setTile(x, y, z, tag); + } + return false; } @Override public boolean isSettingTiles() { - return parent.isSettingTiles(); + if (parent != null) { + return parent.isSettingTiles(); + } + return false; } @Override public boolean enqueue() { @@ -111,11 +147,27 @@ public class DelegateQueueCoordinator extends QueueCoordinator { return false; } + @Override public void start() { + if (parent != null) { + parent.start(); + } + } + + @Override public void cancel() { + if (parent != null) { + parent.cancel(); + } + } + @Override public void setCompleteTask(Runnable whenDone) { - parent.setCompleteTask(whenDone); + if (parent != null) { + parent.setCompleteTask(whenDone); + } } @Override public void setChunkConsumer(Consumer consumer) { - parent.setChunkConsumer(consumer); + if (parent != null) { + parent.setChunkConsumer(consumer); + } } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java index cd18fd0f0..e5d69406e 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java @@ -58,20 +58,23 @@ public class GlobalBlockQueue { } /** - * TODO Documentation needed. + * Place an instance of {@link QueueCoordinator} into a list incase access is needed + * and then start it. * - * @param queue todo + * @param queue {@link QueueCoordinator} instance to start. * @return true if added to queue, false otherwise */ public boolean enqueue(QueueCoordinator queue) { boolean success = false; if (queue.size() > 0 && !activeQueues.contains(queue)) { success = activeQueues.add(queue); + queue.start(); } return success; } public void dequeue(QueueCoordinator queue) { + queue.cancel(); activeQueues.remove(queue); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index 91194e25f..e1161ab20 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -108,6 +108,8 @@ public abstract class QueueCoordinator { public abstract boolean isSettingBiomes(); + public abstract void regenChunk(int x, int z); + public abstract World getWorld(); public final void setModified() { @@ -118,6 +120,10 @@ public abstract class QueueCoordinator { return blockQueue.enqueue(this); } + public abstract void start(); + + public abstract void cancel(); + public abstract void setCompleteTask(Runnable whenDone); public abstract void setChunkConsumer(Consumer consumer); From 87a8ff742fe5c542fac80b8ce20c93563ec70bd2 Mon Sep 17 00:00:00 2001 From: N0tMyFaultOG Date: Sun, 19 Jul 2020 14:16:13 +0200 Subject: [PATCH 28/49] 5.13.1 --- Bukkit/pom.xml | 2 +- build.gradle | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index bba553386..26f8a6607 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -21,7 +21,7 @@ com.plotsquared PlotSquared-Core - 5.13.0 + 5.13.1 compile diff --git a/build.gradle b/build.gradle index bfd4ef86f..40639372c 100644 --- a/build.gradle +++ b/build.gradle @@ -30,7 +30,7 @@ ext { git = Grgit.open(dir: new File(rootDir.toString() + "/.git")) } -def ver = "5.13.0" +def ver = "5.13.1" def versuffix = "" ext { if (project.hasProperty("versionsuffix")) { From d24c89405a8513e2cef321220b180d6780d322be Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Sun, 19 Jul 2020 14:17:38 +0100 Subject: [PATCH 29/49] Switch to using a Clipboard for regen in preparation for WE changes --- .../bukkit/queue/BukkitQueueCoordinator.java | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index 3b8e6ce27..db140051d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -36,13 +36,14 @@ import com.plotsquared.core.queue.LocalChunk; import com.plotsquared.core.util.BlockUtil; import com.plotsquared.core.util.MainUtil; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; +import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.SideEffect; import com.sk89q.worldedit.util.SideEffectSet; import com.sk89q.worldedit.world.World; @@ -96,22 +97,22 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { } @Override public boolean enqueue() { - final EditSession editSession; + final Clipboard regenClipboard; if (isRegen()) { - editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(world, -1); - world.regenerate(new CuboidRegion( - BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4), - BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15)), - editSession); + Region region = new CuboidRegion( + BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4), + BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15)); + regenClipboard = new BlockArrayClipboard(region); + world.regenerate(region, regenClipboard); } else { - editSession = null; + regenClipboard = null; } Consumer consumer = getChunkConsumer(); if (consumer == null) { consumer = blockVector2 -> { LocalChunk localChunk = getBlockChunks().get(blockVector2); boolean isRegenChunk = - editSession != null && blockVector2.getBlockX() > getRegenStart()[0] + regenClipboard != null && blockVector2.getBlockX() > getRegenStart()[0] && blockVector2.getBlockZ() > getRegenStart()[1] && blockVector2.getBlockX() < getRegenEnd()[0] && blockVector2.getBlockZ() < getRegenEnd()[1]; @@ -121,7 +122,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { BaseBlock block = - editSession.getFullBlock(BlockVector3.at(x, y, z)); + regenClipboard.getFullBlock(BlockVector3.at(x, y, z)); setWorldBlock(x, y, z, block, blockVector2); } } From 21693e344cf2b9b3443df904d2d50af9f2596989 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Sun, 19 Jul 2020 14:37:42 +0100 Subject: [PATCH 30/49] Switch from MainUtil --- .../bukkit/queue/BukkitQueueCoordinator.java | 14 +++++++------- .../bukkit/util/BukkitRegionManager.java | 2 +- .../com/plotsquared/core/queue/LocalChunk.java | 9 +++++---- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index db140051d..cdb8a7b5e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -34,7 +34,7 @@ import com.plotsquared.core.queue.BasicQueueCoordinator; import com.plotsquared.core.queue.ChunkCoordinator; import com.plotsquared.core.queue.LocalChunk; import com.plotsquared.core.util.BlockUtil; -import com.plotsquared.core.util.MainUtil; +import com.plotsquared.core.util.ChunkUtil; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -145,9 +145,9 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { continue; } BaseBlock block = blocksLayer[j]; - int x = sx + MainUtil.x_loc[layer][j]; - int y = MainUtil.y_loc[layer][j]; - int z = sz + MainUtil.z_loc[layer][j]; + int x = sx + ChunkUtil.getX(j); + int y = ChunkUtil.getY(layer, j); + int z = sz + ChunkUtil.getZ(j); setWorldBlock(x, y, z, block, blockVector2); } } @@ -161,9 +161,9 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { continue; } BiomeType biome = biomesLayer[j]; - int x = sx + MainUtil.x_loc[layer][j]; - int y = MainUtil.y_loc[layer][j]; - int z = sz + MainUtil.z_loc[layer][j]; + int x = sx + ChunkUtil.getX(j); + int y = ChunkUtil.getY(layer, j); + int z = sz + ChunkUtil.getZ(j); world.setBiome(BlockVector3.at(x, y, z), biome); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java index ca1caa09e..795a4cab9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java @@ -473,7 +473,7 @@ public class BukkitRegionManager extends RegionManager { queue.setChunkConsumer(blockVector2 -> { final int cx = blockVector2.getX() << 4; final int cz = blockVector2.getZ() << 4; - MainUtil + WorldUtil .setBiome(world, Math.max(minX, cx), Math.max(minZ, cz), Math.min(maxX, cx + 15), Math.min(maxZ, cz + 15), biome); worldUtil.refreshChunk(blockVector2.getBlockX(), blockVector2.getBlockZ(), world); diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java index af6a30fe3..176e4f083 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java @@ -1,5 +1,6 @@ package com.plotsquared.core.queue; +import com.plotsquared.core.util.ChunkUtil; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MathMan; import com.sk89q.jnbt.CompoundTag; @@ -51,8 +52,8 @@ public class LocalChunk { } public void setBiome(final int x, final int y, final int z, final BiomeType biomeType) { - final int i = MainUtil.CACHE_I[y][x][z]; - final int j = MainUtil.CACHE_J[y][x][z]; + final int i = y >> 4; + final int j = ChunkUtil.getJ(x, y, z); BiomeType[] array = this.biomes[i]; if (array == null) { array = this.biomes[i] = new BiomeType[4096]; @@ -65,8 +66,8 @@ public class LocalChunk { } public void setBlock(final int x, final int y, final int z, final BaseBlock baseBlock) { - final int i = MainUtil.CACHE_I[y][x][z]; - final int j = MainUtil.CACHE_J[y][x][z]; + final int i = y >> 4; + final int j = ChunkUtil.getJ(x, y, z); BaseBlock[] array = baseblocks[i]; if (array == null) { array = (baseblocks[i] = new BaseBlock[4096]); From 94b6a27cf3131eb0cca68fbe96513bbaed9b2342 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Sun, 19 Jul 2020 16:02:30 +0100 Subject: [PATCH 31/49] add missing license headers --- .../core/queue/ChunkCoordinator.java | 25 +++++++++++++++++++ .../core/queue/ChunkCoordinatorBuilder.java | 25 +++++++++++++++++++ .../plotsquared/core/queue/LocalChunk.java | 25 +++++++++++++++++++ .../com/plotsquared/core/util/ChunkUtil.java | 25 +++++++++++++++++++ 4 files changed, 100 insertions(+) diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java index d596d27dc..ca89c5579 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java @@ -1,3 +1,28 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ package com.plotsquared.core.queue; import com.plotsquared.core.util.task.PlotSquaredTask; diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java index 7bb9178d0..cbfab298a 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java @@ -1,3 +1,28 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ package com.plotsquared.core.queue; import com.google.common.base.Preconditions; diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java index 176e4f083..e69c4f0d5 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java @@ -1,3 +1,28 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ package com.plotsquared.core.queue; import com.plotsquared.core.util.ChunkUtil; diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java index 3e89c630a..6c1a1415d 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java @@ -1,3 +1,28 @@ +/* + * _____ _ _ _____ _ + * | __ \| | | | / ____| | | + * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | + * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | + * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | + * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| + * | | + * |_| + * PlotSquared plot management system for Minecraft + * Copyright (C) 2020 IntellectualSites + * + * 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, see . + */ package com.plotsquared.core.util; import lombok.experimental.UtilityClass; From 207e56969ba090a229343c627486927aeeb39a0a Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Sun, 19 Jul 2020 16:03:40 +0100 Subject: [PATCH 32/49] Remove ChunkManager#chunkTask --- .../core/generator/HybridPlotManager.java | 70 +++++---- .../core/generator/HybridUtils.java | 138 +++++++++--------- .../core/queue/ChunkCoordinatorBuilder.java | 1 - .../plotsquared/core/util/ChunkManager.java | 95 +----------- .../com/plotsquared/core/util/ChunkUtil.java | 20 +++ .../core/util/SchematicHandler.java | 91 ++++++------ 6 files changed, 174 insertions(+), 241 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java index 67bf3c011..3955a00ee 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java @@ -35,13 +35,12 @@ import com.plotsquared.core.plot.PlotAreaTerrainType; import com.plotsquared.core.plot.PlotAreaType; import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.queue.QueueCoordinator; -import com.plotsquared.core.util.ChunkManager; +import com.plotsquared.core.util.ChunkUtil; import com.plotsquared.core.util.FileBytes; import com.plotsquared.core.util.FileUtils; import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.WorldUtil; -import com.plotsquared.core.util.task.RunnableVal; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; @@ -228,8 +227,8 @@ public class HybridPlotManager extends ClassicPlotManager { } } final String world = hybridPlotWorld.getWorldName(); - Location pos1 = plot.getBottomAbs(); - Location pos2 = plot.getExtendedTopAbs(); + final Location pos1 = plot.getBottomAbs(); + final Location pos2 = plot.getExtendedTopAbs(); // If augmented final boolean canRegen = (hybridPlotWorld.getType() == PlotAreaType.AUGMENTED) && (hybridPlotWorld.getTerrain() @@ -248,39 +247,38 @@ public class HybridPlotManager extends ClassicPlotManager { final BiomeType biome = hybridPlotWorld.getPlotBiome(); final QueueCoordinator queue = hybridPlotWorld.getQueue(); - ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { - @Override public void run(int[] value) { - // If the chunk isn't near the edge and it isn't an augmented world we can just regen the whole chunk - if (canRegen && (value[6] == 0)) { - queue.regenChunk(value[0], value[1]); - return; - } - /* Otherwise we need to set each component, as we don't want to regenerate the road or other plots that share the same chunk.*/ - // Set the biome - WorldUtil.setBiome(world, value[2], value[3], value[4], value[5], biome); - // These two locations are for each component (e.g. bedrock, main block, floor, air) - Location bot = Location.at(world, value[2], 0, value[3]); - Location top = Location.at(world, value[4], 1, value[5]); - queue.setCuboid(bot, top, bedrock); - // Each component has a different layer - bot = bot.withY(1); - top = top.withY(hybridPlotWorld.PLOT_HEIGHT); - queue.setCuboid(bot, top, filling); - bot = bot.withY(hybridPlotWorld.PLOT_HEIGHT); - top = top.withY(hybridPlotWorld.PLOT_HEIGHT + 1); - queue.setCuboid(bot, top, plotfloor); - bot = bot.withY(hybridPlotWorld.PLOT_HEIGHT + 1); - top = top.withY(getWorldHeight()); - queue.setCuboid(bot, top, air); - // And finally set the schematic, the y value is unimportant for this function - pastePlotSchematic(queue, bot, top); + queue.setChunkConsumer(blockVector2 -> { + // If the chunk isn't near the edge and it isn't an augmented world we can just regen the whole chunk + if (canRegen && ChunkUtil.isWholeChunk(pos1, pos2, blockVector2)) { + queue.regenChunk(blockVector2.getX(), blockVector2.getZ()); + return; } - }, () -> { - // And notify whatever called this when plot clearing is done - queue.setCompleteTask(whenDone); - queue.enqueue(); - }, 10); - return true; + /* Otherwise we need to set each component, as we don't want to regenerate the road or other plots that share the same chunk.*/ + // Set the biome + int x1 = Math.max(pos1.getX(), blockVector2.getX() << 4); + int z1 = Math.max(pos1.getZ(), blockVector2.getZ() << 4); + int x2 = Math.min(pos2.getX(), blockVector2.getX() << 4); + int z2 = Math.min(pos2.getZ(), blockVector2.getZ() << 4); + WorldUtil.setBiome(world, x1, z1, x2, z2, biome); + // These two locations are for each component (e.g. bedrock, main block, floor, air) + Location bot = Location.at(world, x1, 0, z1); + Location top = Location.at(world, x2, 1, z2); + queue.setCuboid(bot, top, bedrock); + // Each component has a different layer + bot = bot.withY(1); + top = top.withY(hybridPlotWorld.PLOT_HEIGHT); + queue.setCuboid(bot, top, filling); + bot = bot.withY(hybridPlotWorld.PLOT_HEIGHT); + top = top.withY(hybridPlotWorld.PLOT_HEIGHT + 1); + queue.setCuboid(bot, top, plotfloor); + bot = bot.withY(hybridPlotWorld.PLOT_HEIGHT + 1); + top = top.withY(getWorldHeight()); + queue.setCuboid(bot, top, air); + // And finally set the schematic, the y value is unimportant for this function + pastePlotSchematic(queue, bot, top); + }); + queue.setCompleteTask(whenDone); + return queue.enqueue(); } public void pastePlotSchematic(QueueCoordinator queue, Location bottom, Location top) { diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index e89e221c2..c54e494aa 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -64,8 +64,8 @@ import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; import java.io.File; import java.util.ArrayDeque; import java.util.ArrayList; @@ -80,7 +80,8 @@ import java.util.concurrent.atomic.AtomicInteger; public class HybridUtils { - private static final Logger logger = LoggerFactory.getLogger("P2/" + HybridUtils.class.getSimpleName()); + private static final Logger logger = + LoggerFactory.getLogger("P2/" + HybridUtils.class.getSimpleName()); public static HybridUtils manager; public static Set regions; @@ -98,7 +99,8 @@ public class HybridUtils { @Inject public HybridUtils(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final ChunkManager chunkManager, @Nonnull final GlobalBlockQueue blockQueue, - @Nonnull final WorldUtil worldUtil, @Nonnull final RegionManager regionManager, @Nonnull final SchematicHandler schematicHandler) { + @Nonnull final WorldUtil worldUtil, @Nonnull final RegionManager regionManager, + @Nonnull final SchematicHandler schematicHandler) { this.plotAreaManager = plotAreaManager; this.chunkManager = chunkManager; this.blockQueue = blockQueue; @@ -127,8 +129,6 @@ public class HybridUtils { * */ TaskManager.runTaskAsync(() -> { - final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world)); - final BlockVector3 bot = region.getMinimumPoint(); final BlockVector3 top = region.getMaximumPoint(); @@ -160,6 +160,55 @@ public class HybridUtils { System.gc(); System.gc(); + QueueCoordinator queue = area.getQueue(); + + queue.setChunkConsumer(blockVector2 -> { + int X = blockVector2.getX(); + int Z = blockVector2.getZ(); + int minX; + if (X == cbx) { + minX = bx & 15; + } else { + minX = 0; + } + int minZ; + if (Z == cbz) { + minZ = bz & 15; + } else { + minZ = 0; + } + int maxX; + if (X == ctx) { + maxX = tx & 15; + } else { + maxX = 16; + } + int maxZ; + if (Z == ctz) { + maxZ = tz & 15; + } else { + maxZ = 16; + } + + int chunkBlockX = X << 4; + int chunkBlockZ = Z << 4; + + int xb = chunkBlockX - bx; + int zb = chunkBlockZ - bz; + for (int x = minX; x <= maxX; x++) { + int xx = chunkBlockX + x; + for (int z = minZ; z <= maxZ; z++) { + int zz = chunkBlockZ + z; + for (int y = 0; y < 256; y++) { + BlockState block = queue.getBlock(xx, y, zz); + int xr = xb + x; + int zr = zb + z; + newBlocks[y][xr][zr] = block; + } + } + } + }); + final Runnable run = () -> TaskManager.runTaskAsync(() -> { int size = width * length; int[] changes = new int[size]; @@ -248,57 +297,8 @@ public class HybridUtils { whenDone.value = analysis; whenDone.run(); }); - System.gc(); - Location botLoc = Location.at(world, bot.getX(), bot.getY(), bot.getZ()); - Location topLoc = Location.at(world, top.getX(), top.getY(), top.getZ()); - ChunkManager.chunkTask(botLoc, topLoc, new RunnableVal() { - @Override public void run(int[] value) { - int X = value[0]; - int Z = value[1]; - int minX; - if (X == cbx) { - minX = bx & 15; - } else { - minX = 0; - } - int minZ; - if (Z == cbz) { - minZ = bz & 15; - } else { - minZ = 0; - } - int maxX; - if (X == ctx) { - maxX = tx & 15; - } else { - maxX = 16; - } - int maxZ; - 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++) { - BlockState block = queue.getBlock(xx, y, zz); - int xr = xb + x; - int zr = zb + z; - newBlocks[y][xr][zr] = block; - } - } - } - } - }, () -> TaskManager.runTaskAsync(run), 5); + queue.setCompleteTask(run); + queue.enqueue(); }); } @@ -466,9 +466,11 @@ public class HybridUtils { BlockVector2 loc = iterator.next(); iterator.remove(); if (Settings.DEBUG) { - logger.info("[P2] Updating .mcr: {}, {} (approx 1024 chunks)", - loc.getX(), loc.getZ()); - logger.info("[P2] - Remaining: {}", HybridUtils.regions.size()); + logger + .info("[P2] Updating .mcr: {}, {} (approx 1024 chunks)", + loc.getX(), loc.getZ()); + logger.info("[P2] - Remaining: {}", + HybridUtils.regions.size()); } chunks.addAll(getChunks(loc)); System.gc(); @@ -482,8 +484,7 @@ public class HybridUtils { .isEmpty()) { final BlockVector2 chunk = iterator.next(); iterator.remove(); - boolean regenedRoads = - regenerateRoad(area, chunk, extend); + boolean regenedRoads = regenerateRoad(area, chunk, extend); if (!regenedRoads && Settings.DEBUG) { logger.info("[P2] Failed to regenerate road"); } @@ -496,13 +497,15 @@ public class HybridUtils { Iterator iterator = HybridUtils.regions.iterator(); BlockVector2 loc = iterator.next(); iterator.remove(); - logger.error("[P2] Error! Could not update '{}/region/r.{}.{}.mca' (Corrupt chunk?)", + logger.error( + "[P2] Error! Could not update '{}/region/r.{}.{}.mca' (Corrupt chunk?)", area.getWorldHash(), loc.getX(), loc.getZ()); int sx = loc.getX() << 5; int sz = loc.getZ() << 5; for (int x = sx; x < sx + 32; x++) { for (int z = sz; z < sz + 32; z++) { - chunkManager.unloadChunk(area.getWorldName(), BlockVector2.at(x, z), + chunkManager + .unloadChunk(area.getWorldName(), BlockVector2.at(x, z), true); } } @@ -544,7 +547,8 @@ public class HybridUtils { this.schematicHandler.getCompoundTag(world, sideRoad, new RunnableVal() { @Override public void run(CompoundTag value) { schematicHandler.save(value, dir + "sideroad.schem"); - schematicHandler.getCompoundTag(world, intersection, new RunnableVal() { + schematicHandler + .getCompoundTag(world, intersection, new RunnableVal() { @Override public void run(CompoundTag value) { schematicHandler.save(value, dir + "intersection.schem"); plotworld.ROAD_SCHEMATIC_ENABLED = true; @@ -604,7 +608,8 @@ public class HybridUtils { z -= plotWorld.ROAD_OFFSET_Z; final int finalX = x; final int finalZ = z; - QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(plotWorld.getWorldName())); + QueueCoordinator queue = + this.blockQueue.getNewQueue(worldUtil.getWeWorld(plotWorld.getWorldName())); if (id1 == null || id2 == null || id1 != id2) { this.chunkManager.loadChunk(area.getWorldName(), chunk, false).thenRun(() -> { if (id1 != null) { @@ -643,7 +648,8 @@ public class HybridUtils { } if (condition) { BaseBlock[] blocks = plotWorld.G_SCH.get(MathMan.pair(absX, absZ)); - int minY = Settings.Schematics.PASTE_ROAD_ON_TOP ? plotWorld.SCHEM_Y : 1; + int minY = + Settings.Schematics.PASTE_ROAD_ON_TOP ? plotWorld.SCHEM_Y : 1; int maxY = Math.max(extend, blocks.length); for (int y = 0; y < maxY; y++) { if (y > blocks.length - 1) { diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java index cbfab298a..861ccc8ed 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java @@ -29,7 +29,6 @@ import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory; import com.plotsquared.core.location.Location; -import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.world.World; import org.jetbrains.annotations.NotNull; diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java index 2d5b2371e..e2e5c36e9 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java @@ -31,12 +31,8 @@ import com.plotsquared.core.plot.Plot; import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.task.RunnableVal; -import com.plotsquared.core.util.task.TaskManager; -import com.plotsquared.core.util.task.TaskTime; import com.sk89q.worldedit.math.BlockVector2; -import com.sk89q.worldedit.regions.CuboidRegion; -import java.util.ArrayList; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; @@ -50,8 +46,8 @@ public abstract class ChunkManager { public static void setChunkInPlotArea(RunnableVal force, RunnableVal add, String world, BlockVector2 loc) { - QueueCoordinator queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); + QueueCoordinator queue = PlotSquared.platform().getGlobalBlockQueue() + .getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); if (PlotSquared.get().getPlotAreaManager().isAugmented(world) && PlotSquared.get() .isNonStandardGeneration(world, loc)) { int blockX = loc.getX() << 4; @@ -99,93 +95,10 @@ public abstract class ChunkManager { return false; } - public static void chunkTask(final Plot plot, final RunnableVal task, - final Runnable whenDone, final int allocate) { - final ArrayList regions = new ArrayList<>(plot.getRegions()); - Runnable smallTask = new Runnable() { - @Override public void run() { - if (regions.isEmpty()) { - TaskManager.runTask(whenDone); - return; - } - CuboidRegion value = regions.remove(0); - Location pos1 = Location.at(plot.getWorldName(), value.getMinimumPoint().getX(), 0, - value.getMinimumPoint().getZ()); - Location pos2 = Location.at(plot.getWorldName(), value.getMaximumPoint().getX(), 0, - value.getMaximumPoint().getZ()); - chunkTask(pos1, pos2, task, this, allocate); - } - }; - smallTask.run(); - } - - /** - * The int[] will be in the form: [chunkX, chunkZ, pos1x, pos1z, pos2x, pos2z, isEdge] and will represent the bottom and top parts of the chunk - * - * @param pos1 - * @param pos2 - * @param task - * @param whenDone - */ - public static void chunkTask(Location pos1, Location pos2, final RunnableVal task, - final Runnable whenDone, final int allocate) { - 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 ArrayList chunks = new ArrayList<>(); - - for (int x = bcx; x <= tcx; x++) { - for (int z = bcz; z <= tcz; z++) { - chunks.add(BlockVector2.at(x, z)); - } - } - TaskManager.runTask(new Runnable() { - @Override public void run() { - long start = System.currentTimeMillis(); - while (!chunks.isEmpty() && ((System.currentTimeMillis() - start) < allocate)) { - BlockVector2 chunk = chunks.remove(0); - task.value = new int[7]; - task.value[0] = chunk.getX(); - task.value[1] = chunk.getZ(); - task.value[2] = task.value[0] << 4; - task.value[3] = task.value[1] << 4; - task.value[4] = task.value[2] + 15; - task.value[5] = task.value[3] + 15; - if (task.value[0] == bcx) { - task.value[2] = p1x; - task.value[6] = 1; - } - if (task.value[0] == tcx) { - task.value[4] = p2x; - task.value[6] = 1; - } - if (task.value[1] == bcz) { - task.value[3] = p1z; - task.value[6] = 1; - } - if (task.value[1] == tcz) { - task.value[5] = p2z; - task.value[6] = 1; - } - task.run(); - } - if (!chunks.isEmpty()) { - TaskManager.runTaskLater(this, TaskTime.ticks(1L)); - } else { - TaskManager.runTask(whenDone); - } - } - }); - } - + @Deprecated public abstract CompletableFuture loadChunk(String world, BlockVector2 loc, boolean force); - public abstract void unloadChunk(String world, BlockVector2 loc, boolean save); + @Deprecated public abstract void unloadChunk(String world, BlockVector2 loc, boolean save); public Plot hasPlot(String world, BlockVector2 chunk) { int x1 = chunk.getX() << 4; diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java index 6c1a1415d..fc73c7ba1 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java @@ -25,6 +25,8 @@ */ package com.plotsquared.core.util; +import com.plotsquared.core.location.Location; +import com.sk89q.worldedit.math.BlockVector2; import lombok.experimental.UtilityClass; import org.jetbrains.annotations.Range; @@ -115,4 +117,22 @@ public class ChunkUtil { public static int getZ(@Range(from = 0, to = 4095) int j) { return z_loc[j]; } + + /** + * Returns true if the region pos1 -> pos2 contains the chunk + * + * @param pos1 Region minimum point + * @param pos2 Region maximum point + * @param chunk BlockVector2 of chunk coordinates + * @return true if the region pos1 -> pos2 contains the chunk + */ + public static boolean isWholeChunk(Location pos1, Location pos2, BlockVector2 chunk) { + int x1 = pos1.getX(); + int z1 = pos1.getZ(); + int x2 = pos2.getX(); + int z2 = pos2.getZ(); + int cx = chunk.getX() << 4; + int cz = chunk.getZ() << 4; + return cx > x1 && cz > z1 && cx < x2 && cz < z2; + } } diff --git a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java index 2b570c9ed..0381945fa 100644 --- a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java +++ b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java @@ -224,7 +224,8 @@ public abstract class SchematicHandler { final String name; if (namingScheme == null) { name = - plot.getId().getX() + ";" + plot.getId().getY() + ',' + plot.getArea() + ',' + owner; + plot.getId().getX() + ";" + plot.getId().getY() + ',' + plot.getArea() + ',' + + owner; } else { name = namingScheme.replaceAll("%id%", plot.getId().toString()) .replaceAll("%idx%", plot.getId().getX() + "") @@ -330,57 +331,53 @@ public abstract class SchematicHandler { final int tcx = p2x >> 4; final int tcz = p2z >> 4; - ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { - @Override public void run(int[] value) { - BlockVector2 chunk = BlockVector2.at(value[0], value[1]); - int x = chunk.getX(); - int z = chunk.getZ(); - 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; - } - // Paste schematic here + queue.setChunkConsumer(blockVector2 -> { + int x = blockVector2.getX(); + int z = blockVector2.getZ(); + 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; + } + // Paste schematic here - for (int ry = 0; ry < Math.min(256, HEIGHT); ry++) { - int yy = y_offset_actual + ry; - if (yy > 255) { - continue; - } - for (int rz = zzb - p1z; rz <= (zzt - p1z); rz++) { - for (int rx = xxb - p1x; rx <= (xxt - p1x); rx++) { - int xx = p1x + xOffset + rx; - int zz = p1z + zOffset + rz; - BaseBlock id = blockArrayClipboard - .getFullBlock(BlockVector3.at(rx, ry, rz)); - queue.setBlock(xx, yy, zz, id); - if (ry == 0) { - BiomeType biome = - blockArrayClipboard.getBiome(BlockVector2.at(rx, rz)); - queue.setBiome(xx, zz, biome); - } + for (int ry = 0; ry < Math.min(256, HEIGHT); ry++) { + int yy = y_offset_actual + ry; + if (yy > 255) { + continue; + } + for (int rz = zzb - p1z; rz <= (zzt - p1z); rz++) { + for (int rx = xxb - p1x; rx <= (xxt - p1x); rx++) { + int xx = p1x + xOffset + rx; + int zz = p1z + zOffset + rz; + BaseBlock id = + blockArrayClipboard.getFullBlock(BlockVector3.at(rx, ry, rz)); + queue.setBlock(xx, yy, zz, id); + if (ry == 0) { + BiomeType biome = + blockArrayClipboard.getBiome(BlockVector2.at(rx, rz)); + queue.setBiome(xx, zz, biome); } } } - queue.enqueue(); } - }, () -> { - if (whenDone != null) { - whenDone.value = true; - whenDone.run(); - } - }, 10); + }); + if (whenDone != null) { + whenDone.value = true; + } + queue.setCompleteTask(whenDone); + queue.enqueue(); } catch (Exception e) { e.printStackTrace(); TaskManager.runTask(whenDone); From 73e3572c726849a884842b2f83b891b9a5b14a6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Tue, 21 Jul 2020 13:11:28 +0200 Subject: [PATCH 33/49] Fix the redstone flag on roads --- .../com/plotsquared/bukkit/listener/BlockEventListener.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java index 899a03a04..32408f41e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java @@ -133,7 +133,7 @@ public class BlockEventListener implements Listener { } Plot plot = location.getOwnedPlot(); if (plot == null) { - if (area.isRoadFlags() && area.getRoadFlag(RedstoneFlag.class)) { + if (area.isRoadFlags() && !area.getRoadFlag(RedstoneFlag.class)) { event.setNewCurrent(0); } return; From 27498f68fba7ac43c0fa35ba2300a10d57f8af6b Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Thu, 23 Jul 2020 17:30:23 +0100 Subject: [PATCH 34/49] Many Much - Add readregions to queues for when we're setting our own consumer (usually meaning the queue writes its own blocks, so it doesn't know which chunks to actually load) - Finish removing chunk/regionTasks - Allow the queue to not remove tickets from chunks (useful for swapping chunks so they don't unload needlessly) - Remove a lot of unused methods - Implement entities to queues - Remove chunk unloading (the server should really handle it) --- .../bukkit/inject/BukkitModule.java | 5 +- .../bukkit/queue/BukkitChunkCoordinator.java | 9 +- .../bukkit/queue/BukkitQueueCoordinator.java | 53 +-- .../bukkit/util/BukkitChunkManager.java | 33 -- .../bukkit/util/BukkitRegionManager.java | 349 ++++++------------ .../com/plotsquared/core/command/Area.java | 165 +++++---- .../core/generator/AugmentedUtils.java | 25 +- .../core/generator/HybridPlotManager.java | 3 + .../core/generator/HybridUtils.java | 12 +- .../factory/ChunkCoordinatorFactory.java | 7 +- .../java/com/plotsquared/core/plot/Plot.java | 4 +- .../core/queue/BasicQueueCoordinator.java | 46 ++- .../core/queue/ChunkCoordinatorBuilder.java | 36 +- .../core/queue/DelegateQueueCoordinator.java | 36 ++ .../plotsquared/core/queue/LocalChunk.java | 18 +- .../core/queue/QueueCoordinator.java | 19 + .../plotsquared/core/queue/QueueProvider.java | 15 +- .../plotsquared/core/util/ChunkManager.java | 18 - .../plotsquared/core/util/RegionManager.java | 186 ++++++---- .../core/util/SchematicHandler.java | 3 +- build.gradle | 2 +- 21 files changed, 504 insertions(+), 540 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java index 3361add35..17afd5a1b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java @@ -53,7 +53,6 @@ import com.plotsquared.core.plot.world.DefaultPlotAreaManager; import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.plot.world.SinglePlotAreaManager; import com.plotsquared.core.queue.ChunkCoordinator; -import com.plotsquared.core.queue.ChunkCoordinatorBuilder; import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.queue.QueueProvider; import com.plotsquared.core.util.ChunkManager; @@ -94,8 +93,8 @@ public class BukkitModule extends AbstractModule { bind(InventoryUtil.class).to(BukkitInventoryUtil.class); bind(SetupUtils.class).to(BukkitSetupUtils.class); bind(WorldUtil.class).to(BukkitUtil.class); - bind(GlobalBlockQueue.class).toInstance(new GlobalBlockQueue( - QueueProvider.of(BukkitQueueCoordinator.class, BukkitQueueCoordinator.class))); + bind(GlobalBlockQueue.class) + .toInstance(new GlobalBlockQueue(QueueProvider.of(BukkitQueueCoordinator.class))); bind(ChunkManager.class).to(BukkitChunkManager.class); bind(RegionManager.class).to(BukkitRegionManager.class); bind(SchematicHandler.class).to(BukkitSchematicHandler.class); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java index 41ebeef24..3961cbdac 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java @@ -69,6 +69,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { private final org.bukkit.World bukkitWorld; private final Runnable whenDone; private final Consumer throwableConsumer; + private final boolean unloadAfter; private final int totalSize; private final AtomicInteger expectedSize; @@ -80,7 +81,8 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { @Assisted @Nonnull final World world, @Assisted @Nonnull final Collection requestedChunks, @Assisted @Nonnull final Runnable whenDone, - @Assisted @Nonnull final Consumer throwableConsumer) { + @Assisted @Nonnull final Consumer throwableConsumer, + @Assisted final boolean unloadAfter) { this.requestedChunks = new LinkedBlockingQueue<>(requestedChunks); this.availableChunks = new LinkedBlockingQueue<>(); this.totalSize = requestedChunks.size(); @@ -90,6 +92,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { this.maxIterationTime = maxIterationTime; this.whenDone = whenDone; this.throwableConsumer = throwableConsumer; + this.unloadAfter = unloadAfter; this.plugin = JavaPlugin.getPlugin(BukkitPlatform.class); this.bukkitWorld = Bukkit.getWorld(world.getName()); } @@ -119,7 +122,9 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { } catch (final Throwable throwable) { this.throwableConsumer.accept(throwable); } - this.freeChunk(chunk); + if (unloadAfter) { + this.freeChunk(chunk); + } processedChunks++; final long end = System.currentTimeMillis(); // Update iteration time diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index cdb8a7b5e..a2bd8afeb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -52,17 +52,16 @@ import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import org.bukkit.Bukkit; import org.bukkit.Chunk; -import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Container; import org.bukkit.block.data.BlockData; -import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Collection; import java.util.function.Consumer; public class BukkitQueueCoordinator extends BasicQueueCoordinator { - private final World world; private final SideEffectSet sideEffectSet; private org.bukkit.World bukkitWorld; @Inject private ChunkCoordinatorBuilderFactory chunkCoordinatorBuilderFactory; @@ -72,13 +71,12 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { @Inject public BukkitQueueCoordinator(World world) { super(world); - this.world = world; sideEffectSet = SideEffectSet.none().with(SideEffect.LIGHTING, SideEffect.State.OFF) .with(SideEffect.NEIGHBORS, SideEffect.State.OFF); } @Override public BlockState getBlock(int x, int y, int z) { - org.bukkit.World worldObj = BukkitAdapter.adapt(world); + org.bukkit.World worldObj = BukkitAdapter.adapt(getWorld()); if (worldObj != null) { Block block = worldObj.getBlockAt(x, y, z); return BukkitBlockUtil.get(block); @@ -103,7 +101,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4), BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15)); regenClipboard = new BlockArrayClipboard(region); - world.regenerate(region, regenClipboard); + getWorld().regenerate(region, regenClipboard); } else { regenClipboard = null; } @@ -164,40 +162,51 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { int x = sx + ChunkUtil.getX(j); int y = ChunkUtil.getY(layer, j); int z = sz + ChunkUtil.getZ(j); - world.setBiome(BlockVector3.at(x, y, z), biome); + getWorld().setBiome(BlockVector3.at(x, y, z), biome); } } if (localChunk.getTiles().size() > 0) { localChunk.getTiles().forEach(((blockVector3, tag) -> { try { - BaseBlock block = world.getBlock(blockVector3).toBaseBlock(tag); - world.setBlock(blockVector3, block, sideEffectSet); + BaseBlock block = getWorld().getBlock(blockVector3).toBaseBlock(tag); + getWorld().setBlock(blockVector3, block, sideEffectSet); } catch (WorldEditException ignored) { StateWrapper sw = new StateWrapper(tag); - sw.restoreTag(world.getName(), blockVector3.getX(), blockVector3.getY(), - blockVector3.getZ()); + sw.restoreTag(getWorld().getName(), blockVector3.getX(), + blockVector3.getY(), blockVector3.getZ()); } })); } + if (localChunk.getEntities().size() > 0) { + localChunk.getEntities().forEach((location, entity) -> { + getWorld().createEntity(location, entity); + }); + } }; } + CuboidRegion region; + Collection read = new ArrayList<>(); + if ((region = getReadRegion()) != null) { + read = region.getChunks(); + } chunkCoordinator = - chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(world) - .withChunks(getBlockChunks().keySet()).withInitialBatchSize(3) + chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(getWorld()) + .withChunks(getBlockChunks().keySet()).withChunks(read).withInitialBatchSize(3) .withMaxIterationTime(40).withThrowableConsumer(Throwable::printStackTrace) - .withFinalAction(whenDone).withConsumer(consumer).build(); + .withFinalAction(whenDone).withConsumer(consumer).unloadAfter(isUnloadAfter()) + .build(); return super.enqueue(); } private void setWorldBlock(int x, int y, int z, BaseBlock block, BlockVector2 blockVector2) { try { - world.setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); + getWorld().setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); } catch (WorldEditException ignored) { // Fallback to not so nice method BlockData blockData = BukkitAdapter.adapt(block); if (bukkitWorld == null) { - bukkitWorld = Bukkit.getWorld(world.getName()); + bukkitWorld = Bukkit.getWorld(getWorld().getName()); } Chunk chunk = bukkitWorld.getChunkAt(blockVector2.getX(), blockVector2.getZ()); @@ -218,7 +227,8 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { CompoundTag tag = block.getNbtData(); StateWrapper sw = new StateWrapper(tag); - sw.restoreTag(world.getName(), existing.getX(), existing.getY(), existing.getZ()); + sw.restoreTag(getWorld().getName(), existing.getX(), existing.getY(), + existing.getZ()); } } } @@ -227,13 +237,4 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { this.whenDone = whenDone; } - private void setMaterial(@Nonnull final BlockState plotBlock, @Nonnull final Block block) { - Material material = BukkitAdapter.adapt(plotBlock.getBlockType()); - block.setType(material, false); - } - - private boolean equals(@Nonnull final BlockState plotBlock, @Nonnull final Block block) { - return plotBlock.equals(BukkitBlockUtil.get(block)); - } - } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java index ed2898c65..4e5bfb49b 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java @@ -129,37 +129,4 @@ public class BukkitChunkManager extends ChunkManager { .getChunkAtAsync(BukkitUtil.getWorld(world), chunkLoc.getX(), chunkLoc.getZ(), force); } - @Override - public void unloadChunk(final String world, final BlockVector2 chunkLoc, final boolean save) { - if (!PlotSquared.get().isMainThread(Thread.currentThread())) { - TaskManager.runTask(() -> BukkitUtil.getWorld(world) - .unloadChunk(chunkLoc.getX(), chunkLoc.getZ(), save)); - } else { - BukkitUtil.getWorld(world).unloadChunk(chunkLoc.getX(), chunkLoc.getZ(), save); - } - } - - private void count(int[] count, Entity entity) { - final com.sk89q.worldedit.world.entity.EntityType entityType = - BukkitAdapter.adapt(entity.getType()); - - if (EntityCategories.PLAYER.contains(entityType)) { - return; - } else if (EntityCategories.PROJECTILE.contains(entityType) || EntityCategories.OTHER - .contains(entityType) || EntityCategories.HANGING.contains(entityType)) { - count[CAP_MISC]++; - } else if (EntityCategories.ANIMAL.contains(entityType) || EntityCategories.VILLAGER - .contains(entityType) || EntityCategories.TAMEABLE.contains(entityType)) { - count[CAP_MOB]++; - count[CAP_ANIMAL]++; - } else if (EntityCategories.VEHICLE.contains(entityType)) { - count[CAP_VEHICLE]++; - } else if (EntityCategories.HOSTILE.contains(entityType)) { - count[CAP_MOB]++; - count[CAP_MONSTER]++; - } - count[CAP_ENTITY]++; - } - - } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java index 795a4cab9..23ed242d7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java @@ -28,15 +28,13 @@ package com.plotsquared.bukkit.util; import com.google.inject.Inject; import com.google.inject.Singleton; import com.plotsquared.bukkit.BukkitPlatform; -import com.plotsquared.core.PlotSquared; import com.plotsquared.core.generator.AugmentedUtils; -import com.plotsquared.core.inject.factory.ChunkCoordinatorBuilderFactory; -import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory; import com.plotsquared.core.location.Location; import com.plotsquared.core.location.PlotLoc; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotManager; +import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.ChunkManager; @@ -45,13 +43,11 @@ import com.plotsquared.core.util.RegionUtil; import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.entity.EntityCategories; import com.plotsquared.core.util.task.RunnableVal; -import com.plotsquared.core.util.task.TaskManager; -import com.plotsquared.core.util.task.TaskTime; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; -import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockTypes; import io.papermc.lib.PaperLib; @@ -63,17 +59,13 @@ import org.bukkit.entity.Player; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nonnull; -import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashSet; import java.util.List; -import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.concurrent.Semaphore; -import static com.google.common.base.Preconditions.checkNotNull; import static com.plotsquared.core.util.entity.EntityCategories.CAP_ANIMAL; import static com.plotsquared.core.util.entity.EntityCategories.CAP_ENTITY; import static com.plotsquared.core.util.entity.EntityCategories.CAP_MISC; @@ -86,19 +78,8 @@ public class BukkitRegionManager extends RegionManager { private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitRegionManager.class.getSimpleName()); - private final WorldUtil worldUtil; - private final ChunkCoordinatorFactory chunkCoordinatorFactory; - private final ChunkCoordinatorBuilderFactory chunkCoordinatorBuilderFactory; - - @Inject public BukkitRegionManager(@Nonnull final ChunkManager chunkManager, - @Nonnull final WorldUtil worldUtil, - @Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory, - @Nonnull ChunkCoordinatorBuilderFactory chunkCoordinatorBuilderFactory) { - super(chunkManager, worldUtil, chunkCoordinatorBuilderFactory); - this.worldUtil = worldUtil; - this.chunkCoordinatorFactory = chunkCoordinatorFactory; - this.chunkCoordinatorBuilderFactory = chunkCoordinatorBuilderFactory; - } + @Inject private WorldUtil worldUtil; + @Inject private GlobalBlockQueue blockQueue; @Override public Set getChunkChunks(String world) { Set chunks = super.getChunkChunks(world); @@ -141,7 +122,6 @@ public class BukkitRegionManager extends RegionManager { } PlotArea area = plot.getArea(); World world = BukkitUtil.getWorld(area.getWorldName()); - Location bot = plot.getBottomAbs(); Location top = plot.getTopAbs(); int bx = bot.getX() >> 4; @@ -209,53 +189,6 @@ public class BukkitRegionManager extends RegionManager { return count; } - @Override @Inject - public boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, - final Runnable whenDone) { - final int relX = newPos.getX() - pos1.getX(); - final int relZ = newPos.getZ() - pos1.getZ(); - final com.sk89q.worldedit.world.World oldWorld = worldUtil.getWeWorld(pos1.getWorldName()); - final BukkitWorld newWorld = new BukkitWorld((World) newPos.getWorld()); - assert oldWorld.equals(newWorld); - final ContentMap map = new ContentMap(); - final QueueCoordinator queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(newWorld); - chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(newWorld) - .withRegion(pos1, pos2).withThrowableConsumer(Throwable::printStackTrace) - .withRegion(pos1, pos2).withInitialBatchSize(4).withMaxIterationTime(45) - .withConsumer(chunk -> { - int cbx = chunk.getX(); - int cbz = chunk.getZ(); - int bx = Math.max(pos1.getX() & 15, 0); - int bz = Math.max(pos1.getZ() & 15, 0); - int tx = Math.min(pos2.getX() & 15, 15); - int tz = Math.min(pos2.getZ() & 15, 15); - for (int x = bx; x <= tx; x++) { - for (int z = bz; z <= tz; z++) { - map.saveBlocks(newWorld, 256, cbx + x, cbz + z, relX, relZ); - } - } - }).withFinalAction(() -> { - for (Entry entry : map.allBlocks.entrySet()) { - PlotLoc loc = entry.getKey(); - BaseBlock[] blocks = entry.getValue(); - for (int y = 0; y < blocks.length; y++) { - if (blocks[y] != null) { - BaseBlock block = blocks[y]; - queue.setBlock(loc.getX(), y, loc.getZ(), block); - } - } - } - queue.setCompleteTask(() -> { - //map.restoreBlocks(newWorld, 0, 0); - map.restoreEntities(Bukkit.getWorld(newPos.getWorldName()), relX, relZ); - TaskManager.runTask(whenDone); - }); - queue.enqueue(); - }); - return true; - } - @Override @Inject public boolean regenerateRegion(final Location pos1, final Location pos2, final boolean ignoreAugment, final Runnable whenDone) { final BukkitWorld world = new BukkitWorld((World) pos1.getWorld()); @@ -269,130 +202,120 @@ public class BukkitRegionManager extends RegionManager { final int tcx = p2x >> 4; final int tcz = p2z >> 4; - final List chunks = new ArrayList<>(); + final QueueCoordinator queue = blockQueue.getNewQueue(world); + queue.setReadRegion(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3())); + queue.setChunkConsumer(chunk -> { - for (int x = bcx; x <= tcx; x++) { - for (int z = bcz; z <= tcz; z++) { - chunks.add(BlockVector2.at(x, z)); + int x = chunk.getX(); + int z = chunk.getZ(); + int xxb = x << 4; + int zzb = z << 4; + int xxt = xxb + 15; + int zzt = zzb + 15; + if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) { + AugmentedUtils + .bypass(ignoreAugment, () -> queue.regenChunk(chunk.getX(), chunk.getZ())); + return; } - } + boolean checkX1 = false; - final QueueCoordinator queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(world); - chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(world) - .withRegion(pos1, pos2).withThrowableConsumer(Throwable::printStackTrace) - .withRegion(pos1, pos2).withInitialBatchSize(4).withMaxIterationTime(45) - .withConsumer(chunk -> { + int xxb2; - int x = chunk.getX(); - int z = chunk.getZ(); - int xxb = x << 4; - int zzb = z << 4; - int xxt = xxb + 15; - int zzt = zzb + 15; - if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) { - AugmentedUtils.bypass(ignoreAugment, - () -> queue.regenChunk(chunk.getX(), chunk.getZ())); - return; - } - boolean checkX1 = false; - - int xxb2; - - if (x == bcx) { - xxb2 = p1x - 1; - checkX1 = true; - } else { - xxb2 = xxb; - } - boolean checkX2 = false; - int xxt2; - if (x == tcx) { - xxt2 = p2x + 1; - checkX2 = true; - } else { - xxt2 = xxt; - } - boolean checkZ1 = false; - int zzb2; - if (z == bcz) { - zzb2 = p1z - 1; - checkZ1 = true; - } else { - zzb2 = zzb; - } - boolean checkZ2 = false; - int zzt2; - if (z == tcz) { - zzt2 = p2z + 1; - checkZ2 = true; - } else { - zzt2 = zzt; - } - final ContentMap map = new ContentMap(); - if (checkX1) { - map.saveRegion(world, xxb, xxb2, zzb2, zzt2); // - } - if (checkX2) { - map.saveRegion(world, xxt2, xxt, zzb2, zzt2); // - } - if (checkZ1) { - map.saveRegion(world, xxb2, xxt2, zzb, zzb2); // - } - if (checkZ2) { - map.saveRegion(world, xxb2, xxt2, zzt2, zzt); // - } - if (checkX1 && checkZ1) { - map.saveRegion(world, xxb, xxb2, zzb, zzb2); // - } - if (checkX2 && checkZ1) { - map.saveRegion(world, xxt2, xxt, zzb, zzb2); // ? - } - if (checkX1 && checkZ2) { - map.saveRegion(world, xxb, xxb2, zzt2, zzt); // ? - } - if (checkX2 && checkZ2) { - map.saveRegion(world, xxt2, xxt, zzt2, zzt); // - } - CuboidRegion currentPlotClear = - RegionUtil.createRegion(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); - map.saveEntitiesOut(Bukkit.getWorld(world.getName()).getChunkAt(x, z), - currentPlotClear); - AugmentedUtils.bypass(ignoreAugment, () -> ChunkManager - .setChunkInPlotArea(null, new RunnableVal() { - @Override public void run(ScopedQueueCoordinator value) { - Location min = value.getMin(); - int bx = min.getX(); - int bz = min.getZ(); - for (int x1 = 0; x1 < 16; x1++) { - for (int z1 = 0; z1 < 16; z1++) { - PlotLoc plotLoc = new PlotLoc(bx + x1, bz + z1); - BaseBlock[] ids = map.allBlocks.get(plotLoc); - if (ids != null) { - for (int y = 0; y < Math.min(128, ids.length); y++) { - BaseBlock id = ids[y]; - if (id != null) { - value.setBlock(x1, y, z1, id); - } else { - value.setBlock(x1, y, z1, - BlockTypes.AIR.getDefaultState()); - } + if (x == bcx) { + xxb2 = p1x - 1; + checkX1 = true; + } else { + xxb2 = xxb; + } + boolean checkX2 = false; + int xxt2; + if (x == tcx) { + xxt2 = p2x + 1; + checkX2 = true; + } else { + xxt2 = xxt; + } + boolean checkZ1 = false; + int zzb2; + if (z == bcz) { + zzb2 = p1z - 1; + checkZ1 = true; + } else { + zzb2 = zzb; + } + boolean checkZ2 = false; + int zzt2; + if (z == tcz) { + zzt2 = p2z + 1; + checkZ2 = true; + } else { + zzt2 = zzt; + } + final ContentMap map = new ContentMap(); + if (checkX1) { + map.saveRegion(world, xxb, xxb2, zzb2, zzt2); // + } + if (checkX2) { + map.saveRegion(world, xxt2, xxt, zzb2, zzt2); // + } + if (checkZ1) { + map.saveRegion(world, xxb2, xxt2, zzb, zzb2); // + } + if (checkZ2) { + map.saveRegion(world, xxb2, xxt2, zzt2, zzt); // + } + if (checkX1 && checkZ1) { + map.saveRegion(world, xxb, xxb2, zzb, zzb2); // + } + if (checkX2 && checkZ1) { + map.saveRegion(world, xxt2, xxt, zzb, zzb2); // ? + } + if (checkX1 && checkZ2) { + map.saveRegion(world, xxb, xxb2, zzt2, zzt); // ? + } + if (checkX2 && checkZ2) { + map.saveRegion(world, xxt2, xxt, zzt2, zzt); // + } + CuboidRegion currentPlotClear = + RegionUtil.createRegion(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); + map.saveEntitiesOut(Bukkit.getWorld(world.getName()).getChunkAt(x, z), + currentPlotClear); + AugmentedUtils.bypass(ignoreAugment, () -> ChunkManager + .setChunkInPlotArea(null, new RunnableVal() { + @Override public void run(ScopedQueueCoordinator value) { + Location min = value.getMin(); + int bx = min.getX(); + int bz = min.getZ(); + for (int x1 = 0; x1 < 16; x1++) { + for (int z1 = 0; z1 < 16; z1++) { + PlotLoc plotLoc = new PlotLoc(bx + x1, bz + z1); + BaseBlock[] ids = map.allBlocks.get(plotLoc); + if (ids != null) { + for (int y = 0; y < Math.min(128, ids.length); y++) { + BaseBlock id = ids[y]; + if (id != null) { + value.setBlock(x1, y, z1, id); + } else { + value.setBlock(x1, y, z1, + BlockTypes.AIR.getDefaultState()); } - for (int y = Math.min(128, ids.length); - y < ids.length; y++) { - BaseBlock id = ids[y]; - if (id != null) { - value.setBlock(x1, y, z1, id); - } + } + for (int y = Math.min(128, ids.length); y < ids.length; y++) { + BaseBlock id = ids[y]; + if (id != null) { + value.setBlock(x1, y, z1, id); } } } } } - }, world.getName(), chunk)); - //map.restoreBlocks(worldObj, 0, 0); - map.restoreEntities(Bukkit.getWorld(world.getName()), 0, 0); - }).withFinalAction(whenDone); + } + }, world.getName(), chunk)); + //map.restoreBlocks(worldObj, 0, 0); + map.restoreEntities(Bukkit.getWorld(world.getName()), 0, 0); + }); + queue.setCompleteTask(whenDone); + queue.enqueue(); return true; } @@ -425,62 +348,6 @@ public class BukkitRegionManager extends RegionManager { } } - @Override public void swap(Location bot1, Location top1, Location bot2, Location top2, - final Runnable whenDone) { - CuboidRegion region1 = - RegionUtil.createRegion(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); - CuboidRegion region2 = - RegionUtil.createRegion(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ()); - final World world1 = Bukkit.getWorld(bot1.getWorldName()); - final World world2 = Bukkit.getWorld(bot2.getWorldName()); - checkNotNull(world1, "Critical error during swap."); - checkNotNull(world2, "Critical error during swap."); - int relX = bot2.getX() - bot1.getX(); - int relZ = bot2.getZ() - bot1.getZ(); - - final ArrayDeque maps = new ArrayDeque<>(); - - for (int x = bot1.getX() >> 4; x <= top1.getX() >> 4; x++) { - for (int z = bot1.getZ() >> 4; z <= top1.getZ() >> 4; z++) { - Chunk chunk1 = world1.getChunkAt(x, z); - Chunk chunk2 = world2.getChunkAt(x + (relX >> 4), z + (relZ >> 4)); - maps.add( - BukkitChunkManager.swapChunk(world1, world2, chunk1, chunk2, region1, region2)); - } - } - PlotSquared.platform().getGlobalBlockQueue().addEmptyTask(() -> { - for (ContentMap map : maps) { - map.restoreEntities(world1, 0, 0); - TaskManager.runTaskLater(whenDone, TaskTime.ticks(1L)); - } - }); - } - - @Override - public void setBiome(final CuboidRegion region, final int extendBiome, final BiomeType biome, - final String world, final Runnable whenDone) { - Location pos1 = Location.at(world, region.getMinimumPoint().getX() - extendBiome, - region.getMinimumPoint().getY(), region.getMinimumPoint().getZ() - extendBiome); - Location pos2 = Location.at(world, region.getMaximumPoint().getX() + extendBiome, - region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome); - final QueueCoordinator queue = PlotSquared.platform().getGlobalBlockQueue() - .getNewQueue(worldUtil.getWeWorld(world)); - - final int minX = pos1.getX(); - final int minZ = pos1.getZ(); - final int maxX = pos2.getX(); - final int maxZ = pos2.getZ(); - queue.setChunkConsumer(blockVector2 -> { - final int cx = blockVector2.getX() << 4; - final int cz = blockVector2.getZ() << 4; - WorldUtil - .setBiome(world, Math.max(minX, cx), Math.max(minZ, cz), Math.min(maxX, cx + 15), - Math.min(maxZ, cz + 15), biome); - worldUtil.refreshChunk(blockVector2.getBlockX(), blockVector2.getBlockZ(), world); - }); - queue.enqueue(); - } - private void count(int[] count, Entity entity) { final com.sk89q.worldedit.world.entity.EntityType entityType = BukkitAdapter.adapt(entity.getType()); diff --git a/Core/src/main/java/com/plotsquared/core/command/Area.java b/Core/src/main/java/com/plotsquared/core/command/Area.java index aad920373..5003b3b14 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Area.java +++ b/Core/src/main/java/com/plotsquared/core/command/Area.java @@ -27,8 +27,6 @@ package com.plotsquared.core.command; import com.google.inject.Inject; import com.plotsquared.core.PlotSquared; -import com.plotsquared.core.inject.annotations.WorldConfig; -import com.plotsquared.core.inject.annotations.WorldFile; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.configuration.ConfigurationSection; import com.plotsquared.core.configuration.ConfigurationUtil; @@ -36,6 +34,8 @@ import com.plotsquared.core.configuration.file.YamlConfiguration; import com.plotsquared.core.events.TeleportCause; import com.plotsquared.core.generator.AugmentedUtils; import com.plotsquared.core.generator.HybridPlotWorld; +import com.plotsquared.core.inject.annotations.WorldConfig; +import com.plotsquared.core.inject.annotations.WorldFile; import com.plotsquared.core.inject.factory.HybridPlotWorldFactory; import com.plotsquared.core.location.Location; import com.plotsquared.core.player.ConsolePlayer; @@ -46,6 +46,8 @@ import com.plotsquared.core.plot.PlotAreaType; import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.plot.message.PlotMessage; import com.plotsquared.core.plot.world.PlotAreaManager; +import com.plotsquared.core.queue.GlobalBlockQueue; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.setup.PlotAreaBuilder; import com.plotsquared.core.util.FileUtils; import com.plotsquared.core.util.MainUtil; @@ -57,7 +59,6 @@ import com.plotsquared.core.util.SchematicHandler; import com.plotsquared.core.util.SetupUtils; import com.plotsquared.core.util.StringMan; import com.plotsquared.core.util.WorldUtil; -import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.RunnableVal3; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalSession; @@ -68,12 +69,11 @@ import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operations; -import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -100,14 +100,14 @@ public class Area extends SubCommand { private final SetupUtils setupUtils; private final WorldUtil worldUtil; private final RegionManager regionManager; + private final GlobalBlockQueue blockQueue; @Inject public Area(@Nonnull final PlotAreaManager plotAreaManager, - @WorldConfig @Nonnull final YamlConfiguration worldConfiguration, - @WorldFile @Nonnull final File worldFile, - @Nonnull final HybridPlotWorldFactory hybridPlotWorldFactory, - @Nonnull final SetupUtils setupUtils, - @Nonnull final WorldUtil worldUtil, - @Nonnull final RegionManager regionManager) { + @WorldConfig @Nonnull final YamlConfiguration worldConfiguration, + @WorldFile @Nonnull final File worldFile, + @Nonnull final HybridPlotWorldFactory hybridPlotWorldFactory, + @Nonnull final SetupUtils setupUtils, @Nonnull final WorldUtil worldUtil, + @Nonnull final RegionManager regionManager, @Nonnull final GlobalBlockQueue blockQueue) { this.plotAreaManager = plotAreaManager; this.worldConfiguration = worldConfiguration; this.worldFile = worldFile; @@ -115,6 +115,7 @@ public class Area extends SubCommand { this.setupUtils = setupUtils; this.worldUtil = worldUtil; this.regionManager = regionManager; + this.blockQueue = blockQueue; } @Override public boolean onCommand(final PlotPlayer player, String[] args) { @@ -129,27 +130,32 @@ public class Area extends SubCommand { return false; } if (!Permissions.hasPermission(player, Captions.PERMISSION_AREA_CREATE)) { - MainUtil.sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_AREA_CREATE); + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_AREA_CREATE); return false; } if (args.length < 2) { MainUtil.sendMessage(player, Captions.SINGLE_AREA_NEEDS_NAME); return false; } - final PlotArea existingArea = this.plotAreaManager.getPlotArea(player.getLocation().getWorldName(), args[1]); + final PlotArea existingArea = + this.plotAreaManager.getPlotArea(player.getLocation().getWorldName(), args[1]); if (existingArea != null && existingArea.getId().equalsIgnoreCase(args[1])) { MainUtil.sendMessage(player, Captions.SINGLE_AREA_NAME_TAKEN); return false; } - final LocalSession localSession = WorldEdit.getInstance().getSessionManager().getIfPresent(player.toActor()); + final LocalSession localSession = + WorldEdit.getInstance().getSessionManager().getIfPresent(player.toActor()); if (localSession == null) { MainUtil.sendMessage(player, Captions.SINGLE_AREA_MISSING_SELECTION); return false; } Region playerSelectedRegion = null; try { - playerSelectedRegion = localSession.getSelection(((Player) player.toActor()).getWorld()); - } catch (final Exception ignored) {} + playerSelectedRegion = + localSession.getSelection(((Player) player.toActor()).getWorld()); + } catch (final Exception ignored) { + } if (playerSelectedRegion == null) { MainUtil.sendMessage(player, Captions.SINGLE_AREA_MISSING_SELECTION); return false; @@ -158,23 +164,28 @@ public class Area extends SubCommand { MainUtil.sendMessage(player, Captions.SINGLE_AREA_NOT_SQUARE); return false; } - if (this.plotAreaManager.getPlotAreas( - Objects.requireNonNull(playerSelectedRegion.getWorld()).getName(), CuboidRegion.makeCuboid(playerSelectedRegion)).length != 0) { + if (this.plotAreaManager + .getPlotAreas(Objects.requireNonNull(playerSelectedRegion.getWorld()).getName(), + CuboidRegion.makeCuboid(playerSelectedRegion)).length != 0) { MainUtil.sendMessage(player, Captions.SINGLE_AREA_OVERLAPPING); } // Alter the region final BlockVector3 playerSelectionMin = playerSelectedRegion.getMinimumPoint(); final BlockVector3 playerSelectionMax = playerSelectedRegion.getMaximumPoint(); // Create a new selection that spans the entire vertical range of the world - final CuboidRegion selectedRegion = new CuboidRegion(playerSelectedRegion.getWorld(), - BlockVector3.at(playerSelectionMin.getX(), 0, playerSelectionMin.getZ()), - BlockVector3.at(playerSelectionMax.getX(), 255, playerSelectionMax.getZ())); + final CuboidRegion selectedRegion = + new CuboidRegion(playerSelectedRegion.getWorld(), + BlockVector3.at(playerSelectionMin.getX(), 0, playerSelectionMin.getZ()), + BlockVector3.at(playerSelectionMax.getX(), 255, playerSelectionMax.getZ())); // There's only one plot in the area... final PlotId plotId = PlotId.of(1, 1); - final HybridPlotWorld hybridPlotWorld = this.hybridPlotWorldFactory.create(player.getLocation().getWorldName(), args[1], - Objects.requireNonNull(PlotSquared.platform()).getDefaultGenerator(), plotId, plotId); + final HybridPlotWorld hybridPlotWorld = this.hybridPlotWorldFactory + .create(player.getLocation().getWorldName(), args[1], + Objects.requireNonNull(PlotSquared.platform()).getDefaultGenerator(), + plotId, plotId); // Plot size is the same as the region width - hybridPlotWorld.PLOT_WIDTH = hybridPlotWorld.SIZE = (short) selectedRegion.getWidth(); + hybridPlotWorld.PLOT_WIDTH = + hybridPlotWorld.SIZE = (short) selectedRegion.getWidth(); // We use a schematic generator hybridPlotWorld.setTerrain(PlotAreaTerrainType.NONE); // It is always a partial plot world @@ -182,23 +193,30 @@ public class Area extends SubCommand { // We save the schematic :D hybridPlotWorld.PLOT_SCHEMATIC = true; // Set the road width to 0 - hybridPlotWorld.ROAD_WIDTH = hybridPlotWorld.ROAD_OFFSET_X = hybridPlotWorld.ROAD_OFFSET_Z = 0; + hybridPlotWorld.ROAD_WIDTH = + hybridPlotWorld.ROAD_OFFSET_X = hybridPlotWorld.ROAD_OFFSET_Z = 0; // Set the plot height to the selection height - hybridPlotWorld.PLOT_HEIGHT = hybridPlotWorld.ROAD_HEIGHT = hybridPlotWorld.WALL_HEIGHT = playerSelectionMin.getBlockY(); + hybridPlotWorld.PLOT_HEIGHT = hybridPlotWorld.ROAD_HEIGHT = + hybridPlotWorld.WALL_HEIGHT = playerSelectionMin.getBlockY(); // No sign plz hybridPlotWorld.setAllowSigns(false); - final File parentFile = FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics" + File.separator + - "GEN_ROAD_SCHEMATIC" + File.separator + hybridPlotWorld.getWorldName() + File.separator + - hybridPlotWorld.getId()); + final File parentFile = FileUtils.getFile(PlotSquared.platform().getDirectory(), + "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + + hybridPlotWorld.getWorldName() + File.separator + hybridPlotWorld + .getId()); if (!parentFile.exists() && !parentFile.mkdirs()) { MainUtil.sendMessage(player, Captions.SINGLE_AREA_COULD_NOT_MAKE_DIRECTORIES); return false; } final File file = new File(parentFile, "plot.schem"); - try (final ClipboardWriter clipboardWriter = BuiltInClipboardFormat.SPONGE_SCHEMATIC.getWriter(new FileOutputStream(file))) { + try (final ClipboardWriter clipboardWriter = BuiltInClipboardFormat.SPONGE_SCHEMATIC + .getWriter(new FileOutputStream(file))) { final BlockArrayClipboard clipboard = new BlockArrayClipboard(selectedRegion); - final EditSession editSession = WorldEdit.getInstance().getEditSessionFactory().getEditSession(selectedRegion.getWorld(), -1); - final ForwardExtentCopy forwardExtentCopy = new ForwardExtentCopy(editSession, selectedRegion, clipboard, selectedRegion.getMinimumPoint()); + final EditSession editSession = WorldEdit.getInstance().getEditSessionFactory() + .getEditSession(selectedRegion.getWorld(), -1); + final ForwardExtentCopy forwardExtentCopy = + new ForwardExtentCopy(editSession, selectedRegion, clipboard, + selectedRegion.getMinimumPoint()); forwardExtentCopy.setCopyingBiomes(true); forwardExtentCopy.setCopyingEntities(true); Operations.complete(forwardExtentCopy); @@ -221,14 +239,14 @@ public class Area extends SubCommand { // Now the schematic is saved, which is wonderful! PlotAreaBuilder singleBuilder = PlotAreaBuilder.ofPlotArea(hybridPlotWorld) - .plotManager(PlotSquared.platform().getPluginName()) - .generatorName(PlotSquared.platform().getPluginName()) - .maximumId(plotId) - .minimumId(plotId); + .plotManager(PlotSquared.platform().getPluginName()) + .generatorName(PlotSquared.platform().getPluginName()).maximumId(plotId) + .minimumId(plotId); Runnable singleRun = () -> { final String path = - "worlds." + hybridPlotWorld.getWorldName() + ".areas." + hybridPlotWorld.getId() + '-' - + singleBuilder.minimumId() + '-' + singleBuilder.maximumId(); + "worlds." + hybridPlotWorld.getWorldName() + ".areas." + hybridPlotWorld + .getId() + '-' + singleBuilder.minimumId() + '-' + singleBuilder + .maximumId(); final int offsetX = singlePos1.getX(); final int offsetZ = singlePos1.getZ(); if (offsetX != 0) { @@ -314,19 +332,20 @@ public class Area extends SubCommand { return false; } PlotAreaBuilder builder = PlotAreaBuilder.ofPlotArea(area) - .plotManager(PlotSquared.platform().getPluginName()) - .generatorName(PlotSquared.platform().getPluginName()) - .minimumId(PlotId.of(1, 1)) - .maximumId(PlotId.of(numX, numZ)); + .plotManager(PlotSquared.platform().getPluginName()) + .generatorName(PlotSquared.platform().getPluginName()) + .minimumId(PlotId.of(1, 1)).maximumId(PlotId.of(numX, numZ)); final String path = "worlds." + area.getWorldName() + ".areas." + area.getId() + '-' + builder.minimumId() + '-' + builder.maximumId(); Runnable run = () -> { if (offsetX != 0) { - this.worldConfiguration.set(path + ".road.offset.x", offsetX); + this.worldConfiguration + .set(path + ".road.offset.x", offsetX); } if (offsetZ != 0) { - this.worldConfiguration.set(path + ".road.offset.z", offsetZ); + this.worldConfiguration + .set(path + ".road.offset.z", offsetZ); } final String world = this.setupUtils.setupWorld(builder); if (this.worldUtil.isWorld(world)) { @@ -335,14 +354,13 @@ public class Area extends SubCommand { player.teleport(this.worldUtil.getSpawn(world), TeleportCause.COMMAND); if (area.getTerrain() != PlotAreaTerrainType.ALL) { - this.regionManager.largeRegionTask(world, region, - new RunnableVal() { - @Override public void run(BlockVector2 value) { - AugmentedUtils - .generate(null, world, value.getX(), - value.getZ(), null); - } - }, null); + QueueCoordinator queue = + blockQueue.getNewQueue(worldUtil.getWeWorld(world)); + queue.setChunkConsumer(chunk -> AugmentedUtils + .generate(null, world, chunk.getX(), chunk.getZ(), + queue)); + queue.setReadRegion(region); + queue.enqueue(); } } else { MainUtil.sendMessage(player, @@ -368,14 +386,16 @@ public class Area extends SubCommand { } PlotAreaBuilder builder = PlotAreaBuilder.newBuilder(); builder.worldName(split[0]); - final HybridPlotWorld pa = this.hybridPlotWorldFactory.create(builder.worldName(), - id, PlotSquared.platform().getDefaultGenerator(), null, null); + final HybridPlotWorld pa = this.hybridPlotWorldFactory + .create(builder.worldName(), id, + PlotSquared.platform().getDefaultGenerator(), null, null); PlotArea other = this.plotAreaManager.getPlotArea(pa.getWorldName(), id); if (other != null && Objects.equals(pa.getId(), other.getId())) { Captions.SETUP_WORLD_TAKEN.send(player, pa.toString()); return false; } - Set areas = this.plotAreaManager.getPlotAreasSet(pa.getWorldName()); + Set areas = + this.plotAreaManager.getPlotAreasSet(pa.getWorldName()); if (!areas.isEmpty()) { PlotArea area = areas.iterator().next(); pa.setType(area.getType()); @@ -454,7 +474,8 @@ public class Area extends SubCommand { if (!this.worldConfiguration.contains(path)) { this.worldConfiguration.createSection(path); } - ConfigurationSection section = this.worldConfiguration.getConfigurationSection(path); + ConfigurationSection section = + this.worldConfiguration.getConfigurationSection(path); pa.saveConfiguration(section); pa.loadConfiguration(section); builder.plotManager(PlotSquared.platform().getPluginName()); @@ -581,7 +602,8 @@ public class Area extends SubCommand { Captions.COMMAND_SYNTAX.send(player, getCommandString() + " list [#]"); return false; } - final List areas = new ArrayList<>(Arrays.asList(this.plotAreaManager.getAllPlotAreas())); + final List areas = + new ArrayList<>(Arrays.asList(this.plotAreaManager.getAllPlotAreas())); paginate(player, areas, 8, page, new RunnableVal3() { @Override public void run(Integer i, PlotArea area, PlotMessage message) { @@ -596,7 +618,8 @@ public class Area extends SubCommand { PlotId max = area.getMax(); name = area.getWorldName() + ';' + area.getId() + ';' + min + ';' + max; - int size = (max.getX() - min.getX() + 1) * (max.getY() - min.getY() + 1); + int size = + (max.getX() - min.getX() + 1) * (max.getY() - min.getY() + 1); percent = claimed == 0 ? 0 : size / (double) claimed; region = area.getRegion().toString(); } else { @@ -641,14 +664,14 @@ public class Area extends SubCommand { "$4Stop the server and delete: " + area.getWorldName() + "/region"); return false; } - this.regionManager.largeRegionTask(area.getWorldName(), area.getRegion(), - new RunnableVal() { - @Override public void run(BlockVector2 value) { - AugmentedUtils - .generate(null, area.getWorldName(), value.getX(), value.getZ(), - null); - } - }, () -> player.sendMessage("Regen complete")); + + QueueCoordinator queue = + blockQueue.getNewQueue(worldUtil.getWeWorld(area.getWorldName())); + queue.setChunkConsumer(chunk -> AugmentedUtils + .generate(null, area.getWorldName(), chunk.getX(), chunk.getZ(), queue)); + queue.setReadRegion(area.getRegion()); + queue.setCompleteTask(() -> player.sendMessage("Regen complete")); + queue.enqueue(); return true; } case "goto": @@ -676,11 +699,13 @@ public class Area extends SubCommand { } else { CuboidRegion region = area.getRegion(); center = Location.at(area.getWorldName(), region.getMinimumPoint().getX() - + (region.getMaximumPoint().getX() - region.getMinimumPoint().getX()) / 2, + + (region.getMaximumPoint().getX() - region.getMinimumPoint().getX()) / 2, 0, region.getMinimumPoint().getZ() - + (region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ()) / 2); - this.worldUtil.getHighestBlock(area.getWorldName(), center.getX(), center.getZ(), y -> - player.teleport(center.withY(1 + y), TeleportCause.COMMAND)); + + (region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ()) + / 2); + this.worldUtil + .getHighestBlock(area.getWorldName(), center.getX(), center.getZ(), + y -> player.teleport(center.withY(1 + y), TeleportCause.COMMAND)); } return true; case "delete": diff --git a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java index 1a06a412d..8c797ba45 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java @@ -72,6 +72,7 @@ public class AugmentedUtils { if (areas.isEmpty()) { return false; } + boolean enqueue = false; boolean generationResult = false; for (final PlotArea area : areas) { // A normal plot world may not contain any clusters @@ -81,14 +82,18 @@ public class AugmentedUtils { } // This means that full vanilla generation is used // so we do not interfere - if (area.getTerrain() == PlotAreaTerrainType.ALL) { + if (area.getTerrain() == PlotAreaTerrainType.ALL || !area.contains(blockX, blockZ)) { continue; } IndependentPlotGenerator generator = area.getGenerator(); // Mask if (queue == null) { - queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); - queue.setChunkObject(chunkObject); + enqueue = true; + queue = PlotSquared.platform().getGlobalBlockQueue() + .getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); + if (chunkObject != null) { + queue.setChunkObject(chunkObject); + } } QueueCoordinator primaryMask; // coordinates @@ -109,7 +114,6 @@ public class AugmentedUtils { relativeTopX = relativeTopZ = 15; primaryMask = queue; } - QueueCoordinator secondaryMask; BlockState air = BlockTypes.AIR.getDefaultState(); if (area.getTerrain() == PlotAreaTerrainType.ROAD) { @@ -147,10 +151,12 @@ public class AugmentedUtils { } generationResult = true; } - primaryMask.setChunkObject(chunkObject); - primaryMask.setForceSync(true); - secondaryMask.setChunkObject(chunkObject); - secondaryMask.setForceSync(true); + if (chunkObject != null) { + primaryMask.setChunkObject(chunkObject); + } + if (chunkObject != null) { + secondaryMask.setChunkObject(chunkObject); + } ScopedQueueCoordinator scoped = new ScopedQueueCoordinator(secondaryMask, Location.at(world, blockX, 0, blockZ), @@ -158,8 +164,7 @@ public class AugmentedUtils { generator.generateChunk(scoped, area); generator.populateChunk(scoped, area); } - if (queue != null) { - queue.setForceSync(true); + if (enqueue) { queue.enqueue(); } return generationResult; diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java index 3955a00ee..0353210a6 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java @@ -42,6 +42,7 @@ import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.WorldUtil; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; @@ -247,6 +248,8 @@ public class HybridPlotManager extends ClassicPlotManager { final BiomeType biome = hybridPlotWorld.getPlotBiome(); final QueueCoordinator queue = hybridPlotWorld.getQueue(); + queue.setReadRegion(new CuboidRegion(plot.getExtendedBottomAbs().getBlockVector3(), + plot.getExtendedTopAbs().getBlockVector3())); queue.setChunkConsumer(blockVector2 -> { // If the chunk isn't near the edge and it isn't an augmented world we can just regen the whole chunk if (canRegen && ChunkUtil.isWholeChunk(pos1, pos2, blockVector2)) { diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index c54e494aa..11560e33c 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -161,7 +161,7 @@ public class HybridUtils { System.gc(); QueueCoordinator queue = area.getQueue(); - + queue.setReadRegion(region); queue.setChunkConsumer(blockVector2 -> { int X = blockVector2.getX(); int Z = blockVector2.getZ(); @@ -438,7 +438,6 @@ public class HybridUtils { if (!regenedRoad && Settings.DEBUG) { logger.info("[P2] Failed to regenerate roads"); } - chunkManager.unloadChunk(area.getWorldName(), chunk, true); } if (Settings.DEBUG) { logger.info("[P2] Cancelled road task"); @@ -500,15 +499,6 @@ public class HybridUtils { logger.error( "[P2] Error! Could not update '{}/region/r.{}.{}.mca' (Corrupt chunk?)", area.getWorldHash(), loc.getX(), loc.getZ()); - int sx = loc.getX() << 5; - int sz = loc.getZ() << 5; - for (int x = sx; x < sx + 32; x++) { - for (int z = sz; z < sz + 32; z++) { - chunkManager - .unloadChunk(area.getWorldName(), BlockVector2.at(x, z), - true); - } - } } TaskManager.runTaskLater(task, TaskTime.seconds(1L)); }); diff --git a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java index 26b30b0c4..df87be525 100644 --- a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java +++ b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java @@ -28,7 +28,6 @@ package com.plotsquared.core.inject.factory; import com.plotsquared.core.queue.ChunkCoordinator; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.world.World; -import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import java.util.Collection; @@ -37,8 +36,8 @@ import java.util.function.Consumer; public interface ChunkCoordinatorFactory { @Nonnull ChunkCoordinator create(final long maxIterationTime, final int initialBatchSize, - @NotNull final Consumer chunkConsumer, @NotNull final World world, - @NotNull final Collection requestedChunks, @NotNull final Runnable whenDone, - @NotNull final Consumer throwableConsumer); + @Nonnull final Consumer chunkConsumer, @Nonnull final World world, + @Nonnull final Collection requestedChunks, @Nonnull final Runnable whenDone, + @Nonnull final Consumer throwableConsumer, final boolean unloadAfter); } diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index 13ec128eb..a7bc5a033 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -3312,9 +3312,7 @@ public class Plot { Location pos2 = corners[1]; Location pos3 = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); - Location pos4 = - pos2.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); - regionManager.swap(pos1, pos2, pos3, pos4, this); + regionManager.swap(pos1, pos2, pos3, this); } } }.run(); diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index f60f43efa..cfb36ca65 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -27,12 +27,16 @@ package com.plotsquared.core.queue; import com.plotsquared.core.util.PatternUtil; import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.entity.EntityTypes; import javax.annotation.Nonnull; import java.util.concurrent.ConcurrentHashMap; @@ -53,6 +57,8 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { private int[] regenStart; private int[] regenEnd; private Consumer consumer = null; + private boolean unloadAfter = true; + private CuboidRegion readRegion = null; private GlobalBlockQueue globalBlockQueue; @@ -61,12 +67,6 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { this.modified = System.currentTimeMillis(); } - public LocalChunk getLocalChunk(int x, int z) { - return new LocalChunk(this, x, z) { - // Allow implementation-specific custom stuff here - }; - } - @Override public abstract BlockState getBlock(int x, int y, int z); @Override public final World getWorld() { @@ -132,12 +132,30 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return this.settingTiles; } + @Override public boolean setEntity(Entity entity) { + if (entity.getState() == null || entity.getState().getType() == EntityTypes.PLAYER) { + return false; + } + Location location = entity.getBlockLocation(); + LocalChunk chunk = getChunk(location.getBlockX() >> 4, location.getBlockZ() >> 4); + chunk.setEntity(location, entity.getState()); + return true; + } + + @Override public CuboidRegion getReadRegion() { + return this.readRegion; + } + + @Override public void setReadRegion(CuboidRegion readRegion) { + this.readRegion = readRegion; + } + @Override public void regenChunk(int x, int z) { regen = true; // There will never only be one nullified coordinate pair if (regenStart == null) { - regenStart = new int[]{x, z}; - regenEnd = new int[]{x, z}; + regenStart = new int[] {x, z}; + regenEnd = new int[] {x, z}; return; } if (x < regenStart[0]) { @@ -154,6 +172,14 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { } } + @Override public boolean isUnloadAfter() { + return this.unloadAfter; + } + + @Override public void setUnloadAfter(boolean unloadAfter) { + this.unloadAfter = unloadAfter; + } + public int[] getRegenStart() { return regenStart; } @@ -189,7 +215,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { BlockVector2 pair = BlockVector2.at(chunkX, chunkZ); lastWrappedChunk = this.blockChunks.get(pair); if (lastWrappedChunk == null) { - lastWrappedChunk = this.getLocalChunk(chunkX, chunkZ); + lastWrappedChunk = new LocalChunk(this, chunkX, chunkZ); LocalChunk previous = this.blockChunks.put(pair, lastWrappedChunk); if (previous == null) { return lastWrappedChunk; @@ -199,6 +225,4 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { } return lastWrappedChunk; } - - } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java index 861ccc8ed..068d61aea 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java @@ -30,6 +30,7 @@ import com.google.inject.Inject; import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory; import com.plotsquared.core.location.Location; import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; import org.jetbrains.annotations.NotNull; @@ -51,30 +52,32 @@ public class ChunkCoordinatorBuilder { }; private long maxIterationTime = 60; // A little over 1 tick; private int initialBatchSize = 4; + private boolean unloadAfter = true; + private CuboidRegion readRegion = null; @Inject public ChunkCoordinatorBuilder(@Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory) { this.chunkCoordinatorFactory = chunkCoordinatorFactory; } - @NotNull public ChunkCoordinatorBuilder inWorld(@NotNull final World world) { + @Nonnull public ChunkCoordinatorBuilder inWorld(@Nonnull final World world) { this.world = Preconditions.checkNotNull(world, "World may not be null"); return this; } - @NotNull public ChunkCoordinatorBuilder withChunk(@NotNull final BlockVector2 chunkLocation) { + @Nonnull public ChunkCoordinatorBuilder withChunk(@Nonnull final BlockVector2 chunkLocation) { this.requestedChunks .add(Preconditions.checkNotNull(chunkLocation, "Chunk location may not be null")); return this; } - @NotNull public ChunkCoordinatorBuilder withChunks( - @NotNull final Collection chunkLocations) { + @Nonnull public ChunkCoordinatorBuilder withChunks( + @Nonnull final Collection chunkLocations) { chunkLocations.forEach(this::withChunk); return this; } - @NotNull public ChunkCoordinatorBuilder withRegion(Location pos1, Location pos2) { + @Nonnull public ChunkCoordinatorBuilder withRegion(Location pos1, Location pos2) { final int p1x = pos1.getX(); final int p1z = pos1.getZ(); final int p2x = pos2.getX(); @@ -95,45 +98,50 @@ public class ChunkCoordinatorBuilder { return this; } - @NotNull public ChunkCoordinatorBuilder withConsumer( - @NotNull final Consumer chunkConsumer) { + @Nonnull public ChunkCoordinatorBuilder withConsumer( + @Nonnull final Consumer chunkConsumer) { this.chunkConsumer = Preconditions.checkNotNull(chunkConsumer, "Chunk consumer may not be null"); return this; } - @NotNull public ChunkCoordinatorBuilder withFinalAction(@NotNull final Runnable whenDone) { + @Nonnull public ChunkCoordinatorBuilder withFinalAction(@Nonnull final Runnable whenDone) { this.whenDone = Preconditions.checkNotNull(whenDone, "Final action may not be null"); return this; } - @NotNull public ChunkCoordinatorBuilder withMaxIterationTime(final long maxIterationTime) { + @Nonnull public ChunkCoordinatorBuilder withMaxIterationTime(final long maxIterationTime) { Preconditions.checkArgument(maxIterationTime > 0, "Max iteration time must be positive"); this.maxIterationTime = maxIterationTime; return this; } - @NotNull public ChunkCoordinatorBuilder withInitialBatchSize(final int initialBatchSize) { + @Nonnull public ChunkCoordinatorBuilder withInitialBatchSize(final int initialBatchSize) { Preconditions.checkArgument(initialBatchSize > 0, "Initial batch size must be positive"); this.initialBatchSize = initialBatchSize; return this; } - @NotNull public ChunkCoordinatorBuilder withThrowableConsumer( - @NotNull final Consumer throwableConsumer) { + @Nonnull public ChunkCoordinatorBuilder withThrowableConsumer( + @Nonnull final Consumer throwableConsumer) { this.throwableConsumer = Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null"); return this; } - @NotNull public ChunkCoordinator build() { + @Nonnull public ChunkCoordinatorBuilder unloadAfter(final boolean unloadAfter) { + this.unloadAfter = unloadAfter; + return this; + } + + @Nonnull public ChunkCoordinator build() { Preconditions.checkNotNull(this.world, "No world was supplied"); Preconditions.checkNotNull(this.chunkConsumer, "No chunk consumer was supplied"); Preconditions.checkNotNull(this.whenDone, "No final action was supplied"); Preconditions.checkNotNull(this.throwableConsumer, "No throwable consumer was supplied"); return chunkCoordinatorFactory .create(this.maxIterationTime, this.initialBatchSize, this.chunkConsumer, this.world, - this.requestedChunks, this.whenDone, this.throwableConsumer); + this.requestedChunks, this.whenDone, this.throwableConsumer, this.unloadAfter); } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index d63773ddd..dd7e0ae01 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -26,8 +26,10 @@ package com.plotsquared.core.queue; import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; @@ -113,6 +115,13 @@ public class DelegateQueueCoordinator extends QueueCoordinator { return false; } + @Override public boolean setEntity(Entity entity) { + if (parent != null) { + return parent.setEntity(entity); + } + return false; + } + @Override public void regenChunk(int x, int z) { if (parent != null) { parent.regenChunk(x, z); @@ -170,4 +179,31 @@ public class DelegateQueueCoordinator extends QueueCoordinator { parent.setChunkConsumer(consumer); } } + + @Override public CuboidRegion getReadRegion() { + if (parent != null) { + return parent.getReadRegion(); + } + return null; + } + + @Override public void setReadRegion(CuboidRegion readRegion) { + if (parent != null) { + parent.setReadRegion(readRegion); + } + } + + @Override public boolean isUnloadAfter() { + if (parent != null) { + return parent.isUnloadAfter(); + } + return false; + } + + @Override public void setUnloadAfter(boolean setUnloadAfter) { + if (parent != null) { + parent.setUnloadAfter(setUnloadAfter); + } + + } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java index e69c4f0d5..59a10f943 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java @@ -26,25 +26,27 @@ package com.plotsquared.core.queue; import com.plotsquared.core.util.ChunkUtil; -import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MathMan; import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import java.util.HashMap; public class LocalChunk { - private final BasicQueueCoordinator parent; + private final QueueCoordinator parent; private final int x; private final int z; private final BaseBlock[][] baseblocks; private final BiomeType[][] biomes; private final HashMap tiles = new HashMap<>(); + private final HashMap entities = new HashMap<>(); - public LocalChunk(BasicQueueCoordinator parent, int x, int z) { + public LocalChunk(QueueCoordinator parent, int x, int z) { this.parent = parent; this.x = x; this.z = z; @@ -52,7 +54,7 @@ public class LocalChunk { biomes = new BiomeType[16][]; } - public BasicQueueCoordinator getParent() { + public QueueCoordinator getParent() { return this.parent; } @@ -103,4 +105,12 @@ public class LocalChunk { public void setTile(final int x, final int y, final int z, final CompoundTag tag) { tiles.put(BlockVector3.at(x, y, z), tag); } + + public void setEntity(Location location, BaseEntity entity) { + this.entities.put(location, entity); + } + + public HashMap getEntities() { + return this.entities; + } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index e1161ab20..57569bd7f 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -30,8 +30,10 @@ import com.plotsquared.core.PlotSquared; import com.plotsquared.core.location.Location; import com.plotsquared.core.util.PatternUtil; import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; @@ -40,6 +42,7 @@ import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import java.util.List; import java.util.function.Consumer; public abstract class QueueCoordinator { @@ -108,6 +111,22 @@ public abstract class QueueCoordinator { public abstract boolean isSettingBiomes(); + public void addEntities(List entities) { + for (Entity e : entities) { + this.setEntity(e); + } + } + + public abstract boolean setEntity(Entity entity); + + public abstract CuboidRegion getReadRegion(); + + public abstract void setReadRegion(CuboidRegion readRegion); + + public abstract void setUnloadAfter(boolean unloadAfter); + + public abstract boolean isUnloadAfter(); + public abstract void regenChunk(int x, int z); public abstract World getWorld(); diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java index 27c6a6866..4c234b0c7 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java @@ -28,23 +28,12 @@ package com.plotsquared.core.queue; import com.sk89q.worldedit.world.World; public abstract class QueueProvider { - public static QueueProvider of(final Class primary, - final Class fallback) { + public static QueueProvider of(final Class primary) { return new QueueProvider() { - private boolean failed = false; - @Override public QueueCoordinator getNewQueue(World world) { - if (!failed) { - try { - return (QueueCoordinator) primary.getConstructors()[0].newInstance(world); - } catch (Throwable e) { - e.printStackTrace(); - failed = true; - } - } try { - return (QueueCoordinator) fallback.getConstructors()[0].newInstance(world); + return (QueueCoordinator) primary.getConstructors()[0].newInstance(world); } catch (Throwable e) { e.printStackTrace(); } diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java index e2e5c36e9..d9bfb4cd3 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java @@ -27,7 +27,6 @@ package com.plotsquared.core.util; import com.plotsquared.core.PlotSquared; import com.plotsquared.core.location.Location; -import com.plotsquared.core.plot.Plot; import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.task.RunnableVal; @@ -98,21 +97,4 @@ public abstract class ChunkManager { @Deprecated public abstract CompletableFuture loadChunk(String world, BlockVector2 loc, boolean force); - @Deprecated public abstract void unloadChunk(String world, BlockVector2 loc, boolean save); - - public Plot hasPlot(String world, BlockVector2 chunk) { - int x1 = chunk.getX() << 4; - int z1 = chunk.getZ() << 4; - int x2 = x1 + 15; - int z2 = z1 + 15; - Location bot = Location.at(world, x1, 0, z1); - Plot plot = bot.getOwnedPlotAbs(); - if (plot != null) { - return plot; - } - Location top = Location.at(world, x2, 0, z2); - plot = top.getOwnedPlotAbs(); - return plot; - } - } diff --git a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java index 228b62a51..a4f5682cd 100644 --- a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java @@ -25,24 +25,27 @@ */ package com.plotsquared.core.util; +import com.google.inject.Inject; import com.plotsquared.core.PlotSquared; -import com.plotsquared.core.inject.factory.ChunkCoordinatorBuilderFactory; import com.plotsquared.core.location.Location; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotManager; +import com.plotsquared.core.queue.BasicQueueCoordinator; +import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.queue.QueueCoordinator; -import com.plotsquared.core.util.task.RunnableVal; import com.plotsquared.core.util.task.TaskManager; -import com.plotsquared.core.util.task.TaskTime; +import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.regions.Region; +import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.File; import java.util.Collection; @@ -55,12 +58,9 @@ public abstract class RegionManager { LoggerFactory.getLogger("P2/" + RegionManager.class.getSimpleName()); public static RegionManager manager = null; - private final ChunkManager chunkManager; - - public RegionManager(@Nonnull final ChunkManager chunkManager, @Nonnull WorldUtil worldUtil, - @Nonnull ChunkCoordinatorBuilderFactory chunkCoordinatorBuilderFactory) { - this.chunkManager = chunkManager; - } + @Inject private WorldUtil worldUtil; + @Inject private ChunkManager chunkManager; + @Inject private GlobalBlockQueue blockQueue; public static BlockVector2 getRegion(Location location) { int x = location.getX() >> 9; @@ -68,46 +68,6 @@ public abstract class RegionManager { return BlockVector2.at(x, z); } - public void largeRegionTask(final String world, final CuboidRegion region, - final RunnableVal task, final Runnable whenDone) { - TaskManager.runTaskAsync(() -> { - HashSet chunks = new HashSet<>(); - Set mcrs = this.getChunkChunks(world); - for (BlockVector2 mcr : mcrs) { - int bx = mcr.getX() << 9; - int bz = mcr.getZ() << 9; - int tx = bx + 511; - int tz = bz + 511; - if (bx <= region.getMaximumPoint().getX() && tx >= region.getMinimumPoint().getX() - && bz <= region.getMaximumPoint().getZ() && tz >= region.getMinimumPoint() - .getZ()) { - for (int x = bx >> 4; x <= (tx >> 4); x++) { - int cbx = x << 4; - int ctx = cbx + 15; - if (cbx <= region.getMaximumPoint().getX() && ctx >= region - .getMinimumPoint().getX()) { - for (int z = bz >> 4; z <= (tz >> 4); z++) { - int cbz = z << 4; - int ctz = cbz + 15; - if (cbz <= region.getMaximumPoint().getZ() && ctz >= region - .getMinimumPoint().getZ()) { - chunks.add(BlockVector2.at(x, z)); - } - } - } - } - } - } - TaskManager.getPlatformImplementation() - .objectTask(chunks, new RunnableVal() { - @Override public void run(BlockVector2 value) { - chunkManager.loadChunk(world, value, false).thenRun(() -> task.run(value)); - } - }).thenAccept(ignore -> TaskManager.getPlatformImplementation() - .taskLater(whenDone, TaskTime.ticks(1L))); - }); - } - /** * 0 = Entity * 1 = Animal @@ -115,9 +75,6 @@ public abstract class RegionManager { * 3 = Mob * 4 = Boat * 5 = Misc - * - * @param plot - * @return */ public abstract int[] countEntities(Plot plot); @@ -146,10 +103,6 @@ public abstract class RegionManager { return chunks; } - public void deleteRegionFiles(String world, Collection chunks) { - deleteRegionFiles(world, chunks, null); - } - public void deleteRegionFiles(final String world, final Collection chunks, final Runnable whenDone) { TaskManager.runTaskAsync(() -> { @@ -167,16 +120,10 @@ public abstract class RegionManager { }); } - public boolean setCuboids(final PlotArea area, final Set regions, - final Pattern blocks, int minY, int maxY) { - return setCuboids(area, regions, blocks, minY, maxY, null); - } - - public boolean setCuboids(final PlotArea area, final Set regions, final Pattern blocks, int minY, int maxY, @Nullable QueueCoordinator queue) { boolean enqueue = false; - if(queue == null) { + if (queue == null) { queue = area.getQueue(); enqueue = true; } @@ -209,27 +156,116 @@ public abstract class RegionManager { /** * Copy a region to a new location (in the same world) */ - public abstract boolean copyRegion(Location pos1, Location pos2, Location newPos, - Runnable whenDone); + public boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, + final Runnable whenDone) { + final int relX = newPos.getX() - pos1.getX(); + final int relZ = newPos.getZ() - pos1.getZ(); + final com.sk89q.worldedit.world.World oldWorld = worldUtil.getWeWorld(pos1.getWorldName()); + final com.sk89q.worldedit.world.World newWorld = + worldUtil.getWeWorld(newPos.getWorldName()); + final QueueCoordinator copyFrom = blockQueue.getNewQueue(oldWorld); + final BasicQueueCoordinator copyTo = + (BasicQueueCoordinator) blockQueue.getNewQueue(newWorld); + copyFromTo(pos1, pos2, relX, relZ, oldWorld, copyFrom, copyTo, false); + copyFrom.setCompleteTask(copyTo::enqueue); + copyFrom.setReadRegion(new CuboidRegion(BlockVector3.at(pos1.getX(), 0, pos1.getZ()), + BlockVector3.at(pos2.getX(), 0, pos2.getZ()))); + copyTo.setCompleteTask(whenDone); + copyFrom.enqueue(); + return true; + } /** * Assumptions:
* - pos1 and pos2 are in the same plot
* It can be harmful to the world if parameters outside this scope are provided - * - * @param pos1 - * @param pos2 - * @param whenDone - * @return */ public abstract boolean regenerateRegion(Location pos1, Location pos2, boolean ignoreAugment, Runnable whenDone); public abstract void clearAllEntities(Location pos1, Location pos2); - public abstract void swap(Location bot1, Location top1, Location bot2, Location top2, - Runnable whenDone); + public void swap(Location pos1, Location pos2, Location swapPos, final Runnable whenDone) { + int relX = swapPos.getX() - pos1.getX(); + int relZ = swapPos.getZ() - pos1.getZ(); - public abstract void setBiome(CuboidRegion region, int extendBiome, BiomeType biome, - String world, Runnable whenDone); + World world1 = worldUtil.getWeWorld(pos1.getWorldName()); + World world2 = worldUtil.getWeWorld(swapPos.getWorldName()); + + QueueCoordinator fromQueue1 = blockQueue.getNewQueue(world1); + QueueCoordinator fromQueue2 = blockQueue.getNewQueue(world2); + fromQueue1.setUnloadAfter(false); + fromQueue2.setUnloadAfter(false); + fromQueue1.setReadRegion(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3())); + fromQueue2.setReadRegion(new CuboidRegion(swapPos.getBlockVector3(), BlockVector3 + .at(swapPos.getX() + pos2.getX() - pos1.getX(), 0, + swapPos.getZ() + pos2.getZ() - pos1.getZ()))); + QueueCoordinator toQueue1 = blockQueue.getNewQueue(world1); + QueueCoordinator toQueue2 = blockQueue.getNewQueue(world2); + + copyFromTo(pos1, pos2, relX, relZ, world1, fromQueue1, toQueue2, true); + copyFromTo(pos1, pos2, relX, relZ, world1, fromQueue2, toQueue1, true); + fromQueue1.setCompleteTask(fromQueue2::enqueue); + fromQueue2.setCompleteTask(toQueue1::enqueue); + toQueue1.setCompleteTask(toQueue2::enqueue); + toQueue2.setCompleteTask(whenDone); + } + + private void copyFromTo(Location pos1, Location pos2, int relX, int relZ, World world1, + QueueCoordinator fromQueue, QueueCoordinator toQueue, boolean removeEntities) { + fromQueue.setChunkConsumer(chunk -> { + int cx = chunk.getX(); + int cz = chunk.getZ(); + int cbx = cx << 4; + int cbz = cz << 4; + int bx = Math.max(pos1.getX() & 15, 0); + int bz = Math.max(pos1.getZ() & 15, 0); + int tx = Math.min(pos2.getX() & 15, 15); + int tz = Math.min(pos2.getZ() & 15, 15); + for (int y = 0; y < 256; y++) { + for (int x = bx; x <= tx; x++) { + for (int z = bz; z <= tz; z++) { + int rx = cbx + x; + int rz = cbz + z; + BlockVector3 loc = BlockVector3.at(rx, y, rz); + toQueue.setBlock(rx + relX, y, rz + relZ, world1.getFullBlock(loc)); + toQueue.setBiome(rx + relX, y, rz + relZ, world1.getBiome(loc)); + } + } + } + Region region = new CuboidRegion(BlockVector3.at(cbx + bx, 0, cbz + bz), + BlockVector3.at(cbx + tx, 255, cbz + tz)); + toQueue.addEntities(world1.getEntities(region)); + if (removeEntities) { + for (Entity entity : world1.getEntities(region)) { + entity.remove(); + } + } + }); + } + + public void setBiome(final CuboidRegion region, final int extendBiome, final BiomeType biome, + final String world, final Runnable whenDone) { + Location pos1 = Location.at(world, region.getMinimumPoint().getX() - extendBiome, + region.getMinimumPoint().getY(), region.getMinimumPoint().getZ() - extendBiome); + Location pos2 = Location.at(world, region.getMaximumPoint().getX() + extendBiome, + region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome); + final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world)); + + final int minX = pos1.getX(); + final int minZ = pos1.getZ(); + final int maxX = pos2.getX(); + final int maxZ = pos2.getZ(); + queue.setReadRegion(region); + queue.setChunkConsumer(blockVector2 -> { + final int cx = blockVector2.getX() << 4; + final int cz = blockVector2.getZ() << 4; + WorldUtil + .setBiome(world, Math.max(minX, cx), Math.max(minZ, cz), Math.min(maxX, cx + 15), + Math.min(maxZ, cz + 15), biome); + worldUtil.refreshChunk(blockVector2.getBlockX(), blockVector2.getBlockZ(), world); + }); + queue.setCompleteTask(whenDone); + queue.enqueue(); + } } diff --git a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java index 0381945fa..1373562da 100644 --- a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java +++ b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java @@ -330,7 +330,8 @@ public abstract class SchematicHandler { final int bcz = p1z >> 4; final int tcx = p2x >> 4; final int tcz = p2z >> 4; - + queue.setReadRegion( + new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3())); queue.setChunkConsumer(blockVector2 -> { int x = blockVector2.getX(); int z = blockVector2.getZ(); diff --git a/build.gradle b/build.gradle index eacbc0fc2..d855d1ef3 100644 --- a/build.gradle +++ b/build.gradle @@ -81,7 +81,7 @@ subprojects { subproject -> dependencies { compile group: 'org.json', name: 'json', version: '20200518' - implementation("com.sk89q.worldedit:worldedit-core:7.0.0") { + implementation("com.sk89q.worldedit:worldedit-core:7.2.0-SNAPSHOT") { exclude(module: "bukkit-classloader-check") exclude(module: "mockito-core") exclude(module: "dummypermscompat") From c3322021d09d169bbc6f65f28d4f22e3257cc81d Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Thu, 23 Jul 2020 18:02:29 +0100 Subject: [PATCH 35/49] mavenLocal, poms --- Bukkit/build.gradle | 2 +- Bukkit/pom.xml | 6 +++--- Core/pom.xml | 2 +- build.gradle | 1 + 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index e752aca5f..1bf48750c 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -2,6 +2,7 @@ plugins { id "com.github.johnrengelman.shadow" } repositories { + mavenLocal() maven { url = "https://hub.spigotmc.org/nexus/content/repositories/snapshots/" } maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" } maven { url = "https://jitpack.io" } @@ -14,7 +15,6 @@ repositories { maven { url = "https://ci.ender.zone/plugin/repository/everything/" } maven { url = "https://mvn.intellectualsites.com/content/repositories/snapshots" } maven { url = "https://repo.wea-ondara.net/repository/public/" } - mavenLocal() } diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index d4848ae84..223190636 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -39,7 +39,7 @@ com.sk89q.worldedit worldedit-bukkit - 7.1.0 + 7.2.0-SNAPSHOT compile @@ -51,7 +51,7 @@ io.papermc paperlib - 1.0.2 + 1.0.4 compile @@ -93,7 +93,7 @@ com.sk89q.worldedit worldedit-core - 7.0.0 + 7.2.0-SNAPSHOT runtime diff --git a/Core/pom.xml b/Core/pom.xml index ac6a4ef60..272b95508 100644 --- a/Core/pom.xml +++ b/Core/pom.xml @@ -45,7 +45,7 @@ com.sk89q.worldedit worldedit-core - 7.0.0 + 7.2.0-SNAPSHOT runtime diff --git a/build.gradle b/build.gradle index d855d1ef3..7c710c29f 100644 --- a/build.gradle +++ b/build.gradle @@ -114,6 +114,7 @@ subprojects { subproject -> } repositories { + mavenLocal() mavenCentral() maven { url = "https://maven.enginehub.org/repo/" } maven { url = "https://repo.maven.apache.org/maven2" } From 420e38beadf9bd22826d4312ecd40fb42354538e Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Thu, 23 Jul 2020 18:07:23 +0100 Subject: [PATCH 36/49] idek? --- .../java/com/plotsquared/core/queue/BasicQueueCoordinator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index cfb36ca65..bbaffc6df 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -136,7 +136,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { if (entity.getState() == null || entity.getState().getType() == EntityTypes.PLAYER) { return false; } - Location location = entity.getBlockLocation(); + Location location = entity.getLocation(); LocalChunk chunk = getChunk(location.getBlockX() >> 4, location.getBlockZ() >> 4); chunk.setEntity(location, entity.getState()); return true; From 2cfb64606525a6deffdd659e9168156629dc614b Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Thu, 23 Jul 2020 18:11:52 +0100 Subject: [PATCH 37/49] Javadoc no fun --- Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java index fc73c7ba1..d60cb0f6b 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java @@ -119,12 +119,12 @@ public class ChunkUtil { } /** - * Returns true if the region pos1 -> pos2 contains the chunk + * Returns true if the region pos1-pos2 contains the chunk * * @param pos1 Region minimum point * @param pos2 Region maximum point * @param chunk BlockVector2 of chunk coordinates - * @return true if the region pos1 -> pos2 contains the chunk + * @return true if the region pos1-pos2 contains the chunk */ public static boolean isWholeChunk(Location pos1, Location pos2, BlockVector2 chunk) { int x1 = pos1.getX(); From d906a85095d5f30011cdb4d967f799c70e36fc47 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 24 Jul 2020 12:18:36 +0100 Subject: [PATCH 38/49] Fix some issues I caused with Guice --- Bukkit/pom.xml | 2 +- .../bukkit/util/BukkitRegionManager.java | 38 +--- .../plotsquared/bukkit/util/BukkitUtil.java | 130 +++++++------ .../com/plotsquared/core/command/Debug.java | 9 +- .../com/plotsquared/core/command/Trim.java | 2 +- .../core/generator/HybridUtils.java | 2 +- .../plotsquared/core/util/RegionManager.java | 25 --- .../com/plotsquared/core/util/WorldUtil.java | 172 ++++++++++-------- build.gradle | 4 +- 9 files changed, 181 insertions(+), 203 deletions(-) diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index 223190636..b12a2d969 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -27,7 +27,7 @@ com.plotsquared PlotSquared-Core - 5.12.5 + 6.0.0-SUPER-SNAPSHOT compile diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java index 23ed242d7..7309952a2 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java @@ -27,7 +27,6 @@ package com.plotsquared.bukkit.util; import com.google.inject.Inject; import com.google.inject.Singleton; -import com.plotsquared.bukkit.BukkitPlatform; import com.plotsquared.core.generator.AugmentedUtils; import com.plotsquared.core.location.Location; import com.plotsquared.core.location.PlotLoc; @@ -40,13 +39,10 @@ import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.RegionUtil; -import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.entity.EntityCategories; import com.plotsquared.core.util.task.RunnableVal; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.BukkitWorld; -import com.sk89q.worldedit.math.BlockVector2; -import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockTypes; @@ -62,9 +58,7 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashSet; import java.util.List; -import java.util.Objects; import java.util.Set; -import java.util.concurrent.Semaphore; import static com.plotsquared.core.util.entity.EntityCategories.CAP_ANIMAL; import static com.plotsquared.core.util.entity.EntityCategories.CAP_ENTITY; @@ -78,38 +72,8 @@ public class BukkitRegionManager extends RegionManager { private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitRegionManager.class.getSimpleName()); - @Inject private WorldUtil worldUtil; @Inject private GlobalBlockQueue blockQueue; - @Override public Set getChunkChunks(String world) { - Set chunks = super.getChunkChunks(world); - if (Bukkit.isPrimaryThread()) { - for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)).getLoadedChunks()) { - BlockVector2 loc = BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5); - chunks.add(loc); - } - } else { - final Semaphore semaphore = new Semaphore(1); - try { - semaphore.acquire(); - Bukkit.getScheduler() - .runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> { - for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)) - .getLoadedChunks()) { - BlockVector2 loc = - BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5); - chunks.add(loc); - } - semaphore.release(); - }); - semaphore.acquireUninterruptibly(); - } catch (final Exception e) { - e.printStackTrace(); - } - } - return chunks; - } - @Override public boolean handleClear(Plot plot, Runnable whenDone, PlotManager manager) { return false; } @@ -189,7 +153,7 @@ public class BukkitRegionManager extends RegionManager { return count; } - @Override @Inject public boolean regenerateRegion(final Location pos1, final Location pos2, + @Override public boolean regenerateRegion(final Location pos1, final Location pos2, final boolean ignoreAugment, final Runnable whenDone) { final BukkitWorld world = new BukkitWorld((World) pos1.getWorld()); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 90e3bcff8..659b6a7d7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -25,7 +25,6 @@ */ package com.plotsquared.bukkit.util; -import com.google.inject.Inject; import com.google.inject.Singleton; import com.plotsquared.bukkit.BukkitPlatform; import com.plotsquared.bukkit.player.BukkitPlayer; @@ -36,7 +35,6 @@ import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.util.BlockUtil; import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.PlayerManager; -import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.StringComparison; import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.task.TaskManager; @@ -102,6 +100,7 @@ import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.concurrent.Semaphore; import java.util.function.Consumer; import java.util.function.IntConsumer; import java.util.stream.Stream; @@ -110,13 +109,10 @@ import java.util.stream.Stream; @Singleton public class BukkitUtil extends WorldUtil { - private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitUtil.class.getSimpleName()); + private static final Logger logger = + LoggerFactory.getLogger("P2/" + BukkitUtil.class.getSimpleName()); private final Collection tileEntityTypes = new HashSet<>(); - @Inject public BukkitUtil(@Nonnull final RegionManager regionManager) { - super(regionManager); - } - /** * Get a {@link PlotPlayer} from an {@link OfflinePlayer}. If the player is * online, it returns a complete player. If the player is offline, it creates @@ -156,7 +152,8 @@ public class BukkitUtil extends WorldUtil { */ @Nonnull public static Location adapt(@Nonnull final org.bukkit.Location location) { return Location.at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), - MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ())); + MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), + MathMan.roundInt(location.getZ())); } /** @@ -168,8 +165,8 @@ public class BukkitUtil extends WorldUtil { */ @Nonnull public static Location adaptComplete(@Nonnull final org.bukkit.Location location) { return Location.at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), - MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), location.getYaw(), - location.getPitch()); + MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), + MathMan.roundInt(location.getZ()), location.getYaw(), location.getPitch()); } /** @@ -180,8 +177,8 @@ public class BukkitUtil extends WorldUtil { * @return Bukkit location */ @Nonnull public static org.bukkit.Location adapt(@Nonnull final Location location) { - return new org.bukkit.Location((World) location.getWorld().getPlatformWorld(), location.getX(), - location.getY(), location.getZ()); + return new org.bukkit.Location((World) location.getWorld().getPlatformWorld(), + location.getX(), location.getY(), location.getZ()); } /** @@ -196,23 +193,23 @@ public class BukkitUtil extends WorldUtil { private static void ensureLoaded(@Nonnull final String world, final int x, final int z, @Nonnull final Consumer chunkConsumer) { - PaperLib.getChunkAtAsync(Objects.requireNonNull(getWorld(world)), - x >> 4, z >> 4, true) + PaperLib.getChunkAtAsync(Objects.requireNonNull(getWorld(world)), x >> 4, z >> 4, true) .thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); } - private static void ensureLoaded(@Nonnull final Location location, @Nonnull final Consumer chunkConsumer) { + private static void ensureLoaded(@Nonnull final Location location, + @Nonnull final Consumer chunkConsumer) { PaperLib.getChunkAtAsync(adapt(location), true) .thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); } private static void ensureMainThread(@Nonnull final Consumer consumer, - @Nonnull final T value) { + @Nonnull final T value) { if (Bukkit.isPrimaryThread()) { consumer.accept(value); } else { - Bukkit.getScheduler() - .runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> consumer.accept(value)); + Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), + () -> consumer.accept(value)); } } @@ -228,8 +225,8 @@ public class BukkitUtil extends WorldUtil { return PlotPlayer.wrap(Bukkit.getOfflinePlayer(uuid)); } - @Override public boolean isBlockSame(@Nonnull final BlockState block1, - @Nonnull final BlockState block2) { + @Override + public boolean isBlockSame(@Nonnull final BlockState block1, @Nonnull final BlockState block2) { if (block1.equals(block2)) { return true; } @@ -242,19 +239,18 @@ public class BukkitUtil extends WorldUtil { return getWorld(worldName) != null; } - @Override public void getBiome(@Nonnull final String world, final int x, - final int z, @Nonnull final Consumer result) { + @Override public void getBiome(@Nonnull final String world, final int x, final int z, + @Nonnull final Consumer result) { ensureLoaded(world, x, z, chunk -> result.accept(BukkitAdapter.adapt(getWorld(world).getBiome(x, z)))); } - @Override @Nonnull public BiomeType getBiomeSynchronous(@Nonnull final String world, - final int x, final int z) { + @Override @Nonnull + public BiomeType getBiomeSynchronous(@Nonnull final String world, final int x, final int z) { return BukkitAdapter.adapt(Objects.requireNonNull(getWorld(world)).getBiome(x, z)); } - @Override - public void getHighestBlock(@Nonnull final String world, final int x, final int z, + @Override public void getHighestBlock(@Nonnull final String world, final int x, final int z, @Nonnull final IntConsumer result) { ensureLoaded(world, x, z, chunk -> { final World bukkitWorld = Objects.requireNonNull(getWorld(world)); @@ -282,8 +278,7 @@ public class BukkitUtil extends WorldUtil { } @Override @Nonnegative - public int getHighestBlockSynchronous(@Nonnull final String world, - final int x, final int z) { + public int getHighestBlockSynchronous(@Nonnull final String world, final int x, final int z) { final World bukkitWorld = Objects.requireNonNull(getWorld(world)); // Skip top and bottom block int air = 1; @@ -305,8 +300,7 @@ public class BukkitUtil extends WorldUtil { return bukkitWorld.getMaxHeight() - 1; } - @Override @Nonnull - public String[] getSignSynchronous(@Nonnull final Location location) { + @Override @Nonnull public String[] getSignSynchronous(@Nonnull final Location location) { Block block = Objects.requireNonNull(getWorld(location.getWorldName())) .getBlockAt(location.getX(), location.getY(), location.getZ()); try { @@ -323,8 +317,7 @@ public class BukkitUtil extends WorldUtil { return new String[0]; } - @Override @Nonnull - public Location getSpawn(@Nonnull final String world) { + @Override @Nonnull public Location getSpawn(@Nonnull final String world) { final org.bukkit.Location temp = getWorld(world).getSpawnLocation(); return Location .at(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), @@ -392,9 +385,8 @@ public class BukkitUtil extends WorldUtil { } @Override - public void setBiomes(@Nonnull final String worldName, - @Nonnull final CuboidRegion region, - @Nonnull final BiomeType biomeType) { + public void setBiomes(@Nonnull final String worldName, @Nonnull final CuboidRegion region, + @Nonnull final BiomeType biomeType) { final World world = getWorld(worldName); if (world == null) { logger.warn("[P2] An error occured while setting the biome because the world was null", @@ -412,7 +404,8 @@ public class BukkitUtil extends WorldUtil { } } - @Override @Nonnull public com.sk89q.worldedit.world.World getWeWorld(@Nonnull final String world) { + @Override @Nonnull + public com.sk89q.worldedit.world.World getWeWorld(@Nonnull final String world) { return new BukkitWorld(Bukkit.getWorld(world)); } @@ -420,15 +413,14 @@ public class BukkitUtil extends WorldUtil { Bukkit.getWorld(world).refreshChunk(x, z); } - @Override - public void getBlock(@Nonnull final Location location, - @Nonnull final Consumer result) { + @Override public void getBlock(@Nonnull final Location location, + @Nonnull final Consumer result) { ensureLoaded(location, chunk -> { final World world = getWorld(location.getWorldName()); final Block block = Objects.requireNonNull(world) .getBlockAt(location.getX(), location.getY(), location.getZ()); - result.accept(Objects.requireNonNull(BukkitAdapter - .asBlockType(block.getType())).getDefaultState()); + result.accept(Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())) + .getDefaultState()); }); } @@ -436,33 +428,28 @@ public class BukkitUtil extends WorldUtil { final World world = getWorld(location.getWorldName()); final Block block = Objects.requireNonNull(world) .getBlockAt(location.getX(), location.getY(), location.getZ()); - return Objects.requireNonNull(BukkitAdapter - .asBlockType(block.getType())).getDefaultState(); + return Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())).getDefaultState(); } @Override @Nonnegative public double getHealth(@Nonnull final PlotPlayer player) { - return Objects.requireNonNull(Bukkit - .getPlayer(player.getUUID())).getHealth(); + return Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).getHealth(); } @Override @Nonnegative public int getFoodLevel(@Nonnull final PlotPlayer player) { - return Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())) - .getFoodLevel(); + return Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).getFoodLevel(); } - @Override public void setHealth(@Nonnull final PlotPlayer player, - @Nonnegative final double health) { - Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())) - .setHealth(health); + @Override + public void setHealth(@Nonnull final PlotPlayer player, @Nonnegative final double health) { + Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).setHealth(health); } @Override public void setFoodLevel(@Nonnull final PlotPlayer player, - @Nonnegative final int foodLevel) { + @Nonnegative final int foodLevel) { Bukkit.getPlayer(player.getUUID()).setFoodLevel(foodLevel); } - @Override @Nonnull - public Set getTypesInCategory( + @Override @Nonnull public Set getTypesInCategory( @Nonnull final String category) { final Collection> allowedInterfaces = new HashSet<>(); switch (category) { @@ -567,11 +554,38 @@ public class BukkitUtil extends WorldUtil { } @Override @Nonnegative - public int getTileEntityCount(@Nonnull final String world, - @Nonnull final BlockVector2 chunk) { + public int getTileEntityCount(@Nonnull final String world, @Nonnull final BlockVector2 chunk) { return Objects.requireNonNull(getWorld(world)). - getChunkAt(chunk.getBlockX(), chunk.getBlockZ()) - .getTileEntities().length; + getChunkAt(chunk.getBlockX(), chunk.getBlockZ()).getTileEntities().length; + } + + @Override public Set getChunkChunks(String world) { + Set chunks = super.getChunkChunks(world); + if (Bukkit.isPrimaryThread()) { + for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)).getLoadedChunks()) { + BlockVector2 loc = BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5); + chunks.add(loc); + } + } else { + final Semaphore semaphore = new Semaphore(1); + try { + semaphore.acquire(); + Bukkit.getScheduler() + .runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> { + for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)) + .getLoadedChunks()) { + BlockVector2 loc = + BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5); + chunks.add(loc); + } + semaphore.release(); + }); + semaphore.acquireUninterruptibly(); + } catch (final Exception e) { + e.printStackTrace(); + } + } + return chunks; } } diff --git a/Core/src/main/java/com/plotsquared/core/command/Debug.java b/Core/src/main/java/com/plotsquared/core/command/Debug.java index d8e591313..3e1ef1204 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Debug.java +++ b/Core/src/main/java/com/plotsquared/core/command/Debug.java @@ -33,6 +33,7 @@ import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.StringMan; +import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.entity.EntityCategories; import com.plotsquared.core.util.entity.EntityCategory; import com.plotsquared.core.util.query.PlotQuery; @@ -57,12 +58,12 @@ public class Debug extends SubCommand { private static final Logger logger = LoggerFactory.getLogger("P2/" + Debug.class.getSimpleName()); private final PlotAreaManager plotAreaManager; - private final RegionManager regionManager; + private final WorldUtil worldUtil; @Inject public Debug(@Nonnull final PlotAreaManager plotAreaManager, - @Nonnull final RegionManager regionManager) { + @Nonnull final WorldUtil worldUtil) { this.plotAreaManager = plotAreaManager; - this.regionManager = regionManager; + this.worldUtil = worldUtil; } @Override public boolean onCommand(PlotPlayer player, String[] args) { @@ -78,7 +79,7 @@ public class Debug extends SubCommand { final long start = System.currentTimeMillis(); MainUtil.sendMessage(player, "Fetching loaded chunks..."); TaskManager.runTaskAsync(() -> MainUtil.sendMessage(player, - "Loaded chunks: " + this.regionManager.getChunkChunks(player.getLocation().getWorldName()).size() + "(" + ( + "Loaded chunks: " + this.worldUtil.getChunkChunks(player.getLocation().getWorldName()).size() + "(" + ( System.currentTimeMillis() - start) + "ms) using thread: " + Thread .currentThread().getName())); return true; diff --git a/Core/src/main/java/com/plotsquared/core/command/Trim.java b/Core/src/main/java/com/plotsquared/core/command/Trim.java index 4a79d4098..02eda501c 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Trim.java +++ b/Core/src/main/java/com/plotsquared/core/command/Trim.java @@ -98,7 +98,7 @@ public class Trim extends SubCommand { if (ExpireManager.IMP != null) { plots.removeAll(ExpireManager.IMP.getPendingExpired()); } - result.value1 = new HashSet<>(PlotSquared.platform().getRegionManager().getChunkChunks(world)); + result.value1 = new HashSet<>(PlotSquared.platform().getWorldUtil().getChunkChunks(world)); result.value2 = new HashSet<>(); MainUtil.sendMessage(null, " - MCA #: " + result.value1.size()); MainUtil.sendMessage(null, " - CHUNKS: " + (result.value1.size() * 1024) + " (max)"); diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index 11560e33c..34928a014 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -406,7 +406,7 @@ public class HybridUtils { return false; } HybridUtils.UPDATE = true; - Set regions = this.regionManager.getChunkChunks(area.getWorldName()); + Set regions = this.worldUtil.getChunkChunks(area.getWorldName()); return scheduleRoadUpdate(area, regions, extend, new HashSet<>()); } diff --git a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java index a4f5682cd..f16420021 100644 --- a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java @@ -78,31 +78,6 @@ public abstract class RegionManager { */ public abstract int[] countEntities(Plot plot); - public Set getChunkChunks(String world) { - File folder = - new File(PlotSquared.platform().getWorldContainer(), world + File.separator + "region"); - File[] regionFiles = folder.listFiles(); - if (regionFiles == null) { - throw new RuntimeException( - "Could not find worlds folder: " + folder + " ? (no read access?)"); - } - HashSet chunks = new HashSet<>(); - for (File file : regionFiles) { - String name = file.getName(); - if (name.endsWith("mca")) { - String[] split = name.split("\\."); - try { - int x = Integer.parseInt(split[1]); - int z = Integer.parseInt(split[2]); - BlockVector2 loc = BlockVector2.at(x, z); - chunks.add(loc); - } catch (NumberFormatException ignored) { - } - } - } - return chunks; - } - public void deleteRegionFiles(final String world, final Collection chunks, final Runnable whenDone) { TaskManager.runTaskAsync(() -> { diff --git a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java index 03f6728ca..4d566aac9 100644 --- a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java @@ -53,6 +53,7 @@ import java.io.IOException; import java.io.OutputStream; import java.net.URL; import java.util.Collection; +import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; @@ -65,20 +66,14 @@ import java.util.zip.ZipOutputStream; public abstract class WorldUtil { - private final RegionManager regionManager; - - public WorldUtil(@Nonnull final RegionManager regionManager) { - this.regionManager = regionManager; - } - /** * Set the biome in a region * * @param world World name - * @param p1x Min X - * @param p1z Min Z - * @param p2x Max X - * @param p2z Max Z + * @param p1x Min X + * @param p1z Min Z + * @param p2x Max X + * @param p2z Max Z * @param biome Biome */ public static void setBiome(String world, int p1x, int p1z, int p2x, int p2z, BiomeType biome) { @@ -196,8 +191,8 @@ public abstract class WorldUtil { * @return Result * @deprecated Use {@link #getHighestBlock(String, int, int, IntConsumer)} */ - @Deprecated @Nonnegative - public abstract int getHighestBlockSynchronous(@Nonnull String world, int x, int z); + @Deprecated @Nonnegative public abstract int getHighestBlockSynchronous(@Nonnull String world, + int x, int z); /** * Set the text in a sign @@ -232,81 +227,82 @@ public abstract class WorldUtil { /** * Refresh (resend) chunk to player. Usually after setting the biome * - * @param x Chunk x location - * @param z Chunk z location + * @param x Chunk x location + * @param z Chunk z location * @param world World of the chunk */ public abstract void refreshChunk(int x, int z, String world); public void upload(@Nonnull final Plot plot, @Nullable final UUID uuid, @Nullable final String file, @Nonnull final RunnableVal whenDone) { - plot.getHome(home -> SchematicHandler.upload(uuid, file, "zip", new RunnableVal() { - @Override public void run(OutputStream output) { - try (final ZipOutputStream zos = new ZipOutputStream(output)) { - File dat = getDat(plot.getWorldName()); - Location spawn = getSpawn(plot.getWorldName()); - if (dat != null) { - ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName()); - zos.putNextEntry(ze); - try (NBTInputStream nis = new NBTInputStream( - new GZIPInputStream(new FileInputStream(dat)))) { - CompoundTag tag = (CompoundTag) nis.readNamedTag().getTag(); - CompoundTag data = (CompoundTag) tag.getValue().get("Data"); - Map map = ReflectionUtils.getMap(data.getValue()); - map.put("SpawnX", new IntTag(home.getX())); - map.put("SpawnY", new IntTag(home.getY())); - map.put("SpawnZ", new IntTag(home.getZ())); - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - try (NBTOutputStream out = new NBTOutputStream( - new GZIPOutputStream(baos, true))) { - //TODO Find what this should be called - out.writeNamedTag("Schematic????", tag); - } - zos.write(baos.toByteArray()); - } - } - } - setSpawn(spawn); - byte[] buffer = new byte[1024]; - for (Plot current : plot.getConnectedPlots()) { - Location bot = current.getBottomAbs(); - Location top = current.getTopAbs(); - int brx = bot.getX() >> 9; - int brz = bot.getZ() >> 9; - int trx = top.getX() >> 9; - int trz = top.getZ() >> 9; - Set files = regionManager.getChunkChunks(bot.getWorldName()); - for (BlockVector2 mca : files) { - if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz - && mca.getZ() <= trz) { - final File file = - getMcr(plot.getWorldName(), mca.getX(), mca.getZ()); - if (file != null) { - //final String name = "r." + (x - cx) + "." + (z - cz) + ".mca"; - String name = file.getName(); - final ZipEntry ze = new ZipEntry( - "world" + File.separator + "region" + File.separator - + name); - zos.putNextEntry(ze); - try (FileInputStream in = new FileInputStream(file)) { - int len; - while ((len = in.read(buffer)) > 0) { - zos.write(buffer, 0, len); - } + plot.getHome( + home -> SchematicHandler.upload(uuid, file, "zip", new RunnableVal() { + @Override public void run(OutputStream output) { + try (final ZipOutputStream zos = new ZipOutputStream(output)) { + File dat = getDat(plot.getWorldName()); + Location spawn = getSpawn(plot.getWorldName()); + if (dat != null) { + ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName()); + zos.putNextEntry(ze); + try (NBTInputStream nis = new NBTInputStream( + new GZIPInputStream(new FileInputStream(dat)))) { + CompoundTag tag = (CompoundTag) nis.readNamedTag().getTag(); + CompoundTag data = (CompoundTag) tag.getValue().get("Data"); + Map map = ReflectionUtils.getMap(data.getValue()); + map.put("SpawnX", new IntTag(home.getX())); + map.put("SpawnY", new IntTag(home.getY())); + map.put("SpawnZ", new IntTag(home.getZ())); + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + try (NBTOutputStream out = new NBTOutputStream( + new GZIPOutputStream(baos, true))) { + //TODO Find what this should be called + out.writeNamedTag("Schematic????", tag); } - zos.closeEntry(); + zos.write(baos.toByteArray()); } } } + setSpawn(spawn); + byte[] buffer = new byte[1024]; + for (Plot current : plot.getConnectedPlots()) { + Location bot = current.getBottomAbs(); + Location top = current.getTopAbs(); + int brx = bot.getX() >> 9; + int brz = bot.getZ() >> 9; + int trx = top.getX() >> 9; + int trz = top.getZ() >> 9; + Set files = getChunkChunks(bot.getWorldName()); + for (BlockVector2 mca : files) { + if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz + && mca.getZ() <= trz) { + final File file = + getMcr(plot.getWorldName(), mca.getX(), mca.getZ()); + if (file != null) { + //final String name = "r." + (x - cx) + "." + (z - cz) + ".mca"; + String name = file.getName(); + final ZipEntry ze = new ZipEntry( + "world" + File.separator + "region" + File.separator + + name); + zos.putNextEntry(ze); + try (FileInputStream in = new FileInputStream(file)) { + int len; + while ((len = in.read(buffer)) > 0) { + zos.write(buffer, 0, len); + } + } + zos.closeEntry(); + } + } + } + } + zos.closeEntry(); + zos.flush(); + zos.finish(); + } catch (IOException e) { + e.printStackTrace(); } - zos.closeEntry(); - zos.flush(); - zos.finish(); - } catch (IOException e) { - e.printStackTrace(); } - } - }, whenDone)); + }, whenDone)); } @Nullable final File getDat(@Nonnull final String world) { @@ -328,6 +324,32 @@ public abstract class WorldUtil { return null; } + + public Set getChunkChunks(String world) { + File folder = + new File(PlotSquared.platform().getWorldContainer(), world + File.separator + "region"); + File[] regionFiles = folder.listFiles(); + if (regionFiles == null) { + throw new RuntimeException( + "Could not find worlds folder: " + folder + " ? (no read access?)"); + } + HashSet chunks = new HashSet<>(); + for (File file : regionFiles) { + String name = file.getName(); + if (name.endsWith("mca")) { + String[] split = name.split("\\."); + try { + int x = Integer.parseInt(split[1]); + int z = Integer.parseInt(split[2]); + BlockVector2 loc = BlockVector2.at(x, z); + chunks.add(loc); + } catch (NumberFormatException ignored) { + } + } + } + return chunks; + } + /** * Check if two blocks are the same type) * diff --git a/build.gradle b/build.gradle index ebf5e7284..03e5159b7 100644 --- a/build.gradle +++ b/build.gradle @@ -31,7 +31,7 @@ ext { } def ver = "6.0.0" -def versuffix = "SUPER-SNAPSHOT" +def versuffix = "-SUPER-SNAPSHOT" ext { if (project.hasProperty("versionsuffix")) { versuffix = "-$versionsuffix" @@ -125,6 +125,8 @@ subprojects { subproject -> dependencies { include(dependency("org.json:json:20200518")) include(dependency("net.kyori:text-api:3.0.2")) + include(dependency("javax.inject:javax.inject:1")) + include(dependency("aopalliance:aopalliance:1.0")) } relocate("io.papermc.lib", "com.plotsquared.bukkit.paperlib") relocate("org.json", "com.plotsquared.json") { From 18918eb3a31b1816e148fb055a7acd426bf6f8f6 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 24 Jul 2020 14:36:50 +0100 Subject: [PATCH 39/49] Fix a couple more Guice issues. Refactor read chunks to be a list of chunks rather than CuboidRegion --- .../bukkit/queue/BukkitQueueCoordinator.java | 4 +-- .../bukkit/util/BukkitRegionManager.java | 11 ++++++-- .../com/plotsquared/core/command/Area.java | 23 +++++++++------- .../core/generator/HybridPlotManager.java | 4 +-- .../core/generator/HybridPlotWorld.java | 10 +++---- .../core/generator/HybridUtils.java | 2 +- .../core/queue/BasicQueueCoordinator.java | 19 +++++++++----- .../core/queue/ChunkCoordinatorBuilder.java | 11 ++++---- .../core/queue/DelegateQueueCoordinator.java | 17 ++++++++---- .../core/queue/GlobalBlockQueue.java | 1 + .../core/queue/QueueCoordinator.java | 11 +++++--- .../plotsquared/core/util/RegionManager.java | 26 ++++++++++++------- .../core/util/SchematicHandler.java | 4 +-- 13 files changed, 87 insertions(+), 56 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index a2bd8afeb..4bf5998f2 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -186,8 +186,8 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { } CuboidRegion region; Collection read = new ArrayList<>(); - if ((region = getReadRegion()) != null) { - read = region.getChunks(); + if (getReadChunks().size() > 0) { + read.addAll(getReadChunks()); } chunkCoordinator = chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(getWorld()) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java index 7309952a2..2aac662f6 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java @@ -39,6 +39,7 @@ import com.plotsquared.core.queue.ScopedQueueCoordinator; import com.plotsquared.core.util.ChunkManager; import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.RegionUtil; +import com.plotsquared.core.util.WorldUtil; import com.plotsquared.core.util.entity.EntityCategories; import com.plotsquared.core.util.task.RunnableVal; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -55,6 +56,7 @@ import org.bukkit.entity.Player; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -72,7 +74,12 @@ public class BukkitRegionManager extends RegionManager { private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitRegionManager.class.getSimpleName()); - @Inject private GlobalBlockQueue blockQueue; + private final GlobalBlockQueue blockQueue; + + @Inject public BukkitRegionManager(@Nonnull WorldUtil worldUtil, @Nonnull GlobalBlockQueue blockQueue) { + super(worldUtil, blockQueue); + this.blockQueue = blockQueue; + } @Override public boolean handleClear(Plot plot, Runnable whenDone, PlotManager manager) { return false; @@ -167,7 +174,7 @@ public class BukkitRegionManager extends RegionManager { final int tcz = p2z >> 4; final QueueCoordinator queue = blockQueue.getNewQueue(world); - queue.setReadRegion(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3())); + queue.addReadChunks(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks()); queue.setChunkConsumer(chunk -> { int x = chunk.getX(); diff --git a/Core/src/main/java/com/plotsquared/core/command/Area.java b/Core/src/main/java/com/plotsquared/core/command/Area.java index 29a9f1551..20b352515 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Area.java +++ b/Core/src/main/java/com/plotsquared/core/command/Area.java @@ -287,16 +287,17 @@ public class Area extends SubCommand { case 2: switch (args[1].toLowerCase()) { case "pos1": { // Set position 1 - HybridPlotWorld area = (HybridPlotWorld) metaData.computeIfAbsent(player.getUUID(), missingUUID -> new HashMap<>()) - .get("area_create_area"); + HybridPlotWorld area = (HybridPlotWorld) metaData + .computeIfAbsent(player.getUUID(), + missingUUID -> new HashMap<>()).get("area_create_area"); if (area == null) { Captions.COMMAND_SYNTAX.send(player, "/plot area create [world[:id]] [=]..."); return false; } Location location = player.getLocation(); - metaData.computeIfAbsent(player.getUUID(), missingUUID -> new HashMap<>()) - .put("area_pos1", location); + metaData.computeIfAbsent(player.getUUID(), + missingUUID -> new HashMap<>()).put("area_pos1", location); Captions.SET_ATTRIBUTE.send(player, "area_pos1", location.getX() + "," + location.getZ()); MainUtil.sendMessage(player, @@ -306,14 +307,17 @@ public class Area extends SubCommand { } case "pos2": // Set position 2 and finish creation for type=2 (partial) final HybridPlotWorld area = (HybridPlotWorld) metaData - .computeIfAbsent(player.getUUID(), missingUUID -> new HashMap<>()).get("area_create_area"); + .computeIfAbsent(player.getUUID(), + missingUUID -> new HashMap<>()).get("area_create_area"); if (area == null) { Captions.COMMAND_SYNTAX.send(player, "/plot area create [world[:id]] [=]..."); return false; } Location pos1 = player.getLocation(); - Location pos2 = (Location) metaData.computeIfAbsent(player.getUUID(), missingUUID -> new HashMap<>()).get("area_pos1"); + Location pos2 = (Location) metaData + .computeIfAbsent(player.getUUID(), + missingUUID -> new HashMap<>()).get("area_pos1"); int dx = Math.abs(pos1.getX() - pos2.getX()); int dz = Math.abs(pos1.getZ() - pos2.getZ()); int numX = Math.max(1, @@ -367,7 +371,7 @@ public class Area extends SubCommand { queue.setChunkConsumer(chunk -> AugmentedUtils .generate(null, world, chunk.getX(), chunk.getZ(), queue)); - queue.setReadRegion(region); + queue.addReadChunks(region.getChunks()); queue.enqueue(); } } else { @@ -529,7 +533,8 @@ public class Area extends SubCommand { player.teleport(this.worldUtil.getSpawn(pa.getWorldName()), TeleportCause.COMMAND); } - metaData.computeIfAbsent(player.getUUID(), missingUUID -> new HashMap<>()).put("area_create_area", pa); + metaData.computeIfAbsent(player.getUUID(), missingUUID -> new HashMap<>()) + .put("area_create_area", pa); MainUtil.sendMessage(player, "$1Go to the first corner and use: $2 " + getCommandString() + " create pos1"); @@ -677,7 +682,7 @@ public class Area extends SubCommand { blockQueue.getNewQueue(worldUtil.getWeWorld(area.getWorldName())); queue.setChunkConsumer(chunk -> AugmentedUtils .generate(null, area.getWorldName(), chunk.getX(), chunk.getZ(), queue)); - queue.setReadRegion(area.getRegion()); + queue.addReadChunks(area.getRegion().getChunks()); queue.setCompleteTask(() -> player.sendMessage("Regen complete")); queue.enqueue(); return true; diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java index 0353210a6..9a022185f 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java @@ -248,8 +248,8 @@ public class HybridPlotManager extends ClassicPlotManager { final BiomeType biome = hybridPlotWorld.getPlotBiome(); final QueueCoordinator queue = hybridPlotWorld.getQueue(); - queue.setReadRegion(new CuboidRegion(plot.getExtendedBottomAbs().getBlockVector3(), - plot.getExtendedTopAbs().getBlockVector3())); + queue.addReadChunks(new CuboidRegion(plot.getExtendedBottomAbs().getBlockVector3(), + plot.getExtendedTopAbs().getBlockVector3()).getChunks()); queue.setChunkConsumer(blockVector2 -> { // If the chunk isn't near the edge and it isn't an augmented world we can just regen the whole chunk if (canRegen && ChunkUtil.isWholeChunk(pos1, pos2, blockVector2)) { diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java index 063849ba5..b89838836 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java @@ -82,8 +82,7 @@ public class HybridPlotWorld extends ClassicPlotWorld { private Location SIGN_LOCATION; @Getter private File root = null; - private final RegionManager regionManager; - private final SchematicHandler schematicHandler; + @Inject private SchematicHandler schematicHandler; @Inject public HybridPlotWorld(@Assisted("world") final String worldName, @Nullable @Assisted("id") final String id, @@ -91,13 +90,10 @@ public class HybridPlotWorld extends ClassicPlotWorld { @Nullable @Assisted("min") final PlotId min, @Nullable @Assisted("max") final PlotId max, @WorldConfig @Nonnull final YamlConfiguration worldConfiguration, - @Nonnull final RegionManager regionManager, - @Nonnull final SchematicHandler schematicHandler, @Nonnull final GlobalBlockQueue blockQueue, @Nullable final EconHandler econHandler) { super(worldName, id, generator, min, max, worldConfiguration, blockQueue, econHandler); - this.regionManager = regionManager; - this.schematicHandler = schematicHandler; + PlotSquared.platform().getInjector().injectMembers(this); } public static byte wrap(byte data, int start) { @@ -148,7 +144,7 @@ public class HybridPlotWorld extends ClassicPlotWorld { } @Nonnull @Override protected PlotManager createManager() { - return new HybridPlotManager(this, this.regionManager); + return new HybridPlotManager(this, PlotSquared.platform().getRegionManager()); } public Location getSignLocation(@Nonnull Plot plot) { diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index 34928a014..7936a6029 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -161,7 +161,7 @@ public class HybridUtils { System.gc(); QueueCoordinator queue = area.getQueue(); - queue.setReadRegion(region); + queue.addReadChunks(region.getChunks()); queue.setChunkConsumer(blockVector2 -> { int X = blockVector2.getX(); int Z = blockVector2.getZ(); diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index bbaffc6df..4a692cd2d 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -30,7 +30,6 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector2; -import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; @@ -39,6 +38,9 @@ import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.entity.EntityTypes; import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; @@ -47,6 +49,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { private final World world; private final ConcurrentHashMap blockChunks = new ConcurrentHashMap<>(); + private final List readRegion = new ArrayList<>(); private long modified; private LocalChunk lastWrappedChunk; private int lastX = Integer.MIN_VALUE; @@ -58,8 +61,6 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { private int[] regenEnd; private Consumer consumer = null; private boolean unloadAfter = true; - private CuboidRegion readRegion = null; - private GlobalBlockQueue globalBlockQueue; public BasicQueueCoordinator(World world) { @@ -74,7 +75,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { } @Override public final int size() { - return blockChunks.size(); + return blockChunks.size() + readRegion.size(); } @Override public final void setModified(long modified) { @@ -142,12 +143,16 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return true; } - @Override public CuboidRegion getReadRegion() { + @Override public List getReadChunks() { return this.readRegion; } - @Override public void setReadRegion(CuboidRegion readRegion) { - this.readRegion = readRegion; + @Override public void addReadChunk(BlockVector2 chunk) { + this.readRegion.add(chunk); + } + + @Override public void addReadChunks(Set readRegion) { + this.readRegion.addAll(readRegion); } @Override public void regenChunk(int x, int z) { diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java index 068d61aea..980e8ee78 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java @@ -30,11 +30,10 @@ import com.google.inject.Inject; import com.plotsquared.core.inject.factory.ChunkCoordinatorFactory; import com.plotsquared.core.location.Location; import com.sk89q.worldedit.math.BlockVector2; -import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; -import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; @@ -53,7 +52,6 @@ public class ChunkCoordinatorBuilder { private long maxIterationTime = 60; // A little over 1 tick; private int initialBatchSize = 4; private boolean unloadAfter = true; - private CuboidRegion readRegion = null; @Inject public ChunkCoordinatorBuilder(@Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory) { @@ -105,8 +103,11 @@ public class ChunkCoordinatorBuilder { return this; } - @Nonnull public ChunkCoordinatorBuilder withFinalAction(@Nonnull final Runnable whenDone) { - this.whenDone = Preconditions.checkNotNull(whenDone, "Final action may not be null"); + @Nonnull public ChunkCoordinatorBuilder withFinalAction(@Nullable final Runnable whenDone) { + if (whenDone == null) { + return this; + } + this.whenDone = whenDone; return this; } diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index dd7e0ae01..a17d57aad 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -29,12 +29,13 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector2; -import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import java.util.List; +import java.util.Set; import java.util.function.Consumer; public class DelegateQueueCoordinator extends QueueCoordinator { @@ -180,16 +181,22 @@ public class DelegateQueueCoordinator extends QueueCoordinator { } } - @Override public CuboidRegion getReadRegion() { + @Override public List getReadChunks() { if (parent != null) { - return parent.getReadRegion(); + return parent.getReadChunks(); } return null; } - @Override public void setReadRegion(CuboidRegion readRegion) { + @Override public void addReadChunks(Set readChunks) { if (parent != null) { - parent.setReadRegion(readRegion); + parent.addReadChunks(readChunks); + } + } + + @Override public void addReadChunk(BlockVector2 chunk) { + if (parent != null) { + parent.addReadChunk(chunk); } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java index e5d69406e..08896e122 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java @@ -68,6 +68,7 @@ public class GlobalBlockQueue { boolean success = false; if (queue.size() > 0 && !activeQueues.contains(queue)) { success = activeQueues.add(queue); + System.out.println("c"); queue.start(); } return success; diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index 57569bd7f..ea67f6401 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -33,7 +33,6 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector2; -import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; @@ -43,6 +42,7 @@ import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; +import java.util.Set; import java.util.function.Consumer; public abstract class QueueCoordinator { @@ -119,14 +119,16 @@ public abstract class QueueCoordinator { public abstract boolean setEntity(Entity entity); - public abstract CuboidRegion getReadRegion(); + public abstract List getReadChunks(); - public abstract void setReadRegion(CuboidRegion readRegion); + public abstract void addReadChunks(Set readChunks); - public abstract void setUnloadAfter(boolean unloadAfter); + public abstract void addReadChunk(BlockVector2 chunk); public abstract boolean isUnloadAfter(); + public abstract void setUnloadAfter(boolean unloadAfter); + public abstract void regenChunk(int x, int z); public abstract World getWorld(); @@ -136,6 +138,7 @@ public abstract class QueueCoordinator { } public boolean enqueue() { + System.out.println("b"); return blockQueue.enqueue(this); } diff --git a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java index f16420021..537425ba6 100644 --- a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java @@ -46,10 +46,10 @@ import com.sk89q.worldedit.world.biome.BiomeType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.File; import java.util.Collection; -import java.util.HashSet; import java.util.Set; public abstract class RegionManager { @@ -58,9 +58,14 @@ public abstract class RegionManager { LoggerFactory.getLogger("P2/" + RegionManager.class.getSimpleName()); public static RegionManager manager = null; - @Inject private WorldUtil worldUtil; - @Inject private ChunkManager chunkManager; - @Inject private GlobalBlockQueue blockQueue; + private final WorldUtil worldUtil; + private final GlobalBlockQueue blockQueue; + + @Inject + public RegionManager(@Nonnull WorldUtil worldUtil, @Nonnull GlobalBlockQueue blockQueue) { + this.worldUtil = worldUtil; + this.blockQueue = blockQueue; + } public static BlockVector2 getRegion(Location location) { int x = location.getX() >> 9; @@ -143,8 +148,8 @@ public abstract class RegionManager { (BasicQueueCoordinator) blockQueue.getNewQueue(newWorld); copyFromTo(pos1, pos2, relX, relZ, oldWorld, copyFrom, copyTo, false); copyFrom.setCompleteTask(copyTo::enqueue); - copyFrom.setReadRegion(new CuboidRegion(BlockVector3.at(pos1.getX(), 0, pos1.getZ()), - BlockVector3.at(pos2.getX(), 0, pos2.getZ()))); + copyFrom.addReadChunks(new CuboidRegion(BlockVector3.at(pos1.getX(), 0, pos1.getZ()), + BlockVector3.at(pos2.getX(), 0, pos2.getZ())).getChunks()); copyTo.setCompleteTask(whenDone); copyFrom.enqueue(); return true; @@ -171,10 +176,11 @@ public abstract class RegionManager { QueueCoordinator fromQueue2 = blockQueue.getNewQueue(world2); fromQueue1.setUnloadAfter(false); fromQueue2.setUnloadAfter(false); - fromQueue1.setReadRegion(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3())); - fromQueue2.setReadRegion(new CuboidRegion(swapPos.getBlockVector3(), BlockVector3 + fromQueue1.addReadChunks( + new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks()); + fromQueue2.addReadChunks(new CuboidRegion(swapPos.getBlockVector3(), BlockVector3 .at(swapPos.getX() + pos2.getX() - pos1.getX(), 0, - swapPos.getZ() + pos2.getZ() - pos1.getZ()))); + swapPos.getZ() + pos2.getZ() - pos1.getZ())).getChunks()); QueueCoordinator toQueue1 = blockQueue.getNewQueue(world1); QueueCoordinator toQueue2 = blockQueue.getNewQueue(world2); @@ -231,7 +237,7 @@ public abstract class RegionManager { final int minZ = pos1.getZ(); final int maxX = pos2.getX(); final int maxZ = pos2.getZ(); - queue.setReadRegion(region); + queue.addReadChunks(region.getChunks()); queue.setChunkConsumer(blockVector2 -> { final int cx = blockVector2.getX() << 4; final int cz = blockVector2.getZ() << 4; diff --git a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java index 1373562da..c26846dca 100644 --- a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java +++ b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java @@ -330,8 +330,8 @@ public abstract class SchematicHandler { final int bcz = p1z >> 4; final int tcx = p2x >> 4; final int tcz = p2z >> 4; - queue.setReadRegion( - new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3())); + queue.addReadChunks( + new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks()); queue.setChunkConsumer(blockVector2 -> { int x = blockVector2.getX(); int z = blockVector2.getZ(); From 72c0021306d354d11d0def00c73001c4a75c401f Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 24 Jul 2020 15:17:42 +0100 Subject: [PATCH 40/49] A couple of reworks - Redo how regeneration works a little to also take a cuboid region for regeneration off-chunk plots - Fix a couple of cases where we were writing to the queue instead of the world in the ChunkConsumer (dum) - this seems to be working. --- .../bukkit/queue/BukkitQueueCoordinator.java | 45 +++++++++----- .../bukkit/util/BukkitRegionManager.java | 12 ++-- .../com/plotsquared/core/command/Area.java | 4 +- .../core/generator/HybridPlotManager.java | 44 ++++---------- .../core/queue/BasicQueueCoordinator.java | 10 ++++ .../core/queue/DelegateQueueCoordinator.java | 14 +++++ .../core/queue/GlobalBlockQueue.java | 1 - .../core/queue/QueueCoordinator.java | 22 ++++++- .../core/util/SchematicHandler.java | 60 ++++++------------- 9 files changed, 115 insertions(+), 97 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index 4bf5998f2..791071e09 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -97,11 +97,18 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { @Override public boolean enqueue() { final Clipboard regenClipboard; if (isRegen()) { - Region region = new CuboidRegion( - BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4), - BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15)); + BlockVector3 start = + BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4); + BlockVector3 end = + BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15); + Region region = new CuboidRegion(start, end); regenClipboard = new BlockArrayClipboard(region); + regenClipboard.setOrigin(start); getWorld().regenerate(region, regenClipboard); + } else if (getRegenRegion() != null) { + regenClipboard = new BlockArrayClipboard(getRegenRegion()); + regenClipboard.setOrigin(getRegenRegion().getMinimumPoint()); + getWorld().regenerate(getRegenRegion(), regenClipboard); } else { regenClipboard = null; } @@ -121,15 +128,17 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { for (int z = 0; z < 16; z++) { BaseBlock block = regenClipboard.getFullBlock(BlockVector3.at(x, y, z)); - setWorldBlock(x, y, z, block, blockVector2); + if (block != null) { + setWorldBlock(x, y, z, block, blockVector2); + } } } } } + } + // Allow regen and then blocks to be placed (plot schematic etc) + if (localChunk == null) { return; - } else if (localChunk == null) { - throw new NullPointerException( - "LocalChunk cannot be null when accessed from ChunkCoordinator"); } int sx = blockVector2.getX() << 4; int sz = blockVector2.getZ() << 4; @@ -143,10 +152,13 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { continue; } BaseBlock block = blocksLayer[j]; - int x = sx + ChunkUtil.getX(j); - int y = ChunkUtil.getY(layer, j); - int z = sz + ChunkUtil.getZ(j); - setWorldBlock(x, y, z, block, blockVector2); + + if (block != null) { + int x = sx + ChunkUtil.getX(j); + int y = ChunkUtil.getY(layer, j); + int z = sz + ChunkUtil.getZ(j); + setWorldBlock(x, y, z, block, blockVector2); + } } } for (int layer = 0; layer < localChunk.getBaseblocks().length; layer++) { @@ -159,10 +171,12 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { continue; } BiomeType biome = biomesLayer[j]; - int x = sx + ChunkUtil.getX(j); - int y = ChunkUtil.getY(layer, j); - int z = sz + ChunkUtil.getZ(j); - getWorld().setBiome(BlockVector3.at(x, y, z), biome); + if (biome != null) { + int x = sx + ChunkUtil.getX(j); + int y = ChunkUtil.getY(layer, j); + int z = sz + ChunkUtil.getZ(j); + getWorld().setBiome(BlockVector3.at(x, y, z), biome); + } } } if (localChunk.getTiles().size() > 0) { @@ -184,7 +198,6 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { } }; } - CuboidRegion region; Collection read = new ArrayList<>(); if (getReadChunks().size() > 0) { read.addAll(getReadChunks()); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java index 2aac662f6..01e7bf769 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitRegionManager.java @@ -76,7 +76,8 @@ public class BukkitRegionManager extends RegionManager { LoggerFactory.getLogger("P2/" + BukkitRegionManager.class.getSimpleName()); private final GlobalBlockQueue blockQueue; - @Inject public BukkitRegionManager(@Nonnull WorldUtil worldUtil, @Nonnull GlobalBlockQueue blockQueue) { + @Inject + public BukkitRegionManager(@Nonnull WorldUtil worldUtil, @Nonnull GlobalBlockQueue blockQueue) { super(worldUtil, blockQueue); this.blockQueue = blockQueue; } @@ -174,7 +175,9 @@ public class BukkitRegionManager extends RegionManager { final int tcz = p2z >> 4; final QueueCoordinator queue = blockQueue.getNewQueue(world); - queue.addReadChunks(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks()); + final QueueCoordinator regenQueue = blockQueue.getNewQueue(world); + queue.addReadChunks( + new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks()); queue.setChunkConsumer(chunk -> { int x = chunk.getX(); @@ -185,7 +188,7 @@ public class BukkitRegionManager extends RegionManager { int zzt = zzb + 15; if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) { AugmentedUtils - .bypass(ignoreAugment, () -> queue.regenChunk(chunk.getX(), chunk.getZ())); + .bypass(ignoreAugment, () -> regenQueue.regenChunk(chunk.getX(), chunk.getZ())); return; } boolean checkX1 = false; @@ -285,7 +288,8 @@ public class BukkitRegionManager extends RegionManager { //map.restoreBlocks(worldObj, 0, 0); map.restoreEntities(Bukkit.getWorld(world.getName()), 0, 0); }); - queue.setCompleteTask(whenDone); + regenQueue.setCompleteTask(whenDone); + queue.setCompleteTask(regenQueue::enqueue); queue.enqueue(); return true; } diff --git a/Core/src/main/java/com/plotsquared/core/command/Area.java b/Core/src/main/java/com/plotsquared/core/command/Area.java index 20b352515..2aa2a1e4f 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Area.java +++ b/Core/src/main/java/com/plotsquared/core/command/Area.java @@ -370,7 +370,7 @@ public class Area extends SubCommand { blockQueue.getNewQueue(worldUtil.getWeWorld(world)); queue.setChunkConsumer(chunk -> AugmentedUtils .generate(null, world, chunk.getX(), chunk.getZ(), - queue)); + null)); queue.addReadChunks(region.getChunks()); queue.enqueue(); } @@ -681,7 +681,7 @@ public class Area extends SubCommand { QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(area.getWorldName())); queue.setChunkConsumer(chunk -> AugmentedUtils - .generate(null, area.getWorldName(), chunk.getX(), chunk.getZ(), queue)); + .generate(null, area.getWorldName(), chunk.getX(), chunk.getZ(), null)); queue.addReadChunks(area.getRegion().getChunks()); queue.setCompleteTask(() -> player.sendMessage("Regen complete")); queue.enqueue(); diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java index 9a022185f..55b6091f5 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java @@ -35,7 +35,6 @@ import com.plotsquared.core.plot.PlotAreaTerrainType; import com.plotsquared.core.plot.PlotAreaType; import com.plotsquared.core.plot.PlotId; import com.plotsquared.core.queue.QueueCoordinator; -import com.plotsquared.core.util.ChunkUtil; import com.plotsquared.core.util.FileBytes; import com.plotsquared.core.util.FileUtils; import com.plotsquared.core.util.MathMan; @@ -248,38 +247,19 @@ public class HybridPlotManager extends ClassicPlotManager { final BiomeType biome = hybridPlotWorld.getPlotBiome(); final QueueCoordinator queue = hybridPlotWorld.getQueue(); - queue.addReadChunks(new CuboidRegion(plot.getExtendedBottomAbs().getBlockVector3(), - plot.getExtendedTopAbs().getBlockVector3()).getChunks()); - queue.setChunkConsumer(blockVector2 -> { - // If the chunk isn't near the edge and it isn't an augmented world we can just regen the whole chunk - if (canRegen && ChunkUtil.isWholeChunk(pos1, pos2, blockVector2)) { - queue.regenChunk(blockVector2.getX(), blockVector2.getZ()); - return; - } - /* Otherwise we need to set each component, as we don't want to regenerate the road or other plots that share the same chunk.*/ - // Set the biome - int x1 = Math.max(pos1.getX(), blockVector2.getX() << 4); - int z1 = Math.max(pos1.getZ(), blockVector2.getZ() << 4); - int x2 = Math.min(pos2.getX(), blockVector2.getX() << 4); - int z2 = Math.min(pos2.getZ(), blockVector2.getZ() << 4); - WorldUtil.setBiome(world, x1, z1, x2, z2, biome); - // These two locations are for each component (e.g. bedrock, main block, floor, air) - Location bot = Location.at(world, x1, 0, z1); - Location top = Location.at(world, x2, 1, z2); - queue.setCuboid(bot, top, bedrock); + if (!canRegen) { + queue.setCuboid(pos1.withY(0), pos2.withY(0), bedrock); // Each component has a different layer - bot = bot.withY(1); - top = top.withY(hybridPlotWorld.PLOT_HEIGHT); - queue.setCuboid(bot, top, filling); - bot = bot.withY(hybridPlotWorld.PLOT_HEIGHT); - top = top.withY(hybridPlotWorld.PLOT_HEIGHT + 1); - queue.setCuboid(bot, top, plotfloor); - bot = bot.withY(hybridPlotWorld.PLOT_HEIGHT + 1); - top = top.withY(getWorldHeight()); - queue.setCuboid(bot, top, air); - // And finally set the schematic, the y value is unimportant for this function - pastePlotSchematic(queue, bot, top); - }); + queue.setCuboid(pos1.withY(1), pos2.withY(hybridPlotWorld.PLOT_HEIGHT - 1), filling); + queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT), + pos2.withY(hybridPlotWorld.PLOT_HEIGHT), plotfloor); + queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT + 1), + pos2.withY(getWorldHeight()), air); + queue.setBiomeCuboid(pos1, pos2, biome); + } else { + queue.setRegenRegion(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3())); + } + pastePlotSchematic(queue, pos1, pos2); queue.setCompleteTask(whenDone); return queue.enqueue(); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index 4a692cd2d..3e00deee5 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -30,6 +30,7 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; @@ -59,6 +60,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { private boolean regen = false; private int[] regenStart; private int[] regenEnd; + private CuboidRegion regenRegion = null; private Consumer consumer = null; private boolean unloadAfter = true; private GlobalBlockQueue globalBlockQueue; @@ -155,6 +157,14 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { this.readRegion.addAll(readRegion); } + @Override public CuboidRegion getRegenRegion() { + return this.regenRegion != null ? this.regenRegion.clone() : null; + } + + @Override public void setRegenRegion(CuboidRegion regenRegion) { + this.regenRegion = regenRegion; + } + @Override public void regenChunk(int x, int z) { regen = true; // There will never only be one nullified coordinate pair diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index a17d57aad..23af47151 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -29,6 +29,7 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; @@ -211,6 +212,19 @@ public class DelegateQueueCoordinator extends QueueCoordinator { if (parent != null) { parent.setUnloadAfter(setUnloadAfter); } + } + + @Override public CuboidRegion getRegenRegion() { + if (parent != null) { + return parent.getRegenRegion(); + } + return null; + } + + @Override public void setRegenRegion(CuboidRegion regenRegion) { + if (parent != null) { + parent.setRegenRegion(regenRegion); + } } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java index 08896e122..e5d69406e 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java @@ -68,7 +68,6 @@ public class GlobalBlockQueue { boolean success = false; if (queue.size() > 0 && !activeQueues.contains(queue)) { success = activeQueues.add(queue); - System.out.println("c"); queue.start(); } return success; diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index ea67f6401..f3b0f63c1 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -33,6 +33,7 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; @@ -129,6 +130,10 @@ public abstract class QueueCoordinator { public abstract void setUnloadAfter(boolean unloadAfter); + public abstract CuboidRegion getRegenRegion(); + + public abstract void setRegenRegion(CuboidRegion regenRegion); + public abstract void regenChunk(int x, int z); public abstract World getWorld(); @@ -138,7 +143,6 @@ public abstract class QueueCoordinator { } public boolean enqueue() { - System.out.println("b"); return blockQueue.enqueue(this); } @@ -181,4 +185,20 @@ public abstract class QueueCoordinator { } } } + + public void setBiomeCuboid(Location pos1, Location pos2, BiomeType biome) { + int yMin = Math.min(pos1.getY(), pos2.getY()); + int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); + int xMin = Math.min(pos1.getX(), pos2.getX()); + int xMax = Math.max(pos1.getX(), pos2.getX()); + int zMin = Math.min(pos1.getZ(), pos2.getZ()); + int zMax = Math.max(pos1.getZ(), pos2.getZ()); + for (int y = yMin; y <= yMax; y++) { + for (int x = xMin; x <= xMax; x++) { + for (int z = zMin; z <= zMax; z++) { + setBiome(x, y, z, biome); + } + } + } + } } diff --git a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java index c26846dca..3c8bec5c6 100644 --- a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java +++ b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java @@ -281,7 +281,6 @@ public abstract class SchematicHandler { return; } try { - final QueueCoordinator queue = plot.getArea().getQueue(); BlockVector3 dimension = schematic.getClipboard().getDimensions(); final int WIDTH = dimension.getX(); final int LENGTH = dimension.getZ(); @@ -330,50 +329,29 @@ public abstract class SchematicHandler { final int bcz = p1z >> 4; final int tcx = p2x >> 4; final int tcz = p2z >> 4; - queue.addReadChunks( - new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks()); - queue.setChunkConsumer(blockVector2 -> { - int x = blockVector2.getX(); - int z = blockVector2.getZ(); - 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; - } - // Paste schematic here + // Paste schematic here + final QueueCoordinator queue = plot.getArea().getQueue(); - for (int ry = 0; ry < Math.min(256, HEIGHT); ry++) { - int yy = y_offset_actual + ry; - if (yy > 255) { - continue; - } - for (int rz = zzb - p1z; rz <= (zzt - p1z); rz++) { - for (int rx = xxb - p1x; rx <= (xxt - p1x); rx++) { - int xx = p1x + xOffset + rx; - int zz = p1z + zOffset + rz; - BaseBlock id = - blockArrayClipboard.getFullBlock(BlockVector3.at(rx, ry, rz)); - queue.setBlock(xx, yy, zz, id); - if (ry == 0) { - BiomeType biome = - blockArrayClipboard.getBiome(BlockVector2.at(rx, rz)); - queue.setBiome(xx, zz, biome); - } + for (int ry = 0; ry < Math.min(256, HEIGHT); ry++) { + int yy = y_offset_actual + ry; + if (yy > 255) { + continue; + } + for (int rz = 0; rz <= blockArrayClipboard.getDimensions().getZ(); rz++) { + for (int rx = 0; rx < blockArrayClipboard.getDimensions().getX(); rx++) { + int xx = p1x + xOffset + rx; + int zz = p1z + zOffset + rz; + BaseBlock id = + blockArrayClipboard.getFullBlock(BlockVector3.at(rx, ry, rz)); + queue.setBlock(xx, yy, zz, id); + if (ry == 0) { + BiomeType biome = + blockArrayClipboard.getBiome(BlockVector3.at(rx, ry, rz)); + queue.setBiome(xx, yy, zz, biome); } } } - }); + } if (whenDone != null) { whenDone.value = true; } From 1d0760c63097189938f6035ee1c2163cbeaf5378 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 24 Jul 2020 16:24:53 +0100 Subject: [PATCH 41/49] Formatting, mark nonnull, nullable etc --- .../plotsquared/bukkit/BukkitPlatform.java | 195 ++---- .../bukkit/generator/BlockStatePopulator.java | 12 +- .../bukkit/generator/BukkitPlotGenerator.java | 2 +- .../bukkit/inject/BukkitModule.java | 16 +- .../bukkit/queue/BukkitChunkCoordinator.java | 60 +- .../bukkit/queue/BukkitQueueCoordinator.java | 43 +- .../plotsquared/bukkit/queue/GenChunk.java | 51 +- .../bukkit/util/BukkitChunkManager.java | 92 +-- .../plotsquared/bukkit/util/BukkitUtil.java | 133 ++-- .../components/ComponentPresetManager.java | 135 ++-- .../core/generator/AugmentedUtils.java | 19 +- .../core/generator/ClassicPlotManager.java | 262 +++----- .../core/generator/HybridPlotManager.java | 82 +-- .../core/generator/HybridPlotWorld.java | 68 +- .../core/generator/HybridUtils.java | 126 ++-- .../core/generator/SquarePlotManager.java | 47 +- .../inject/annotations/QueuePipeline.java | 39 -- .../ChunkCoordinatorBuilderFactory.java | 3 +- .../factory/ChunkCoordinatorFactory.java | 12 +- .../java/com/plotsquared/core/plot/Plot.java | 588 +++++++----------- .../plotsquared/core/plot/PlotManager.java | 79 ++- .../core/plot/world/SinglePlotManager.java | 88 ++- .../AreaBoundDelegateQueueCoordinator.java | 15 +- .../core/queue/BasicQueueCoordinator.java | 30 +- .../core/queue/ChunkCoordinatorBuilder.java | 27 +- .../core/queue/ChunkQueueCoordinator.java | 22 +- .../core/queue/DelegateQueueCoordinator.java | 36 +- .../core/queue/GlobalBlockQueue.java | 13 +- .../plotsquared/core/queue/LocalChunk.java | 21 +- ...ocationOffsetDelegateQueueCoordinator.java | 56 +- .../core/queue/OffsetQueueCoordinator.java | 14 +- .../core/queue/QueueCoordinator.java | 41 +- .../plotsquared/core/queue/QueueProvider.java | 8 +- .../core/queue/ScopedQueueCoordinator.java | 36 +- .../plotsquared/core/util/ChunkManager.java | 22 +- .../com/plotsquared/core/util/ChunkUtil.java | 12 +- .../plotsquared/core/util/RegionManager.java | 79 ++- .../core/util/SchematicHandler.java | 164 ++--- .../com/plotsquared/core/util/WorldUtil.java | 160 +++-- 39 files changed, 1172 insertions(+), 1736 deletions(-) delete mode 100644 Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index ea5f45430..1b824c3b4 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -165,8 +165,7 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; @SuppressWarnings("unused") public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPlatform { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + BukkitPlatform.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitPlatform.class.getSimpleName()); private static final int BSTATS_ID = 1404; static { @@ -236,10 +235,8 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl final PlotSquared plotSquared = new PlotSquared(this, "Bukkit"); if (PlotSquared.platform().getServerVersion()[1] < 13) { - System.out.println( - "You can't use this version of PlotSquared on a server less than Minecraft 1.13.2."); - System.out - .println("Please check the download page for the link to the legacy versions."); + System.out.println("You can't use this version of PlotSquared on a server less than Minecraft 1.13.2."); + System.out.println("Please check the download page for the link to the legacy versions."); System.out.println("The server will now be shutdown to prevent any corruption."); Bukkit.shutdown(); return; @@ -247,11 +244,9 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl // We create the injector after PlotSquared has been initialized, so that we have access // to generated instances and settings - this.injector = Guice.createInjector(Stage.PRODUCTION, new PermissionModule(), - new WorldManagerModule(), - new PlotSquaredModule(), - new BukkitModule(this), - new BackupModule()); + this.injector = Guice + .createInjector(Stage.PRODUCTION, new PermissionModule(), new WorldManagerModule(), new PlotSquaredModule(), new BukkitModule(this), + new BackupModule()); this.injector.injectMembers(this); if (PremiumVerification.isPremium() && Settings.Enabled_Components.UPDATE_NOTIFICATIONS) { @@ -296,8 +291,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl // Do stuff that was previously done in PlotSquared // Kill entities - if (Settings.Enabled_Components.KILL_ROAD_MOBS - || Settings.Enabled_Components.KILL_ROAD_VEHICLES) { + if (Settings.Enabled_Components.KILL_ROAD_MOBS || Settings.Enabled_Components.KILL_ROAD_VEHICLES) { this.runEntityTask(); } @@ -305,35 +299,28 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl if (Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) { try { logger.info("[P2] {} hooked into WorldEdit", this.getPluginName()); - WorldEdit.getInstance().getEventBus() - .register(this.getInjector().getInstance(WESubscriber.class)); + WorldEdit.getInstance().getEventBus().register(this.getInjector().getInstance(WESubscriber.class)); if (Settings.Enabled_Components.COMMANDS) { new WE_Anywhere(); } } catch (Throwable e) { - logger.error( - "[P2] Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master"); + logger.error("[P2] Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master"); } } if (Settings.Enabled_Components.EVENTS) { - getServer().getPluginManager() - .registerEvents(getInjector().getInstance(PlayerEvents.class), this); - getServer().getPluginManager() - .registerEvents(getInjector().getInstance(EntitySpawnListener.class), this); + getServer().getPluginManager().registerEvents(getInjector().getInstance(PlayerEvents.class), this); + getServer().getPluginManager().registerEvents(getInjector().getInstance(EntitySpawnListener.class), this); if (PaperLib.isPaper() && Settings.Paper_Components.PAPER_LISTENERS) { - getServer().getPluginManager() - .registerEvents(getInjector().getInstance(PaperListener.class), this); + getServer().getPluginManager().registerEvents(getInjector().getInstance(PaperListener.class), this); } this.plotListener.startRunnable(); } // Required - getServer().getPluginManager() - .registerEvents(getInjector().getInstance(WorldEvents.class), this); + getServer().getPluginManager().registerEvents(getInjector().getInstance(WorldEvents.class), this); if (Settings.Enabled_Components.CHUNK_PROCESSOR) { - getServer().getPluginManager() - .registerEvents(getInjector().getInstance(ChunkListener.class), this); + getServer().getPluginManager().registerEvents(getInjector().getInstance(ChunkListener.class), this); } // Commands @@ -361,8 +348,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } // World generators: - final ConfigurationSection section = - this.worldConfiguration.getConfigurationSection("worlds"); + final ConfigurationSection section = this.worldConfiguration.getConfigurationSection("worlds"); final WorldUtil worldUtil = getInjector().getInstance(WorldUtil.class); if (section != null) { @@ -380,15 +366,11 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl continue; } if (!worldUtil.isWorld(world) && !world.equals("*")) { - logger.warn( - "[P2] `{}` was not properly loaded - {} will now try to load it properly", - world, this.getPluginName()); + logger.warn("[P2] `{}` was not properly loaded - {} will now try to load it properly", world, this.getPluginName()); logger.warn( "[P2] - Are you trying to delete this world? Remember to remove it from the worlds.yml, bukkit.yml and multiverse worlds.yml"); - logger.warn( - "[P2] - Your world management plugin may be faulty (or non existent)"); - logger.warn( - "[P2] This message may also be a false positive and could be ignored."); + logger.warn("[P2] - Your world management plugin may be faulty (or non existent)"); + logger.warn("[P2] This message may also be a false positive and could be ignored."); this.setGenerator(world); } } @@ -396,8 +378,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } // Services are accessed in order - final CacheUUIDService cacheUUIDService = - new CacheUUIDService(Settings.UUID.UUID_CACHE_SIZE); + final CacheUUIDService cacheUUIDService = new CacheUUIDService(Settings.UUID.UUID_CACHE_SIZE); this.impromptuPipeline.registerService(cacheUUIDService); this.backgroundPipeline.registerService(cacheUUIDService); this.impromptuPipeline.registerConsumer(cacheUUIDService); @@ -413,8 +394,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } if (Settings.UUID.SERVICE_BUKKIT) { - final OfflinePlayerUUIDService offlinePlayerUUIDService = - new OfflinePlayerUUIDService(); + final OfflinePlayerUUIDService offlinePlayerUUIDService = new OfflinePlayerUUIDService(); this.impromptuPipeline.registerService(offlinePlayerUUIDService); this.backgroundPipeline.registerService(offlinePlayerUUIDService); } @@ -422,16 +402,14 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl final SQLiteUUIDService sqLiteUUIDService = new SQLiteUUIDService("user_cache.db"); final SQLiteUUIDService legacyUUIDService; - if (Settings.UUID.LEGACY_DATABASE_SUPPORT && - FileUtils.getFile(PlotSquared.platform().getDirectory(), "usercache.db").exists()) { + if (Settings.UUID.LEGACY_DATABASE_SUPPORT && FileUtils.getFile(PlotSquared.platform().getDirectory(), "usercache.db").exists()) { legacyUUIDService = new SQLiteUUIDService("usercache.db"); } else { legacyUUIDService = null; } final LuckPermsUUIDService luckPermsUUIDService; - if (Settings.UUID.SERVICE_LUCKPERMS - && Bukkit.getPluginManager().getPlugin("LuckPerms") != null) { + if (Settings.UUID.SERVICE_LUCKPERMS && Bukkit.getPluginManager().getPlugin("LuckPerms") != null) { luckPermsUUIDService = new LuckPermsUUIDService(); logger.info("[P2] (UUID) Using LuckPerms as a complementary UUID service"); } else { @@ -439,8 +417,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } final BungeePermsUUIDService bungeePermsUUIDService; - if (Settings.UUID.SERVICE_BUNGEE_PERMS - && Bukkit.getPluginManager().getPlugin("BungeePerms") != null) { + if (Settings.UUID.SERVICE_BUNGEE_PERMS && Bukkit.getPluginManager().getPlugin("BungeePerms") != null) { bungeePermsUUIDService = new BungeePermsUUIDService(); logger.info("[P2] (UUID) Using BungeePerms as a complementary UUID service"); } else { @@ -448,8 +425,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } final EssentialsUUIDService essentialsUUIDService; - if (Settings.UUID.SERVICE_ESSENTIALSX - && Bukkit.getPluginManager().getPlugin("Essentials") != null) { + if (Settings.UUID.SERVICE_ESSENTIALSX && Bukkit.getPluginManager().getPlugin("Essentials") != null) { essentialsUUIDService = new EssentialsUUIDService(); logger.info("[P2] (UUID) Using EssentialsX as a complementary UUID service"); } else { @@ -489,11 +465,9 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl this.backgroundPipeline.registerService(essentialsUUIDService); } - final SquirrelIdUUIDService impromptuMojangService = - new SquirrelIdUUIDService(Settings.UUID.IMPROMPTU_LIMIT); + final SquirrelIdUUIDService impromptuMojangService = new SquirrelIdUUIDService(Settings.UUID.IMPROMPTU_LIMIT); this.impromptuPipeline.registerService(impromptuMojangService); - final SquirrelIdUUIDService backgroundMojangService = - new SquirrelIdUUIDService(Settings.UUID.BACKGROUND_LIMIT); + final SquirrelIdUUIDService backgroundMojangService = new SquirrelIdUUIDService(Settings.UUID.BACKGROUND_LIMIT); this.backgroundPipeline.registerService(backgroundMojangService); } else { this.impromptuPipeline.registerService(sqLiteUUIDService); @@ -536,10 +510,8 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl // Clean up potential memory leak Bukkit.getScheduler().runTaskTimer(this, () -> { try { - for (final PlotPlayer player : this.getPlayerManager() - .getPlayers()) { - if (player.getPlatformPlayer() == null || !player.getPlatformPlayer() - .isOnline()) { + for (final PlotPlayer player : this.getPlayerManager().getPlayers()) { + if (player.getPlatformPlayer() == null || !player.getPlatformPlayer().isOnline()) { this.getPlayerManager().removePlayer(player); } } @@ -554,8 +526,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl this.methodUnloadSetup = true; try { ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); - this.methodUnloadChunk0 = classCraftWorld.getRealClass() - .getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class); + this.methodUnloadChunk0 = classCraftWorld.getRealClass().getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class); this.methodUnloadChunk0.setAccessible(true); } catch (Throwable event) { event.printStackTrace(); @@ -586,8 +557,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } final Plot plot = area.getOwnedPlot(id); if (plot != null) { - if (!plot.getFlag(ServerPlotFlag.class) || PlotSquared.platform().getPlayerManager() - .getPlayerIfExists(plot.getOwner()) == null) { + if (!plot.getFlag(ServerPlotFlag.class) || PlotSquared.platform().getPlayerManager().getPlayerIfExists(plot.getOwner()) == null) { if (world.getKeepSpawnInMemory()) { world.setKeepSpawnInMemory(false); return; @@ -605,8 +575,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl boolean result; if (methodUnloadChunk0 != null) { try { - result = (boolean) methodUnloadChunk0 - .invoke(world, chunkI.getX(), chunkI.getZ(), true); + result = (boolean) methodUnloadChunk0.invoke(world, chunkI.getX(), chunkI.getZ(), true); } catch (Throwable e) { methodUnloadChunk0 = null; e.printStackTrace(); @@ -629,8 +598,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } } - private void startUuidCaching(@Nonnull final SQLiteUUIDService sqLiteUUIDService, - @Nonnull final CacheUUIDService cacheUUIDService) { + private void startUuidCaching(@Nonnull final SQLiteUUIDService sqLiteUUIDService, @Nonnull final CacheUUIDService cacheUUIDService) { // Load all uuids into a big chunky boi queue final Queue uuidQueue = new LinkedBlockingQueue<>(); PlotSquared.get().forEachPlotRaw(plot -> { @@ -654,8 +622,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl // Now fetch names for all known UUIDs final int totalSize = uuidQueue.size(); int read = 0; - logger.info("[P2] (UUID) PlotSquared will fetch UUIDs in groups of {}", - Settings.UUID.BACKGROUND_LIMIT); + logger.info("[P2] (UUID) PlotSquared will fetch UUIDs in groups of {}", Settings.UUID.BACKGROUND_LIMIT); final List uuidList = new ArrayList<>(Settings.UUID.BACKGROUND_LIMIT); // Used to indicate that the second retrieval has been attempted @@ -671,8 +638,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl // fresh batch secondRun = false; // Populate the request list - for (int i = 0; - i < Settings.UUID.BACKGROUND_LIMIT && !uuidQueue.isEmpty(); i++) { + for (int i = 0; i < Settings.UUID.BACKGROUND_LIMIT && !uuidQueue.isEmpty(); i++) { uuidList.add(uuidQueue.poll()); read++; } @@ -688,8 +654,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl // Print progress final double percentage = ((double) read / (double) totalSize) * 100.0D; if (Settings.DEBUG) { - logger.info("[P2] (UUID) PlotSquared has cached {} of UUIDs", - String.format("%.1f%%", percentage)); + logger.info("[P2] (UUID) PlotSquared has cached {} of UUIDs", String.format("%.1f%%", percentage)); } } catch (final InterruptedException | ExecutionException e) { logger.error("[P2] (UUID) Failed to retrieve last batch. Will try again", e); @@ -791,8 +756,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl case "MINECART_TNT": case "BOAT": if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { - com.plotsquared.core.location.Location location = - BukkitUtil.adapt(entity.getLocation()); + com.plotsquared.core.location.Location location = BukkitUtil.adapt(entity.getLocation()); Plot plot = location.getPlot(); if (plot == null) { if (location.isPlotArea()) { @@ -822,9 +786,8 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl case "FIREBALL": case "DRAGON_FIREBALL": case "DROPPED_ITEM": - if (Settings.Enabled_Components.KILL_ROAD_ITEMS && plotArea - .getOwnedPlotAbs(BukkitUtil.adapt(entity.getLocation())) - == null) { + if (Settings.Enabled_Components.KILL_ROAD_ITEMS + && plotArea.getOwnedPlotAbs(BukkitUtil.adapt(entity.getLocation())) == null) { entity.remove(); } // dropped item @@ -848,15 +811,12 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl PlotId originalPlotId = (PlotId) meta.get(0).value(); if (originalPlotId != null) { - com.plotsquared.core.location.Location pLoc = - BukkitUtil.adapt(entity.getLocation()); + com.plotsquared.core.location.Location pLoc = BukkitUtil.adapt(entity.getLocation()); PlotArea area = pLoc.getPlotArea(); if (area != null) { PlotId currentPlotId = area.getPlotAbs(pLoc).getId(); - if (!originalPlotId.equals(currentPlotId) && ( - currentPlotId == null || !area - .getPlot(originalPlotId) - .equals(area.getPlot(currentPlotId)))) { + if (!originalPlotId.equals(currentPlotId) && (currentPlotId == null || !area.getPlot(originalPlotId) + .equals(area.getPlot(currentPlotId)))) { if (entity.hasMetadata("ps-tmp-teleport")) { continue; } @@ -867,16 +827,12 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } } else { //This is to apply the metadata to already spawned shulkers (see EntitySpawnListener.java) - com.plotsquared.core.location.Location pLoc = - BukkitUtil.adapt(entity.getLocation()); + com.plotsquared.core.location.Location pLoc = BukkitUtil.adapt(entity.getLocation()); PlotArea area = pLoc.getPlotArea(); if (area != null) { PlotId currentPlotId = area.getPlotAbs(pLoc).getId(); if (currentPlotId != null) { - entity.setMetadata("shulkerPlot", - new FixedMetadataValue( - (Plugin) PlotSquared.platform(), - currentPlotId)); + entity.setMetadata("shulkerPlot", new FixedMetadataValue((Plugin) PlotSquared.platform(), currentPlotId)); } } } @@ -957,11 +913,9 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl if (BukkitUtil.adapt(location).isPlotRoad()) { if (entity instanceof LivingEntity) { LivingEntity livingEntity = (LivingEntity) entity; - if (!livingEntity.isLeashed() || !entity - .hasMetadata("keep")) { + if (!livingEntity.isLeashed() || !entity.hasMetadata("keep")) { Entity passenger = entity.getPassenger(); - if (!(passenger instanceof Player) && entity - .getMetadata("keep").isEmpty()) { + if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) { if (entity.hasMetadata("ps-tmp-teleport")) { continue; } @@ -972,8 +926,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } } else { Entity passenger = entity.getPassenger(); - if (!(passenger instanceof Player) && entity - .getMetadata("keep").isEmpty()) { + if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) { if (entity.hasMetadata("ps-tmp-teleport")) { continue; } @@ -994,15 +947,12 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl }), TaskTime.seconds(1L)); } - @Override @Nullable - public final ChunkGenerator getDefaultWorldGenerator(@Nonnull final String worldName, - final String id) { + @Override @Nullable public final ChunkGenerator getDefaultWorldGenerator(@Nonnull final String worldName, final String id) { final IndependentPlotGenerator result; if (id != null && id.equalsIgnoreCase("single")) { result = getInjector().getInstance(SingleWorldGenerator.class); } else { - result = getInjector() - .getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)); + result = getInjector().getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)); if (!PlotSquared.get().setupPlotWorld(worldName, id, result)) { return null; } @@ -1010,8 +960,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl return (ChunkGenerator) result.specify(worldName); } - @Override @Nullable public GeneratorWrapper getGenerator(@Nonnull final String world, - @Nullable final String name) { + @Override @Nullable public GeneratorWrapper getGenerator(@Nonnull final String world, @Nullable final String name) { if (name == null) { return null; } @@ -1023,8 +972,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } return new BukkitPlotGenerator(world, gen, this.plotAreaManager); } else { - return new BukkitPlotGenerator(world, getInjector() - .getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)), + return new BukkitPlotGenerator(world, getInjector().getInstance(Key.get(IndependentPlotGenerator.class, DefaultGenerator.class)), this.plotAreaManager); } } @@ -1045,19 +993,14 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl map.put(plotAreaType.name().toLowerCase(), terrainTypes); } for (final PlotArea plotArea : this.plotAreaManager.getAllPlotAreas()) { - final Map terrainTypeMap = - map.get(plotArea.getType().name().toLowerCase()); - terrainTypeMap.put(plotArea.getTerrain().name().toLowerCase(), - terrainTypeMap.get(plotArea.getTerrain().name().toLowerCase()) + 1); + final Map terrainTypeMap = map.get(plotArea.getType().name().toLowerCase()); + terrainTypeMap.put(plotArea.getTerrain().name().toLowerCase(), terrainTypeMap.get(plotArea.getTerrain().name().toLowerCase()) + 1); } return map; })); - metrics.addCustomChart(new Metrics.SimplePie("premium", - () -> PremiumVerification.isPremium() ? "Premium" : "Non-Premium")); + metrics.addCustomChart(new Metrics.SimplePie("premium", () -> PremiumVerification.isPremium() ? "Premium" : "Non-Premium")); metrics.addCustomChart(new Metrics.SimplePie("worldedit_implementation", - () -> Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit") != null ? - "FastAsyncWorldEdit" : - "WorldEdit")); + () -> Bukkit.getPluginManager().getPlugin("FastAsyncWorldEdit") != null ? "FastAsyncWorldEdit" : "WorldEdit")); } @Override public void unregister(@Nonnull final PlotPlayer player) { @@ -1068,15 +1011,12 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl World world = BukkitUtil.getWorld(worldName); if (world == null) { // create world - ConfigurationSection worldConfig = - this.worldConfiguration.getConfigurationSection("worlds." + worldName); + ConfigurationSection worldConfig = this.worldConfiguration.getConfigurationSection("worlds." + worldName); String manager = worldConfig.getString("generator.plugin", getPluginName()); - PlotAreaBuilder builder = PlotAreaBuilder.newBuilder().plotManager(manager) - .generatorName(worldConfig.getString("generator.init", manager)) - .plotAreaType(ConfigurationUtil.getType(worldConfig)) - .terrainType(ConfigurationUtil.getTerrain(worldConfig)) - .settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null)) - .worldName(worldName); + PlotAreaBuilder builder = + PlotAreaBuilder.newBuilder().plotManager(manager).generatorName(worldConfig.getString("generator.init", manager)) + .plotAreaType(ConfigurationUtil.getType(worldConfig)).terrainType(ConfigurationUtil.getTerrain(worldConfig)) + .settingsNodesWrapper(new SettingsNodesWrapper(new ConfigurationNode[0], null)).worldName(worldName); getInjector().getInstance(SetupUtils.class).setupWorld(builder); world = Bukkit.getWorld(worldName); } else { @@ -1095,8 +1035,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl if (gen instanceof BukkitPlotGenerator) { PlotSquared.get().loadWorld(worldName, (BukkitPlotGenerator) gen); } else if (gen != null) { - PlotSquared.get().loadWorld(worldName, - new BukkitPlotGenerator(worldName, gen, this.plotAreaManager)); + PlotSquared.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen, this.plotAreaManager)); } else if (this.worldConfiguration.contains("worlds." + worldName)) { PlotSquared.get().loadWorld(worldName, null); } @@ -1115,31 +1054,29 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } } - @Override public GeneratorWrapper wrapPlotGenerator(@Nullable final String world, - @Nonnull final IndependentPlotGenerator generator) { + @Override public GeneratorWrapper wrapPlotGenerator(@Nullable final String world, @Nonnull final IndependentPlotGenerator generator) { return new BukkitPlotGenerator(world, generator, this.plotAreaManager); } @Override public List, Boolean>> getPluginIds() { List, Boolean>> names = new ArrayList<>(); for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - Map.Entry id = new AbstractMap.SimpleEntry<>(plugin.getName(), - plugin.getDescription().getVersion()); + Map.Entry id = new AbstractMap.SimpleEntry<>(plugin.getName(), plugin.getDescription().getVersion()); names.add(new AbstractMap.SimpleEntry<>(id, plugin.isEnabled())); } return names; } - + @Override @Nonnull public com.plotsquared.core.location.World getPlatformWorld(@Nonnull final String worldName) { return BukkitWorld.of(worldName); } @Override @Nonnull public PlatformWorldManager getWorldManager() { - return getInjector().getInstance(Key.get(new TypeLiteral>() {})); + return getInjector().getInstance(Key.get(new TypeLiteral>() { + })); } - @Override @Nonnull @SuppressWarnings("ALL") - public PlayerManager, ? extends Player> getPlayerManager() { + @Override @Nonnull @SuppressWarnings("ALL") public PlayerManager, ? extends Player> getPlayerManager() { return (PlayerManager) getInjector().getInstance(PlayerManager.class); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java index 935ef3fde..9a05dd773 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BlockStatePopulator.java @@ -47,24 +47,20 @@ final class BlockStatePopulator extends BlockPopulator { private QueueCoordinator queue; - public BlockStatePopulator(@Nonnull final IndependentPlotGenerator plotGenerator, - @Nonnull final PlotAreaManager plotAreaManager) { + public BlockStatePopulator(@Nonnull final IndependentPlotGenerator plotGenerator, @Nonnull final PlotAreaManager plotAreaManager) { this.plotGenerator = plotGenerator; this.plotAreaManager = plotAreaManager; } - @Override public void populate(@Nonnull final World world, @Nonnull final Random random, - @Nonnull final Chunk source) { + @Override public void populate(@Nonnull final World world, @Nonnull final Random random, @Nonnull final Chunk source) { if (this.queue == null) { - this.queue = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(new BukkitWorld(world)); + this.queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(new BukkitWorld(world)); } final PlotArea area = this.plotAreaManager.getPlotArea(world.getName(), null); if (area == null) { return; } - final ChunkWrapper wrap = - new ChunkWrapper(area.getWorldName(), source.getX(), source.getZ()); + final ChunkWrapper wrap = new ChunkWrapper(area.getWorldName(), source.getX(), source.getZ()); final ScopedQueueCoordinator chunk = this.queue.getForChunk(wrap.x, wrap.z); if (this.plotGenerator.populateChunk(chunk, area)) { this.queue.enqueue(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java index 3e42530c4..bd9959461 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java @@ -63,7 +63,7 @@ public class BukkitPlotGenerator extends ChunkGenerator @Getter private final String levelName; - public BukkitPlotGenerator(@Nonnull final String name, + public BukkitPlotGenerator(@Nonnull final String name, @Nonnull final IndependentPlotGenerator generator, @Nonnull final PlotAreaManager plotAreaManager) { this.plotAreaManager = plotAreaManager; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java index db2e311a0..4d568842e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/inject/BukkitModule.java @@ -82,19 +82,15 @@ public class BukkitModule extends AbstractModule { bind(PlayerManager.class).to(BukkitPlayerManager.class); bind(JavaPlugin.class).toInstance(bukkitPlatform); bind(PlotPlatform.class).toInstance(bukkitPlatform); - bind(IndependentPlotGenerator.class).annotatedWith(DefaultGenerator.class) - .to(HybridGen.class); + bind(IndependentPlotGenerator.class).annotatedWith(DefaultGenerator.class).to(HybridGen.class); // Console actor @Nonnull ConsoleCommandSender console = Bukkit.getServer().getConsoleSender(); - WorldEditPlugin wePlugin = - ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit")); - bind(Actor.class).annotatedWith(ConsoleActor.class) - .toInstance(wePlugin.wrapCommandSender(console)); + WorldEditPlugin wePlugin = ((WorldEditPlugin) Bukkit.getPluginManager().getPlugin("WorldEdit")); + bind(Actor.class).annotatedWith(ConsoleActor.class).toInstance(wePlugin.wrapCommandSender(console)); bind(InventoryUtil.class).to(BukkitInventoryUtil.class); bind(SetupUtils.class).to(BukkitSetupUtils.class); bind(WorldUtil.class).to(BukkitUtil.class); - bind(GlobalBlockQueue.class) - .toInstance(new GlobalBlockQueue(QueueProvider.of(BukkitQueueCoordinator.class))); + bind(GlobalBlockQueue.class).toInstance(new GlobalBlockQueue(QueueProvider.of(BukkitQueueCoordinator.class))); bind(ChunkManager.class).to(BukkitChunkManager.class); bind(RegionManager.class).to(BukkitRegionManager.class); bind(SchematicHandler.class).to(BukkitSchematicHandler.class); @@ -104,9 +100,7 @@ public class BukkitModule extends AbstractModule { bind(PlotAreaManager.class).to(DefaultPlotAreaManager.class); } install(new FactoryModuleBuilder().build(HybridPlotWorldFactory.class)); - install(new FactoryModuleBuilder() - .implement(ChunkCoordinator.class, BukkitChunkCoordinator.class) - .build(ChunkCoordinatorFactory.class)); + install(new FactoryModuleBuilder().implement(ChunkCoordinator.class, BukkitChunkCoordinator.class).build(ChunkCoordinatorFactory.class)); install(new FactoryModuleBuilder().build(ChunkCoordinatorBuilderFactory.class)); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java index 3961cbdac..3f15fc6f3 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java @@ -76,13 +76,13 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { private int batchSize; @Inject private BukkitChunkCoordinator(@Assisted final long maxIterationTime, - @Assisted final int initialBatchSize, - @Assisted @Nonnull final Consumer chunkConsumer, - @Assisted @Nonnull final World world, - @Assisted @Nonnull final Collection requestedChunks, - @Assisted @Nonnull final Runnable whenDone, - @Assisted @Nonnull final Consumer throwableConsumer, - @Assisted final boolean unloadAfter) { + @Assisted final int initialBatchSize, + @Assisted @Nonnull final Consumer chunkConsumer, + @Assisted @Nonnull final World world, + @Assisted @Nonnull final Collection requestedChunks, + @Assisted @Nonnull final Runnable whenDone, + @Assisted @Nonnull final Consumer throwableConsumer, + @Assisted final boolean unloadAfter) { this.requestedChunks = new LinkedBlockingQueue<>(requestedChunks); this.availableChunks = new LinkedBlockingQueue<>(); this.totalSize = requestedChunks.size(); @@ -104,8 +104,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { // Request initial batch this.requestBatch(); // Wait until next tick to give the chunks a chance to be loaded - TaskManager.runTaskLater(() -> TaskManager.runTaskRepeat(this, TaskTime.ticks(1)), - TaskTime.ticks(1)); + TaskManager.runTaskLater(() -> TaskManager.runTaskRepeat(this, TaskTime.ticks(1)), TaskTime.ticks(1)); } @Override public void runTask() { @@ -129,8 +128,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { final long end = System.currentTimeMillis(); // Update iteration time iterationTime = end - start; - } while (2 * iterationTime /* last chunk + next chunk */ < this.maxIterationTime - && (chunk = availableChunks.poll()) != null); + } while (2 * iterationTime /* last chunk + next chunk */ < this.maxIterationTime && (chunk = availableChunks.poll()) != null); if (processedChunks < this.batchSize) { // Adjust batch size based on the amount of processed chunks per tick this.batchSize = processedChunks; @@ -157,36 +155,42 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { } } + /** + * Requests a batch of chunks to be loaded + */ private void requestBatch() { BlockVector2 chunk; for (int i = 0; i < this.batchSize && (chunk = this.requestedChunks.poll()) != null; i++) { // This required PaperLib to be bumped to version 1.0.4 to mark the request as urgent - PaperLib.getChunkAtAsync(this.bukkitWorld, chunk.getX(), chunk.getZ(), true, true) - .whenComplete((chunkObject, throwable) -> { - if (throwable != null) { - throwable.printStackTrace(); - // We want one less because this couldn't be processed - this.expectedSize.decrementAndGet(); - } else { - this.processChunk(chunkObject); - } - }); + PaperLib.getChunkAtAsync(this.bukkitWorld, chunk.getX(), chunk.getZ(), true, true).whenComplete((chunkObject, throwable) -> { + if (throwable != null) { + throwable.printStackTrace(); + // We want one less because this couldn't be processed + this.expectedSize.decrementAndGet(); + } else { + this.processChunk(chunkObject); + } + }); } } + /** + * Once a chunk has been loaded, process it (add a plugin ticket and add to available chunks list) + */ private void processChunk(@Nonnull final Chunk chunk) { if (!chunk.isLoaded()) { - throw new IllegalArgumentException( - String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ())); + throw new IllegalArgumentException(String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ())); } chunk.addPluginChunkTicket(this.plugin); this.availableChunks.add(chunk); } + /** + * Once a chunk has been used, free it up for unload by removing the plugin ticket + */ private void freeChunk(@Nonnull final Chunk chunk) { if (!chunk.isLoaded()) { - throw new IllegalArgumentException( - String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ())); + throw new IllegalArgumentException(String.format("Chunk %d;%d is is not loaded", chunk.getX(), chunk.getZ())); } chunk.removePluginChunkTicket(this.plugin); } @@ -214,8 +218,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { * * @param subscriber Subscriber */ - public void subscribeToProgress( - @Nonnull final BukkitChunkCoordinator.ProgressSubscriber subscriber) { + public void subscribeToProgress(@Nonnull final BukkitChunkCoordinator.ProgressSubscriber subscriber) { this.progressSubscribers.add(subscriber); } @@ -228,8 +231,7 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { * @param coordinator Coordinator instance that triggered the notification * @param progress Progress in the range [0, 1] */ - void notifyProgress(@Nonnull final BukkitChunkCoordinator coordinator, - final float progress); + void notifyProgress(@Nonnull final BukkitChunkCoordinator coordinator, final float progress); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index 791071e09..510b63e7a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -56,6 +56,7 @@ import org.bukkit.block.Block; import org.bukkit.block.Container; import org.bukkit.block.data.BlockData; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collection; import java.util.function.Consumer; @@ -69,10 +70,9 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { private Runnable whenDone; private ChunkCoordinator chunkCoordinator; - @Inject public BukkitQueueCoordinator(World world) { + @Inject public BukkitQueueCoordinator(@Nonnull World world) { super(world); - sideEffectSet = SideEffectSet.none().with(SideEffect.LIGHTING, SideEffect.State.OFF) - .with(SideEffect.NEIGHBORS, SideEffect.State.OFF); + sideEffectSet = SideEffectSet.none().with(SideEffect.LIGHTING, SideEffect.State.OFF).with(SideEffect.NEIGHBORS, SideEffect.State.OFF); } @Override public BlockState getBlock(int x, int y, int z) { @@ -97,10 +97,8 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { @Override public boolean enqueue() { final Clipboard regenClipboard; if (isRegen()) { - BlockVector3 start = - BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4); - BlockVector3 end = - BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15); + BlockVector3 start = BlockVector3.at(getRegenStart()[0] << 4, 0, getRegenStart()[1] << 4); + BlockVector3 end = BlockVector3.at((getRegenEnd()[0] << 4) + 15, 255, (getRegenEnd()[1] << 4) + 15); Region region = new CuboidRegion(start, end); regenClipboard = new BlockArrayClipboard(region); regenClipboard.setOrigin(start); @@ -117,17 +115,14 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { consumer = blockVector2 -> { LocalChunk localChunk = getBlockChunks().get(blockVector2); boolean isRegenChunk = - regenClipboard != null && blockVector2.getBlockX() > getRegenStart()[0] - && blockVector2.getBlockZ() > getRegenStart()[1] - && blockVector2.getBlockX() < getRegenEnd()[0] - && blockVector2.getBlockZ() < getRegenEnd()[1]; + regenClipboard != null && blockVector2.getBlockX() > getRegenStart()[0] && blockVector2.getBlockZ() > getRegenStart()[1] + && blockVector2.getBlockX() < getRegenEnd()[0] && blockVector2.getBlockZ() < getRegenEnd()[1]; if (isRegenChunk) { for (int layer = 0; layer < 16; layer++) { for (int y = layer << 4; y < 16; y++) { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { - BaseBlock block = - regenClipboard.getFullBlock(BlockVector3.at(x, y, z)); + BaseBlock block = regenClipboard.getFullBlock(BlockVector3.at(x, y, z)); if (block != null) { setWorldBlock(x, y, z, block, blockVector2); } @@ -186,8 +181,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { getWorld().setBlock(blockVector3, block, sideEffectSet); } catch (WorldEditException ignored) { StateWrapper sw = new StateWrapper(tag); - sw.restoreTag(getWorld().getName(), blockVector3.getX(), - blockVector3.getY(), blockVector3.getZ()); + sw.restoreTag(getWorld().getName(), blockVector3.getX(), blockVector3.getY(), blockVector3.getZ()); } })); } @@ -203,15 +197,16 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { read.addAll(getReadChunks()); } chunkCoordinator = - chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(getWorld()) - .withChunks(getBlockChunks().keySet()).withChunks(read).withInitialBatchSize(3) - .withMaxIterationTime(40).withThrowableConsumer(Throwable::printStackTrace) - .withFinalAction(whenDone).withConsumer(consumer).unloadAfter(isUnloadAfter()) - .build(); + chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(getWorld()).withChunks(getBlockChunks().keySet()).withChunks(read) + .withInitialBatchSize(3).withMaxIterationTime(40).withThrowableConsumer(Throwable::printStackTrace).withFinalAction(whenDone) + .withConsumer(consumer).unloadAfter(isUnloadAfter()).build(); return super.enqueue(); } - private void setWorldBlock(int x, int y, int z, BaseBlock block, BlockVector2 blockVector2) { + /** + * Set a block to the world. First tries WNA but defaults to normal block setting methods if that fails + */ + private void setWorldBlock(int x, int y, int z, @Nonnull BaseBlock block, @Nonnull BlockVector2 blockVector2) { try { getWorld().setBlock(BlockVector3.at(x, y, z), block, sideEffectSet); } catch (WorldEditException ignored) { @@ -225,8 +220,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { Block existing = chunk.getBlock(x, y, z); final BlockState existingBaseBlock = BukkitAdapter.adapt(existing.getBlockData()); - if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing.getBlockData() - .matches(blockData)) { + if (BukkitBlockUtil.get(existing).equals(existingBaseBlock) && existing.getBlockData().matches(blockData)) { return; } @@ -240,8 +234,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { CompoundTag tag = block.getNbtData(); StateWrapper sw = new StateWrapper(tag); - sw.restoreTag(getWorld().getName(), existing.getX(), existing.getY(), - existing.getZ()); + sw.restoreTag(getWorld().getName(), existing.getX(), existing.getY(), existing.getZ()); } } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java index ddfa03033..195882d81 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java @@ -45,8 +45,10 @@ import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.ChunkGenerator.BiomeGrid; import org.bukkit.generator.ChunkGenerator.ChunkData; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Arrays; public class GenChunk extends ScopedQueueCoordinator { @@ -65,15 +67,15 @@ public class GenChunk extends ScopedQueueCoordinator { this.biomes = Biome.values(); } - public ChunkData getChunkData() { + @Nullable public ChunkData getChunkData() { return this.chunkData; } - public void setChunkData(ChunkData chunkData) { + public void setChunkData(@Nonnull ChunkData chunkData) { this.chunkData = chunkData; } - public Chunk getChunk() { + @Nonnull public Chunk getChunk() { if (chunk == null) { World worldObj = BukkitUtil.getWorld(world); if (worldObj != null) { @@ -83,18 +85,18 @@ public class GenChunk extends ScopedQueueCoordinator { return chunk; } - public void setChunk(Chunk chunk) { + public void setChunk(@Nonnull Chunk chunk) { this.chunk = chunk; } - public void setChunk(ChunkWrapper wrap) { + public void setChunk(@Nonnull ChunkWrapper wrap) { chunk = null; world = wrap.world; chunkX = wrap.x; chunkZ = wrap.z; } - @Override public void fillBiome(BiomeType biomeType) { + @Override public void fillBiome(@Nonnull BiomeType biomeType) { if (biomeGrid == null) { return; } @@ -106,9 +108,8 @@ public class GenChunk extends ScopedQueueCoordinator { } } - @Override public void setCuboid(Location pos1, Location pos2, BlockState block) { - if (result != null && pos1.getX() == 0 && pos1.getZ() == 0 && pos2.getX() == 15 - && pos2.getZ() == 15) { + @Override public void setCuboid(@NotNull Location pos1, @NotNull Location pos2, @NotNull BlockState block) { + if (result != null && pos1.getX() == 0 && pos1.getZ() == 0 && pos2.getX() == 15 && pos2.getZ() == 15) { for (int y = pos1.getY(); y <= pos2.getY(); y++) { int layer = y >> 4; BlockState[] data = result[layer]; @@ -126,15 +127,14 @@ public class GenChunk extends ScopedQueueCoordinator { int maxX = Math.max(pos1.getX(), pos2.getX()); int maxY = Math.max(pos1.getY(), pos2.getY()); int maxZ = Math.max(pos1.getZ(), pos2.getZ()); - chunkData - .setRegion(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1, BukkitAdapter.adapt(block)); + chunkData.setRegion(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1, BukkitAdapter.adapt(block)); } - @Override public boolean setBiome(int x, int z, BiomeType biomeType) { + @Override public boolean setBiome(int x, int z, @NotNull BiomeType biomeType) { return setBiome(x, z, BukkitAdapter.adapt(biomeType)); } - public boolean setBiome(int x, int z, Biome biome) { + public boolean setBiome(int x, int z, @Nonnull Biome biome) { if (this.biomeGrid != null) { this.biomeGrid.setBiome(x, z, biome); return true; @@ -142,12 +142,11 @@ public class GenChunk extends ScopedQueueCoordinator { return false; } - @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { - return setBlock(x, y, z, PatternUtil - .apply(Preconditions.checkNotNull(pattern, "Pattern may not be null"), x, y, z)); + @Override public boolean setBlock(int x, int y, int z, @Nonnull @NotNull Pattern pattern) { + return setBlock(x, y, z, PatternUtil.apply(Preconditions.checkNotNull(pattern, "Pattern may not be null"), x, y, z)); } - @Override public boolean setBlock(int x, int y, int z, BlockState id) { + @Override public boolean setBlock(int x, int y, int z, @NotNull BlockState id) { if (this.result == null) { this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); return true; @@ -157,7 +156,7 @@ public class GenChunk extends ScopedQueueCoordinator { return true; } - private void storeCache(final int x, final int y, final int z, final BlockState id) { + private void storeCache(final int x, final int y, final int z, @Nonnull final BlockState id) { int i = y >> 4; BlockState[] v = this.result[i]; if (v == null) { @@ -167,7 +166,7 @@ public class GenChunk extends ScopedQueueCoordinator { v[j] = id; } - @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { + @Override public boolean setBlock(int x, int y, int z, @NotNull BaseBlock id) { if (this.result == null) { this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); return true; @@ -177,7 +176,7 @@ public class GenChunk extends ScopedQueueCoordinator { return true; } - @Override public BlockState getBlock(int x, int y, int z) { + @Override @Nullable public BlockState getBlock(int x, int y, int z) { int i = y >> 4; if (result == null) { return BukkitBlockUtil.get(chunkData.getType(x, y, z)); @@ -198,21 +197,19 @@ public class GenChunk extends ScopedQueueCoordinator { return chunk == null ? chunkZ : chunk.getZ(); } - @Override public com.sk89q.worldedit.world.World getWorld() { - return chunk == null ? - BukkitAdapter.adapt(Bukkit.getWorld(world)) : - BukkitAdapter.adapt(chunk.getWorld()); + @Override @Nonnull public com.sk89q.worldedit.world.World getWorld() { + return chunk == null ? BukkitAdapter.adapt(Bukkit.getWorld(world)) : BukkitAdapter.adapt(chunk.getWorld()); } - @Override public Location getMax() { + @Override @Nonnull public Location getMax() { return Location.at(getWorld().getName(), 15 + (getX() << 4), 255, 15 + (getZ() << 4)); } - @Override public Location getMin() { + @Override @Nonnull public Location getMin() { return Location.at(getWorld().getName(), getX() << 4, 0, getZ() << 4); } - public GenChunk clone() { + @Nonnull public GenChunk clone() { GenChunk toReturn = new GenChunk(); if (this.result != null) { for (int i = 0; i < this.result.length; i++) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java index 4e5bfb49b..8086d805a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java @@ -26,107 +26,23 @@ package com.plotsquared.bukkit.util; import com.google.inject.Singleton; -import com.plotsquared.core.PlotSquared; -import com.plotsquared.core.listener.WEExtent; -import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.ChunkManager; -import com.plotsquared.core.util.entity.EntityCategories; -import com.plotsquared.core.util.task.TaskManager; -import com.sk89q.worldedit.bukkit.BukkitAdapter; -import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.math.BlockVector2; -import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; -import com.sk89q.worldedit.world.block.BaseBlock; import io.papermc.lib.PaperLib; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Entity; import java.util.concurrent.CompletableFuture; -import static com.plotsquared.core.util.entity.EntityCategories.CAP_ANIMAL; -import static com.plotsquared.core.util.entity.EntityCategories.CAP_ENTITY; -import static com.plotsquared.core.util.entity.EntityCategories.CAP_MISC; -import static com.plotsquared.core.util.entity.EntityCategories.CAP_MOB; -import static com.plotsquared.core.util.entity.EntityCategories.CAP_MONSTER; -import static com.plotsquared.core.util.entity.EntityCategories.CAP_VEHICLE; - @Singleton public class BukkitChunkManager extends ChunkManager { public static boolean isIn(CuboidRegion region, int x, int z) { - return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX() - && z >= region.getMinimumPoint().getZ() && z <= region.getMaximumPoint().getZ(); + return x >= region.getMinimumPoint().getX() && x <= region.getMaximumPoint().getX() && z >= region.getMinimumPoint().getZ() && z <= region + .getMaximumPoint().getZ(); } - public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2, - CuboidRegion r1, CuboidRegion r2) { - ContentMap map = new ContentMap(); - int relX = r2.getMinimumPoint().getX() - r1.getMinimumPoint().getX(); - int relZ = r2.getMinimumPoint().getZ() - r1.getMinimumPoint().getZ(); - - map.saveEntitiesIn(pos1, r1, relX, relZ, true); - map.saveEntitiesIn(pos2, r2, -relX, -relZ, true); - - int sx = pos1.getX() << 4; - int sz = pos1.getZ() << 4; - - BukkitWorld bukkitWorld1 = new BukkitWorld(world1); - BukkitWorld bukkitWorld2 = new BukkitWorld(world2); - - QueueCoordinator queue1 = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(bukkitWorld1); - QueueCoordinator queue2 = - PlotSquared.platform().getGlobalBlockQueue().getNewQueue(bukkitWorld2); - - for (int x = Math.max(r1.getMinimumPoint().getX(), sx); - x <= Math.min(r1.getMaximumPoint().getX(), sx + 15); x++) { - for (int z = Math.max(r1.getMinimumPoint().getZ(), sz); - z <= Math.min(r1.getMaximumPoint().getZ(), sz + 15); z++) { - for (int y = 0; y < 256; y++) { - Block block1 = world1.getBlockAt(x, y, z); - BaseBlock baseBlock1 = bukkitWorld1.getFullBlock(BlockVector3.at(x, y, z)); - BlockData data1 = block1.getBlockData(); - - int xx = x + relX; - int zz = z + relZ; - - Block block2 = world2.getBlockAt(xx, y, zz); - BaseBlock baseBlock2 = bukkitWorld2.getFullBlock(BlockVector3.at(xx, y, zz)); - BlockData data2 = block2.getBlockData(); - - if (block1.isEmpty()) { - if (!block2.isEmpty()) { - queue1.setBlock(x, y, z, baseBlock2); - queue2.setBlock(xx, y, zz, WEExtent.AIRBASE); - } - } else if (block2.isEmpty()) { - queue1.setBlock(x, y, z, WEExtent.AIRBASE); - queue2.setBlock(xx, y, zz, baseBlock1); - } else if (block1.equals(block2)) { - if (!data1.matches(data2)) { - block1.setBlockData(data2); - block2.setBlockData(data1); - } - } else { - queue1.setBlock(x, y, z, baseBlock2); - queue2.setBlock(xx, y, zz, baseBlock1); - } - } - } - } - queue1.enqueue(); - queue2.enqueue(); - return map; - } - - @Override - public CompletableFuture loadChunk(String world, BlockVector2 chunkLoc, boolean force) { - return PaperLib - .getChunkAtAsync(BukkitUtil.getWorld(world), chunkLoc.getX(), chunkLoc.getZ(), force); + @Override public CompletableFuture loadChunk(String world, BlockVector2 chunkLoc, boolean force) { + return PaperLib.getChunkAtAsync(BukkitUtil.getWorld(world), chunkLoc.getX(), chunkLoc.getZ(), force); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 790b322de..61a215272 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -98,7 +98,6 @@ import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; -import java.util.UUID; import java.util.concurrent.Semaphore; import java.util.function.Consumer; import java.util.function.IntConsumer; @@ -108,8 +107,7 @@ import java.util.stream.Stream; @Singleton public class BukkitUtil extends WorldUtil { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + BukkitUtil.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + BukkitUtil.class.getSimpleName()); private final Collection tileEntityTypes = new HashSet<>(); /** @@ -131,9 +129,9 @@ public class BukkitUtil extends WorldUtil { * @return PlotSquared location */ @Nonnull public static Location adapt(@Nonnull final org.bukkit.Location location) { - return Location.at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), - MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), - MathMan.roundInt(location.getZ())); + return Location + .at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), + MathMan.roundInt(location.getZ())); } /** @@ -144,9 +142,9 @@ public class BukkitUtil extends WorldUtil { * @return PlotSquared location */ @Nonnull public static Location adaptComplete(@Nonnull final org.bukkit.Location location) { - return Location.at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), - MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), - MathMan.roundInt(location.getZ()), location.getYaw(), location.getPitch()); + return Location + .at(com.plotsquared.bukkit.util.BukkitWorld.of(location.getWorld()), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), + MathMan.roundInt(location.getZ()), location.getYaw(), location.getPitch()); } /** @@ -157,8 +155,7 @@ public class BukkitUtil extends WorldUtil { * @return Bukkit location */ @Nonnull public static org.bukkit.Location adapt(@Nonnull final Location location) { - return new org.bukkit.Location((World) location.getWorld().getPlatformWorld(), - location.getX(), location.getY(), location.getZ()); + return new org.bukkit.Location((World) location.getWorld().getPlatformWorld(), location.getX(), location.getY(), location.getZ()); } /** @@ -171,30 +168,24 @@ public class BukkitUtil extends WorldUtil { return Bukkit.getWorld(string); } - private static void ensureLoaded(@Nonnull final String world, final int x, final int z, - @Nonnull final Consumer chunkConsumer) { + private static void ensureLoaded(@Nonnull final String world, final int x, final int z, @Nonnull final Consumer chunkConsumer) { PaperLib.getChunkAtAsync(Objects.requireNonNull(getWorld(world)), x >> 4, z >> 4, true) .thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); } - private static void ensureLoaded(@Nonnull final Location location, - @Nonnull final Consumer chunkConsumer) { - PaperLib.getChunkAtAsync(adapt(location), true) - .thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); + private static void ensureLoaded(@Nonnull final Location location, @Nonnull final Consumer chunkConsumer) { + PaperLib.getChunkAtAsync(adapt(location), true).thenAccept(chunk -> ensureMainThread(chunkConsumer, chunk)); } - private static void ensureMainThread(@Nonnull final Consumer consumer, - @Nonnull final T value) { + private static void ensureMainThread(@Nonnull final Consumer consumer, @Nonnull final T value) { if (Bukkit.isPrimaryThread()) { consumer.accept(value); } else { - Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), - () -> consumer.accept(value)); + Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> consumer.accept(value)); } } - @Override public boolean isBlockSame(@Nonnull final BlockState block1, - @Nonnull final BlockState block2) { + @Override public boolean isBlockSame(@Nonnull final BlockState block1, @Nonnull final BlockState block2) { if (block1.equals(block2)) { return true; } @@ -207,19 +198,15 @@ public class BukkitUtil extends WorldUtil { return getWorld(worldName) != null; } - @Override public void getBiome(@Nonnull final String world, final int x, final int z, - @Nonnull final Consumer result) { - ensureLoaded(world, x, z, - chunk -> result.accept(BukkitAdapter.adapt(getWorld(world).getBiome(x, z)))); + @Override public void getBiome(@Nonnull final String world, final int x, final int z, @Nonnull final Consumer result) { + ensureLoaded(world, x, z, chunk -> result.accept(BukkitAdapter.adapt(getWorld(world).getBiome(x, z)))); } - @Override @Nonnull - public BiomeType getBiomeSynchronous(@Nonnull final String world, final int x, final int z) { + @Override @Nonnull public BiomeType getBiomeSynchronous(@Nonnull final String world, final int x, final int z) { return BukkitAdapter.adapt(Objects.requireNonNull(getWorld(world)).getBiome(x, z)); } - @Override public void getHighestBlock(@Nonnull final String world, final int x, final int z, - @Nonnull final IntConsumer result) { + @Override public void getHighestBlock(@Nonnull final String world, final int x, final int z, @Nonnull final IntConsumer result) { ensureLoaded(world, x, z, chunk -> { final World bukkitWorld = Objects.requireNonNull(getWorld(world)); // Skip top and bottom block @@ -245,8 +232,7 @@ public class BukkitUtil extends WorldUtil { }); } - @Override @Nonnegative - public int getHighestBlockSynchronous(@Nonnull final String world, final int x, final int z) { + @Override @Nonnegative public int getHighestBlockSynchronous(@Nonnull final String world, final int x, final int z) { final World bukkitWorld = Objects.requireNonNull(getWorld(world)); // Skip top and bottom block int air = 1; @@ -269,8 +255,7 @@ public class BukkitUtil extends WorldUtil { } @Override @Nonnull public String[] getSignSynchronous(@Nonnull final Location location) { - Block block = Objects.requireNonNull(getWorld(location.getWorldName())) - .getBlockAt(location.getX(), location.getY(), location.getZ()); + Block block = Objects.requireNonNull(getWorld(location.getWorldName())).getBlockAt(location.getX(), location.getY(), location.getZ()); try { return TaskManager.getPlatformImplementation().sync(() -> { if (block.getState() instanceof Sign) { @@ -287,9 +272,7 @@ public class BukkitUtil extends WorldUtil { @Override @Nonnull public Location getSpawn(@Nonnull final String world) { final org.bukkit.Location temp = getWorld(world).getSpawnLocation(); - return Location - .at(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), - temp.getPitch()); + return Location.at(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch()); } @Override public void setSpawn(@Nonnull final Location location) { @@ -307,8 +290,7 @@ public class BukkitUtil extends WorldUtil { } @Override @SuppressWarnings("deprecation") - public void setSign(@Nonnull final String worldName, final int x, final int y, final int z, - @Nonnull final String[] lines) { + public void setSign(@Nonnull final String worldName, final int x, final int y, final int z, @Nonnull final String[] lines) { ensureLoaded(worldName, x, z, chunk -> { final World world = getWorld(worldName); final Block block = world.getBlockAt(x, y, z); @@ -346,25 +328,20 @@ public class BukkitUtil extends WorldUtil { }); } - @Override @Nonnull - public StringComparison.ComparisonResult getClosestBlock(@Nonnull String name) { + @Override @Nonnull public StringComparison.ComparisonResult getClosestBlock(@Nonnull String name) { BlockState state = BlockUtil.get(name); return new StringComparison().new ComparisonResult(1, state); } - @Override - public void setBiomes(@Nonnull final String worldName, @Nonnull final CuboidRegion region, - @Nonnull final BiomeType biomeType) { + @Override public void setBiomes(@Nonnull final String worldName, @Nonnull final CuboidRegion region, @Nonnull final BiomeType biomeType) { final World world = getWorld(worldName); if (world == null) { - logger.warn("[P2] An error occured while setting the biome because the world was null", - new RuntimeException()); + logger.warn("[P2] An error occured while setting the biome because the world was null", new RuntimeException()); return; } final Biome biome = BukkitAdapter.adapt(biomeType); for (int x = region.getMinimumPoint().getX(); x <= region.getMaximumPoint().getX(); x++) { - for (int z = region.getMinimumPoint().getZ(); - z <= region.getMaximumPoint().getZ(); z++) { + for (int z = region.getMinimumPoint().getZ(); z <= region.getMaximumPoint().getZ(); z++) { if (world.getBiome(x, z) != biome) { world.setBiome(x, z, biome); } @@ -372,8 +349,7 @@ public class BukkitUtil extends WorldUtil { } } - @Override @Nonnull - public com.sk89q.worldedit.world.World getWeWorld(@Nonnull final String world) { + @Override @Nonnull public com.sk89q.worldedit.world.World getWeWorld(@Nonnull final String world) { return new BukkitWorld(Bukkit.getWorld(world)); } @@ -381,21 +357,17 @@ public class BukkitUtil extends WorldUtil { Bukkit.getWorld(world).refreshChunk(x, z); } - @Override public void getBlock(@Nonnull final Location location, - @Nonnull final Consumer result) { + @Override public void getBlock(@Nonnull final Location location, @Nonnull final Consumer result) { ensureLoaded(location, chunk -> { final World world = getWorld(location.getWorldName()); - final Block block = Objects.requireNonNull(world) - .getBlockAt(location.getX(), location.getY(), location.getZ()); - result.accept(Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())) - .getDefaultState()); + final Block block = Objects.requireNonNull(world).getBlockAt(location.getX(), location.getY(), location.getZ()); + result.accept(Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())).getDefaultState()); }); } @Override @Nonnull public BlockState getBlockSynchronous(@Nonnull final Location location) { final World world = getWorld(location.getWorldName()); - final Block block = Objects.requireNonNull(world) - .getBlockAt(location.getX(), location.getY(), location.getZ()); + final Block block = Objects.requireNonNull(world).getBlockAt(location.getX(), location.getY(), location.getZ()); return Objects.requireNonNull(BukkitAdapter.asBlockType(block.getType())).getDefaultState(); } @@ -407,18 +379,15 @@ public class BukkitUtil extends WorldUtil { return Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).getFoodLevel(); } - @Override - public void setHealth(@Nonnull final PlotPlayer player, @Nonnegative final double health) { + @Override public void setHealth(@Nonnull final PlotPlayer player, @Nonnegative final double health) { Objects.requireNonNull(Bukkit.getPlayer(player.getUUID())).setHealth(health); } - @Override public void setFoodLevel(@Nonnull final PlotPlayer player, - @Nonnegative final int foodLevel) { + @Override public void setFoodLevel(@Nonnull final PlotPlayer player, @Nonnegative final int foodLevel) { Bukkit.getPlayer(player.getUUID()).setFoodLevel(foodLevel); } - @Override @Nonnull public Set getTypesInCategory( - @Nonnull final String category) { + @Override @Nonnull public Set getTypesInCategory(@Nonnull final String category) { final Collection> allowedInterfaces = new HashSet<>(); switch (category) { case "animal": { @@ -507,22 +476,17 @@ public class BukkitUtil extends WorldUtil { tileEntityTypes.addAll(BlockCategories.FLOWER_POTS.getAll()); // Individual Types // Add these from strings - Stream.of("barrel", "beacon", "beehive", "bee_nest", "bell", "blast_furnace", - "brewing_stand", "campfire", "chest", "ender_chest", "trapped_chest", - "command_block", "end_gateway", "hopper", "jigsaw", "jubekox", "lectern", - "note_block", "black_shulker_box", "blue_shulker_box", "brown_shulker_box", - "cyan_shulker_box", "gray_shulker_box", "green_shulker_box", - "light_blue_shulker_box", "light_gray_shulker_box", "lime_shulker_box", - "magenta_shulker_box", "orange_shulker_box", "pink_shulker_box", - "purple_shulker_box", "red_shulker_box", "shulker_box", "white_shulker_box", - "yellow_shulker_box", "smoker", "structure_block", "structure_void") + Stream.of("barrel", "beacon", "beehive", "bee_nest", "bell", "blast_furnace", "brewing_stand", "campfire", "chest", "ender_chest", + "trapped_chest", "command_block", "end_gateway", "hopper", "jigsaw", "jubekox", "lectern", "note_block", "black_shulker_box", + "blue_shulker_box", "brown_shulker_box", "cyan_shulker_box", "gray_shulker_box", "green_shulker_box", "light_blue_shulker_box", + "light_gray_shulker_box", "lime_shulker_box", "magenta_shulker_box", "orange_shulker_box", "pink_shulker_box", "purple_shulker_box", + "red_shulker_box", "shulker_box", "white_shulker_box", "yellow_shulker_box", "smoker", "structure_block", "structure_void") .map(BlockTypes::get).filter(Objects::nonNull).forEach(tileEntityTypes::add); } return this.tileEntityTypes; } - @Override @Nonnegative - public int getTileEntityCount(@Nonnull final String world, @Nonnull final BlockVector2 chunk) { + @Override @Nonnegative public int getTileEntityCount(@Nonnull final String world, @Nonnull final BlockVector2 chunk) { return Objects.requireNonNull(getWorld(world)). getChunkAt(chunk.getBlockX(), chunk.getBlockZ()).getTileEntities().length; } @@ -538,16 +502,13 @@ public class BukkitUtil extends WorldUtil { final Semaphore semaphore = new Semaphore(1); try { semaphore.acquire(); - Bukkit.getScheduler() - .runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> { - for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)) - .getLoadedChunks()) { - BlockVector2 loc = - BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5); - chunks.add(loc); - } - semaphore.release(); - }); + Bukkit.getScheduler().runTask(BukkitPlatform.getPlugin(BukkitPlatform.class), () -> { + for (Chunk chunk : Objects.requireNonNull(Bukkit.getWorld(world)).getLoadedChunks()) { + BlockVector2 loc = BlockVector2.at(chunk.getX() >> 5, chunk.getZ() >> 5); + chunks.add(loc); + } + semaphore.release(); + }); semaphore.acquireUninterruptibly(); } catch (final Exception e) { e.printStackTrace(); diff --git a/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java b/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java index 9c620c148..3d5e9897e 100644 --- a/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java +++ b/Core/src/main/java/com/plotsquared/core/components/ComponentPresetManager.java @@ -62,20 +62,17 @@ import java.util.stream.Collectors; public class ComponentPresetManager { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + ComponentPresetManager.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + ComponentPresetManager.class.getSimpleName()); private final List presets; private final String guiName; private final EconHandler econHandler; private final InventoryUtil inventoryUtil; - @Inject public ComponentPresetManager(@Nullable final EconHandler econHandler, - @Nonnull final InventoryUtil inventoryUtil) { + @Inject public ComponentPresetManager(@Nullable final EconHandler econHandler, @Nonnull final InventoryUtil inventoryUtil) { this.econHandler = econHandler; this.inventoryUtil = inventoryUtil; - final File file = new File(Objects.requireNonNull(PlotSquared.platform()).getDirectory(), - "components.yml"); + final File file = new File(Objects.requireNonNull(PlotSquared.platform()).getDirectory(), "components.yml"); if (!file.exists()) { boolean created = false; try { @@ -106,16 +103,13 @@ public class ComponentPresetManager { this.guiName = yamlConfiguration.getString("title", "&6Plot Components"); if (yamlConfiguration.contains("presets")) { - this.presets = - yamlConfiguration.getMapList("presets").stream().map(o -> (Map) o) - .map(ComponentPreset::deserialize).collect(Collectors.toList()); + this.presets = yamlConfiguration.getMapList("presets").stream().map(o -> (Map) o).map(ComponentPreset::deserialize) + .collect(Collectors.toList()); } else { final List defaultPreset = Collections.singletonList( - new ComponentPreset(ClassicPlotManagerComponent.FLOOR, "##wool", 0, "", - "&6D&ai&cs&ec&bo &2F&3l&do&9o&4r", Arrays.asList("&6Spice up your plot floor"), - ItemTypes.YELLOW_WOOL)); - yamlConfiguration.set("presets", defaultPreset.stream().map(ComponentPreset::serialize) - .collect(Collectors.toList())); + new ComponentPreset(ClassicPlotManagerComponent.FLOOR, "##wool", 0, "", "&6D&ai&cs&ec&bo &2F&3l&do&9o&4r", + Arrays.asList("&6Spice up your plot floor"), ItemTypes.YELLOW_WOOL)); + yamlConfiguration.set("presets", defaultPreset.stream().map(ComponentPreset::serialize).collect(Collectors.toList())); try { yamlConfiguration.save(file); } catch (final IOException e) { @@ -143,93 +137,84 @@ public class ComponentPresetManager { } else if (!plot.hasOwner()) { Captions.PLOT_UNOWNED.send(player); return null; - } else if (!plot.isOwner(player.getUUID()) && !plot.getTrusted() - .contains(player.getUUID())) { + } else if (!plot.isOwner(player.getUUID()) && !plot.getTrusted().contains(player.getUUID())) { Captions.NO_PLOT_PERMS.send(player); return null; } final List allowedPresets = new ArrayList<>(this.presets.size()); for (final ComponentPreset componentPreset : this.presets) { - if (!componentPreset.getPermission().isEmpty() && !Permissions - .hasPermission(player, componentPreset.getPermission())) { + if (!componentPreset.getPermission().isEmpty() && !Permissions.hasPermission(player, componentPreset.getPermission())) { continue; } allowedPresets.add(componentPreset); } final int size = (int) Math.ceil((double) allowedPresets.size() / 9.0D); - final PlotInventory plotInventory = - new PlotInventory(this.inventoryUtil, player, size, this.guiName) { - @Override public boolean onClick(final int index) { - if (!player.getCurrentPlot().equals(plot)) { - return false; - } - - if (index < 0 || index >= allowedPresets.size()) { - return false; - } - - final ComponentPreset componentPreset = allowedPresets.get(index); - if (componentPreset == null) { - return false; - } - - if (plot.getRunning() > 0) { - Captions.WAIT_FOR_TIMER.send(player); - return false; - } - - final Pattern pattern = - PatternUtil.parse(null, componentPreset.getPattern(), false); - if (pattern == null) { - Captions.PRESET_INVALID.send(player); - return false; - } - - if (componentPreset.getCost() > 0.0D && econHandler != null && plot.getArea() - .useEconomy()) { - if (econHandler.getMoney(player) < componentPreset.getCost()) { - Captions.PRESET_CANNOT_AFFORD.send(player); - return false; - } else { - econHandler.withdrawMoney(player, componentPreset.getCost()); - Captions.REMOVED_BALANCE.send(player, componentPreset.getCost() + ""); - } - } - - BackupManager.backup(player, plot, () -> { - plot.addRunning(); - QueueCoordinator queue = plot.getArea().getQueue(); - for (Plot current : plot.getConnectedPlots()) { - current.setComponent(componentPreset.getComponent().name(), pattern, - queue); - } - queue.setCompleteTask(plot::removeRunning); - queue.enqueue(); - MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); - }); + final PlotInventory plotInventory = new PlotInventory(this.inventoryUtil, player, size, this.guiName) { + @Override public boolean onClick(final int index) { + if (!player.getCurrentPlot().equals(plot)) { return false; } - }; + + if (index < 0 || index >= allowedPresets.size()) { + return false; + } + + final ComponentPreset componentPreset = allowedPresets.get(index); + if (componentPreset == null) { + return false; + } + + if (plot.getRunning() > 0) { + Captions.WAIT_FOR_TIMER.send(player); + return false; + } + + final Pattern pattern = PatternUtil.parse(null, componentPreset.getPattern(), false); + if (pattern == null) { + Captions.PRESET_INVALID.send(player); + return false; + } + + if (componentPreset.getCost() > 0.0D && econHandler != null && plot.getArea().useEconomy()) { + if (econHandler.getMoney(player) < componentPreset.getCost()) { + Captions.PRESET_CANNOT_AFFORD.send(player); + return false; + } else { + econHandler.withdrawMoney(player, componentPreset.getCost()); + Captions.REMOVED_BALANCE.send(player, componentPreset.getCost() + ""); + } + } + + BackupManager.backup(player, plot, () -> { + plot.addRunning(); + QueueCoordinator queue = plot.getArea().getQueue(); + for (Plot current : plot.getConnectedPlots()) { + current.setComponent(componentPreset.getComponent().name(), pattern, queue); + } + queue.setCompleteTask(plot::removeRunning); + queue.enqueue(); + MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); + }); + return false; + } + }; for (int i = 0; i < allowedPresets.size(); i++) { final ComponentPreset preset = allowedPresets.get(i); final List lore = new ArrayList<>(); if (preset.getCost() > 0 && this.econHandler != null && plot.getArea().useEconomy()) { - lore.add(Captions.PRESET_LORE_COST.getTranslated() - .replace("%cost%", String.format("%.2f", preset.getCost()))); + lore.add(Captions.PRESET_LORE_COST.getTranslated().replace("%cost%", String.format("%.2f", preset.getCost()))); } - lore.add(Captions.PRESET_LORE_COMPONENT.getTranslated() - .replace("%component%", preset.getComponent().name().toLowerCase())); + lore.add(Captions.PRESET_LORE_COMPONENT.getTranslated().replace("%component%", preset.getComponent().name().toLowerCase())); lore.removeIf(String::isEmpty); if (!lore.isEmpty()) { lore.add("&6"); } lore.addAll(preset.getDescription()); plotInventory.setItem(i, - new PlotItemStack(preset.getIcon().getId().replace("minecraft:", ""), 1, - preset.getDisplayName(), lore.toArray(new String[0]))); + new PlotItemStack(preset.getIcon().getId().replace("minecraft:", ""), 1, preset.getDisplayName(), lore.toArray(new String[0]))); } return plotInventory; diff --git a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java index 8c797ba45..f888f9bd9 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java @@ -54,8 +54,11 @@ public class AugmentedUtils { enabled = true; } - public static boolean generate(@Nullable Object chunkObject, @Nonnull final String world, - final int chunkX, final int chunkZ, QueueCoordinator queue) { + public static boolean generate(@Nullable Object chunkObject, + @Nonnull final String world, + final int chunkX, + final int chunkZ, + QueueCoordinator queue) { if (!enabled) { return false; } @@ -67,8 +70,7 @@ public class AugmentedUtils { // entire chunk CuboidRegion region = RegionUtil.createRegion(blockX, blockX + 15, blockZ, blockZ + 15); // Query for plot areas in the chunk - final Set areas = - PlotSquared.get().getPlotAreaManager().getPlotAreasSet(world, region); + final Set areas = PlotSquared.get().getPlotAreaManager().getPlotAreasSet(world, region); if (areas.isEmpty()) { return false; } @@ -89,8 +91,7 @@ public class AugmentedUtils { // Mask if (queue == null) { enqueue = true; - queue = PlotSquared.platform().getGlobalBlockQueue() - .getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); + queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); if (chunkObject != null) { queue.setChunkObject(chunkObject); } @@ -138,8 +139,7 @@ public class AugmentedUtils { continue; } generationResult = true; - secondaryMask = new LocationOffsetDelegateQueueCoordinator(canPlace, blockX, blockZ, - primaryMask); + secondaryMask = new LocationOffsetDelegateQueueCoordinator(canPlace, blockX, blockZ, primaryMask); } else { secondaryMask = primaryMask; for (int x = relativeBottomX; x <= relativeTopX; x++) { @@ -159,8 +159,7 @@ public class AugmentedUtils { } ScopedQueueCoordinator scoped = - new ScopedQueueCoordinator(secondaryMask, Location.at(world, blockX, 0, blockZ), - Location.at(world, blockX + 15, 255, blockZ + 15)); + new ScopedQueueCoordinator(secondaryMask, Location.at(world, blockX, 0, blockZ), Location.at(world, blockX + 15, 255, blockZ + 15)); generator.generateChunk(scoped, area); generator.populateChunk(scoped, area); } diff --git a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java index c1de3c0c5..7c2263954 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java @@ -40,6 +40,7 @@ import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.block.BlockTypes; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -54,17 +55,15 @@ public class ClassicPlotManager extends SquarePlotManager { private final ClassicPlotWorld classicPlotWorld; private final RegionManager regionManager; - public ClassicPlotManager(@Nonnull final ClassicPlotWorld classicPlotWorld, - @Nonnull final RegionManager regionManager) { + public ClassicPlotManager(@Nonnull final ClassicPlotWorld classicPlotWorld, @Nonnull final RegionManager regionManager) { super(classicPlotWorld, regionManager); this.classicPlotWorld = classicPlotWorld; this.regionManager = regionManager; } - @Override public boolean setComponent(PlotId plotId, String component, Pattern blocks, - @Nullable QueueCoordinator queue) { - final Optional componentOptional = - ClassicPlotManagerComponent.fromString(component); + @Override + public boolean setComponent(@NotNull PlotId plotId, @NotNull String component, @NotNull Pattern blocks, @Nullable QueueCoordinator queue) { + final Optional componentOptional = ClassicPlotManagerComponent.fromString(component); if (componentOptional.isPresent()) { switch (componentOptional.get()) { case FLOOR: @@ -88,55 +87,50 @@ public class ClassicPlotManager extends SquarePlotManager { return false; } - @Override public boolean unClaimPlot(Plot plot, @Nullable Runnable whenDone, - @Nullable QueueCoordinator queue) { + @Override public boolean unClaimPlot(@NotNull Plot plot, @Nullable Runnable whenDone, @Nullable QueueCoordinator queue) { setWallFilling(plot.getId(), classicPlotWorld.WALL_FILLING.toPattern(), queue); - if (!classicPlotWorld.WALL_BLOCK.isAir() || !classicPlotWorld.WALL_BLOCK - .equals(classicPlotWorld.CLAIMED_WALL_BLOCK)) { + if (!classicPlotWorld.WALL_BLOCK.isAir() || !classicPlotWorld.WALL_BLOCK.equals(classicPlotWorld.CLAIMED_WALL_BLOCK)) { setWall(plot.getId(), classicPlotWorld.WALL_BLOCK.toPattern(), queue); } TaskManager.runTask(whenDone); return true; } - public boolean setFloor(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { - Plot plot = classicPlotWorld.getPlotAbs(plotId); - if (plot != null && plot.isBasePlot()) { - return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, - classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.PLOT_HEIGHT, queue); - } - return false; - } - - public boolean setAll(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { + public boolean setFloor(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); if (plot != null && plot.isBasePlot()) { return this.regionManager - .setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, getWorldHeight(), - queue); + .setCuboids(classicPlotWorld, plot.getRegions(), blocks, classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.PLOT_HEIGHT, queue); } return false; } - public boolean setAir(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { + public boolean setAll(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); if (plot != null && plot.isBasePlot()) { - return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, - classicPlotWorld.PLOT_HEIGHT + 1, getWorldHeight(), queue); + return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, getWorldHeight(), queue); } return false; } - public boolean setMain(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { + public boolean setAir(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { + Plot plot = classicPlotWorld.getPlotAbs(plotId); + if (plot != null && plot.isBasePlot()) { + return this.regionManager + .setCuboids(classicPlotWorld, plot.getRegions(), blocks, classicPlotWorld.PLOT_HEIGHT + 1, getWorldHeight(), queue); + } + return false; + } + + public boolean setMain(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); if (plot == null || plot.isBasePlot()) { - return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, - classicPlotWorld.PLOT_HEIGHT - 1, queue); + return this.regionManager.setCuboids(classicPlotWorld, plot.getRegions(), blocks, 1, classicPlotWorld.PLOT_HEIGHT - 1, queue); } return false; } - public boolean setMiddle(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { + public boolean setMiddle(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); if (plot == null || !plot.isBasePlot()) { return false; @@ -155,7 +149,7 @@ public class ClassicPlotManager extends SquarePlotManager { return !enqueue || queue.enqueue(); } - public boolean setOutline(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { + public boolean setOutline(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { if (classicPlotWorld.ROAD_WIDTH == 0) { return false; } @@ -214,19 +208,15 @@ public class ClassicPlotManager extends SquarePlotManager { } if (plot.isBasePlot()) { for (CuboidRegion region : plot.getRegions()) { - Location pos1 = Location - .at(classicPlotWorld.getWorldName(), region.getMinimumPoint().getX(), maxY, - region.getMinimumPoint().getZ()); - Location pos2 = Location - .at(classicPlotWorld.getWorldName(), region.getMaximumPoint().getX(), maxY, - region.getMaximumPoint().getZ()); + Location pos1 = Location.at(classicPlotWorld.getWorldName(), region.getMinimumPoint().getX(), maxY, region.getMinimumPoint().getZ()); + Location pos2 = Location.at(classicPlotWorld.getWorldName(), region.getMaximumPoint().getX(), maxY, region.getMaximumPoint().getZ()); queue.setCuboid(pos1, pos2, blocks); } } return !enqueue || queue.enqueue(); } - public boolean setWallFilling(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { + public boolean setWallFilling(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { if (classicPlotWorld.ROAD_WIDTH == 0) { return false; } @@ -240,9 +230,7 @@ public class ClassicPlotManager extends SquarePlotManager { if (plot == null) { return false; } - Location bot = plot.getExtendedBottomAbs() - .subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, - plot.getMerged(Direction.NORTH) ? 0 : 1); + Location bot = plot.getExtendedBottomAbs().subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1); boolean enqueue = false; @@ -269,8 +257,7 @@ public class ClassicPlotManager extends SquarePlotManager { } if (!plot.getMerged(Direction.SOUTH)) { int z = top.getZ(); - for (int x = bot.getX(); - x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) { + for (int x = bot.getX(); x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) { for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) { queue.setBlock(x, y, z, blocks); } @@ -278,8 +265,7 @@ public class ClassicPlotManager extends SquarePlotManager { } if (!plot.getMerged(Direction.EAST)) { int x = top.getX(); - for (int z = bot.getZ(); - z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) { + for (int z = bot.getZ(); z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) { for (int y = 1; y <= classicPlotWorld.WALL_HEIGHT; y++) { queue.setBlock(x, y, z, blocks); } @@ -288,7 +274,7 @@ public class ClassicPlotManager extends SquarePlotManager { return !enqueue || queue.enqueue(); } - public boolean setWall(PlotId plotId, Pattern blocks, @Nullable QueueCoordinator queue) { + public boolean setWall(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { if (classicPlotWorld.ROAD_WIDTH == 0) { return false; } @@ -302,9 +288,7 @@ public class ClassicPlotManager extends SquarePlotManager { if (plot == null) { return false; } - Location bot = plot.getExtendedBottomAbs() - .subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, - plot.getMerged(Direction.NORTH) ? 0 : 1); + Location bot = plot.getExtendedBottomAbs().subtract(plot.getMerged(Direction.WEST) ? 0 : 1, 0, plot.getMerged(Direction.NORTH) ? 0 : 1); Location top = plot.getExtendedTopAbs().add(1, 0, 1); boolean enqueue = false; @@ -328,15 +312,13 @@ public class ClassicPlotManager extends SquarePlotManager { } if (!plot.getMerged(Direction.SOUTH)) { int z = top.getZ(); - for (int x = bot.getX(); - x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) { + for (int x = bot.getX(); x < top.getX() + (plot.getMerged(Direction.EAST) ? 0 : 1); x++) { queue.setBlock(x, y, z, blocks); } } if (!plot.getMerged(Direction.EAST)) { int x = top.getX(); - for (int z = bot.getZ(); - z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) { + for (int z = bot.getZ(); z < top.getZ() + (plot.getMerged(Direction.SOUTH) ? 0 : 1); z++) { queue.setBlock(x, y, z, blocks); } } @@ -346,7 +328,7 @@ public class ClassicPlotManager extends SquarePlotManager { /** * PLOT MERGING. */ - @Override public boolean createRoadEast(Plot plot, @Nullable QueueCoordinator queue) { + @Override public boolean createRoadEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) { Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; @@ -361,36 +343,25 @@ public class ClassicPlotManager extends SquarePlotManager { } int maxY = getWorldHeight(); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex, maxY, ez - 1), - BlockTypes.AIR.getDefaultState()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 0, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex, 0, ez - 1), + queue.setCuboid( + Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex, maxY, ez - 1), BlockTypes.AIR.getDefaultState()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 0, sz + 1), Location.at(classicPlotWorld.getWorldName(), ex, 0, ez - 1), BlockUtil.get((short) 7, (byte) 0)); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1), - Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT, ez - 1), - classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid(Location - .at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, sz + 1), - Location - .at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, ez - 1), - classicPlotWorld.WALL_BLOCK.toPattern()); + Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.WALL_HEIGHT + 1, ez - 1), classicPlotWorld.WALL_BLOCK.toPattern()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), ex, 1, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT, ez - 1), - classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid(Location - .at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, sz + 1), - Location - .at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, ez - 1), - classicPlotWorld.WALL_BLOCK.toPattern()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), Location - .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), - classicPlotWorld.ROAD_BLOCK.toPattern()); + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT, ez - 1), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.WALL_HEIGHT + 1, ez - 1), classicPlotWorld.WALL_BLOCK.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); return !enqueue || queue.enqueue(); } - @Override public boolean createRoadSouth(Plot plot, @Nullable QueueCoordinator queue) { + @Override public boolean createRoadSouth(@NotNull Plot plot, @Nullable QueueCoordinator queue) { Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId()); int sz = pos2.getZ() + 1; @@ -404,37 +375,26 @@ public class ClassicPlotManager extends SquarePlotManager { enqueue = true; } - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, - Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location - .at(classicPlotWorld.getWorldName(), ex - 1, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), + queue.setCuboid( + Location.at(classicPlotWorld.getWorldName(), sx + 1, Math.min(classicPlotWorld.WALL_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.getPlotManager().getWorldHeight(), ez), BlockTypes.AIR.getDefaultState()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz), - Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez), + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz), Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez), BlockUtil.get((short) 7, (byte) 0)); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, sz), - classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid(Location - .at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, sz), - Location - .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, sz), - classicPlotWorld.WALL_BLOCK.toPattern()); + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, sz), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, sz), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, sz), classicPlotWorld.WALL_BLOCK.toPattern()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, ez), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, ez), - classicPlotWorld.WALL_FILLING.toPattern()); - queue.setCuboid(Location - .at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, ez), - Location - .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, ez), - classicPlotWorld.WALL_BLOCK.toPattern()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), Location - .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), - classicPlotWorld.ROAD_BLOCK.toPattern()); + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT, ez), classicPlotWorld.WALL_FILLING.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.WALL_HEIGHT + 1, ez), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.WALL_HEIGHT + 1, ez), classicPlotWorld.WALL_BLOCK.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); return !enqueue || queue.enqueue(); } - @Override public boolean createRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { + @Override public boolean createRoadSouthEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) { Location pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; @@ -447,21 +407,17 @@ public class ClassicPlotManager extends SquarePlotManager { enqueue = true; } - queue.setCuboid(Location - .at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.ROAD_HEIGHT + 1, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex - 1, - classicPlotWorld.getPlotManager().getWorldHeight(), ez - 1), + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.ROAD_HEIGHT + 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.getPlotManager().getWorldHeight(), ez - 1), BlockTypes.AIR.getDefaultState()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 0, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez - 1), - BlockUtil.get((short) 7, (byte) 0)); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), Location - .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), - classicPlotWorld.ROAD_BLOCK.toPattern()); + Location.at(classicPlotWorld.getWorldName(), ex - 1, 0, ez - 1), BlockUtil.get((short) 7, (byte) 0)); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); return !enqueue || queue.enqueue(); } - @Override public boolean removeRoadEast(Plot plot, @Nullable QueueCoordinator queue) { + @Override public boolean removeRoadEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) { Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; @@ -475,22 +431,18 @@ public class ClassicPlotManager extends SquarePlotManager { enqueue = true; } - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location - .at(classicPlotWorld.getWorldName(), ex, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), - BlockTypes.AIR.getDefaultState()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1), Location - .at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez - 1), - classicPlotWorld.MAIN_BLOCK.toPattern()); - queue.setCuboid( - Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz + 1), - Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez - 1), - classicPlotWorld.TOP_BLOCK.toPattern()); + queue + .setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez), + BlockTypes.AIR.getDefaultState()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez - 1), classicPlotWorld.MAIN_BLOCK.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz + 1), + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez - 1), classicPlotWorld.TOP_BLOCK.toPattern()); return !enqueue || queue.enqueue(); } - @Override public boolean removeRoadSouth(Plot plot, @Nullable QueueCoordinator queue) { + @Override public boolean removeRoadSouth(@NotNull Plot plot, @Nullable QueueCoordinator queue) { Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId()); int sz = pos2.getZ() + 1; @@ -504,22 +456,18 @@ public class ClassicPlotManager extends SquarePlotManager { enqueue = true; } - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location - .at(classicPlotWorld.getWorldName(), ex, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), - BlockTypes.AIR.getDefaultState()); - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz), Location - .at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT - 1, ez), - classicPlotWorld.MAIN_BLOCK.toPattern()); - queue.setCuboid( - Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.PLOT_HEIGHT, sz), - Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT, ez), - classicPlotWorld.TOP_BLOCK.toPattern()); + queue + .setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez), + BlockTypes.AIR.getDefaultState()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT - 1, ez), classicPlotWorld.MAIN_BLOCK.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, classicPlotWorld.PLOT_HEIGHT, sz), + Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.PLOT_HEIGHT, ez), classicPlotWorld.TOP_BLOCK.toPattern()); return !enqueue || queue.enqueue(); } - @Override public boolean removeRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { + @Override public boolean removeRoadSouthEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) { Location location = getPlotTopLocAbs(plot.getId()); int sx = location.getX() + 1; int ex = sx + classicPlotWorld.ROAD_WIDTH - 1; @@ -532,18 +480,14 @@ public class ClassicPlotManager extends SquarePlotManager { enqueue = true; } - queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, - Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), Location - .at(classicPlotWorld.getWorldName(), ex, - classicPlotWorld.getPlotManager().getWorldHeight(), ez), - BlockTypes.AIR.getDefaultState()); + queue + .setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, Math.min(classicPlotWorld.PLOT_HEIGHT, classicPlotWorld.ROAD_HEIGHT) + 1, sz), + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.getPlotManager().getWorldHeight(), ez), + BlockTypes.AIR.getDefaultState()); queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, 1, sz), - Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez), - classicPlotWorld.MAIN_BLOCK.toPattern()); - queue.setCuboid( - Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz), - Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez), - classicPlotWorld.TOP_BLOCK.toPattern()); + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT - 1, ez), classicPlotWorld.MAIN_BLOCK.toPattern()); + queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx, classicPlotWorld.PLOT_HEIGHT, sz), + Location.at(classicPlotWorld.getWorldName(), ex, classicPlotWorld.PLOT_HEIGHT, ez), classicPlotWorld.TOP_BLOCK.toPattern()); return !enqueue || queue.enqueue(); } @@ -552,8 +496,7 @@ public class ClassicPlotManager extends SquarePlotManager { * * @return false if part of the merge failed, otherwise true if successful. */ - @Override public boolean finishPlotMerge(List plotIds, - @Nullable QueueCoordinator queue) { + @Override public boolean finishPlotMerge(@NotNull List plotIds, @Nullable QueueCoordinator queue) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { for (PlotId plotId : plotIds) { @@ -569,8 +512,7 @@ public class ClassicPlotManager extends SquarePlotManager { return true; } - @Override - public boolean finishPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean finishPlotUnlink(@NotNull List plotIds, @Nullable QueueCoordinator queue) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { for (PlotId id : plotIds) { @@ -580,17 +522,15 @@ public class ClassicPlotManager extends SquarePlotManager { return true; // return false if unlink has been denied } - @Override - public boolean startPlotMerge(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean startPlotMerge(@NotNull List plotIds, @Nullable QueueCoordinator queue) { return true; } - @Override - public boolean startPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean startPlotUnlink(@NotNull List plotIds, @Nullable QueueCoordinator queue) { return true; } - @Override public boolean claimPlot(Plot plot, @Nullable QueueCoordinator queue) { + @Override public boolean claimPlot(@NotNull Plot plot, @Nullable QueueCoordinator queue) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; if (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK)) { return setWall(plot.getId(), claim.toPattern(), queue); @@ -598,7 +538,7 @@ public class ClassicPlotManager extends SquarePlotManager { return true; } - @Override public String[] getPlotComponents(PlotId plotId) { + @Override public String[] getPlotComponents(@NotNull PlotId plotId) { return ClassicPlotManagerComponent.stringValues(); } @@ -608,12 +548,10 @@ public class ClassicPlotManager extends SquarePlotManager { * @param plot The plot * @return The location where a sign should be */ - @Override public Location getSignLoc(Plot plot) { + @Override public Location getSignLoc(@NotNull Plot plot) { plot = plot.getBasePlot(false); final Location bot = plot.getBottomAbs(); - return Location - .at(classicPlotWorld.getWorldName(), bot.getX() - 1, classicPlotWorld.ROAD_HEIGHT + 1, - bot.getZ() - 2); + return Location.at(classicPlotWorld.getWorldName(), bot.getX() - 1, classicPlotWorld.ROAD_HEIGHT + 1, bot.getZ() - 2); } } diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java index 55b6091f5..64acf40ad 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java @@ -47,8 +47,10 @@ import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockTypes; import lombok.Getter; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -62,37 +64,26 @@ public class HybridPlotManager extends ClassicPlotManager { @Getter private final HybridPlotWorld hybridPlotWorld; private final RegionManager regionManager; - public HybridPlotManager(@Nonnull final HybridPlotWorld hybridPlotWorld, - @Nonnull final RegionManager regionManager) { + public HybridPlotManager(@Nonnull final HybridPlotWorld hybridPlotWorld, @Nonnull final RegionManager regionManager) { super(hybridPlotWorld, regionManager); this.hybridPlotWorld = hybridPlotWorld; this.regionManager = regionManager; } @Override public void exportTemplate() throws IOException { - HashSet files = Sets.newHashSet( - new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", - Template.getBytes(hybridPlotWorld))); - String dir = - "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + hybridPlotWorld - .getWorldName() + File.separator; + HashSet files = Sets.newHashSet(new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", Template.getBytes(hybridPlotWorld))); + String dir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + hybridPlotWorld.getWorldName() + File.separator; try { - File sideRoad = - FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "sideroad.schem"); - String newDir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator - + "__TEMP_DIR__" + File.separator; + File sideRoad = FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "sideroad.schem"); + String newDir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + "__TEMP_DIR__" + File.separator; if (sideRoad.exists()) { - files.add(new FileBytes(newDir + "sideroad.schem", - Files.readAllBytes(sideRoad.toPath()))); + files.add(new FileBytes(newDir + "sideroad.schem", Files.readAllBytes(sideRoad.toPath()))); } - File intersection = FileUtils - .getFile(PlotSquared.platform().getDirectory(), dir + "intersection.schem"); + File intersection = FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "intersection.schem"); if (intersection.exists()) { - files.add(new FileBytes(newDir + "intersection.schem", - Files.readAllBytes(intersection.toPath()))); + files.add(new FileBytes(newDir + "intersection.schem", Files.readAllBytes(intersection.toPath()))); } - File plot = - FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "plot.schem"); + File plot = FileUtils.getFile(PlotSquared.platform().getDirectory(), dir + "plot.schem"); if (plot.exists()) { files.add(new FileBytes(newDir + "plot.schem", Files.readAllBytes(plot.toPath()))); } @@ -102,17 +93,14 @@ public class HybridPlotManager extends ClassicPlotManager { Template.zipAll(hybridPlotWorld.getWorldName(), files); } - @Override public boolean createRoadEast(Plot plot) { + @Override public boolean createRoadEast(@Nonnull final Plot plot) { super.createRoadEast(plot); PlotId id = plot.getId(); PlotId id2 = PlotId.of(id.getX() + 1, id.getY()); Location bot = getPlotBottomLocAbs(id2); Location top = getPlotTopLocAbs(id); - Location pos1 = - Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, 0, bot.getZ() - 1); - Location pos2 = Location - .at(hybridPlotWorld.getWorldName(), bot.getX(), Math.min(getWorldHeight(), 255), - top.getZ() + 1); + Location pos1 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, 0, bot.getZ() - 1); + Location pos2 = Location.at(hybridPlotWorld.getWorldName(), bot.getX(), Math.min(getWorldHeight(), 255), top.getZ() + 1); this.resetBiome(hybridPlotWorld, pos1, pos2); if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; @@ -123,24 +111,18 @@ public class HybridPlotManager extends ClassicPlotManager { return true; } - private void resetBiome(@Nonnull final HybridPlotWorld hybridPlotWorld, - @Nonnull final Location pos1, @Nonnull final Location pos2) { + private void resetBiome(@Nonnull final HybridPlotWorld hybridPlotWorld, @Nonnull final Location pos1, @Nonnull final Location pos2) { BiomeType biome = hybridPlotWorld.getPlotBiome(); if (!Objects.equals(PlotSquared.platform().getWorldUtil() - .getBiomeSynchronous(hybridPlotWorld.getWorldName(), (pos1.getX() + pos2.getX()) / 2, - (pos1.getZ() + pos2.getZ()) / 2), biome)) { - WorldUtil - .setBiome(hybridPlotWorld.getWorldName(), pos1.getX(), pos1.getZ(), pos2.getX(), - pos2.getZ(), biome); + .getBiomeSynchronous(hybridPlotWorld.getWorldName(), (pos1.getX() + pos2.getX()) / 2, (pos1.getZ() + pos2.getZ()) / 2), biome)) { + WorldUtil.setBiome(hybridPlotWorld.getWorldName(), pos1.getX(), pos1.getZ(), pos2.getX(), pos2.getZ(), biome); } } - private void createSchemAbs(QueueCoordinator queue, Location pos1, Location pos2, - boolean isRoad) { + private void createSchemAbs(@Nonnull final QueueCoordinator queue, @Nonnull final Location pos1, @Nonnull final Location pos2, boolean isRoad) { int size = hybridPlotWorld.SIZE; int minY; - if ((isRoad && Settings.Schematics.PASTE_ROAD_ON_TOP) || (!isRoad - && Settings.Schematics.PASTE_ON_TOP)) { + if ((isRoad && Settings.Schematics.PASTE_ROAD_ON_TOP) || (!isRoad && Settings.Schematics.PASTE_ON_TOP)) { minY = hybridPlotWorld.SCHEM_Y; } else { minY = 1; @@ -177,17 +159,14 @@ public class HybridPlotManager extends ClassicPlotManager { } } - @Override public boolean createRoadSouth(Plot plot) { + @Override public boolean createRoadSouth(@Nonnull final Plot plot) { super.createRoadSouth(plot); PlotId id = plot.getId(); PlotId id2 = PlotId.of(id.getX(), id.getY() + 1); Location bot = getPlotBottomLocAbs(id2); Location top = getPlotTopLocAbs(id); - Location pos1 = - Location.at(hybridPlotWorld.getWorldName(), bot.getX() - 1, 0, top.getZ() + 1); - Location pos2 = Location - .at(hybridPlotWorld.getWorldName(), top.getX() + 1, Math.min(getWorldHeight(), 255), - bot.getZ()); + Location pos1 = Location.at(hybridPlotWorld.getWorldName(), bot.getX() - 1, 0, top.getZ() + 1); + Location pos2 = Location.at(hybridPlotWorld.getWorldName(), top.getX() + 1, Math.min(getWorldHeight(), 255), bot.getZ()); this.resetBiome(hybridPlotWorld, pos1, pos2); if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; @@ -198,7 +177,7 @@ public class HybridPlotManager extends ClassicPlotManager { return true; } - @Override public boolean createRoadSouthEast(Plot plot) { + @Override public boolean createRoadSouthEast(@Nonnull final Plot plot) { super.createRoadSouthEast(plot); PlotId id = plot.getId(); PlotId id2 = PlotId.of(id.getX() + 1, id.getY() + 1); @@ -219,7 +198,7 @@ public class HybridPlotManager extends ClassicPlotManager { * don't need to do something quite as complex unless you happen to have 512x512 sized plots. *

*/ - @Override public boolean clearPlot(Plot plot, final Runnable whenDone) { + @Override public boolean clearPlot(@Nonnull final Plot plot, @Nullable final Runnable whenDone) { if (this.regionManager.notifyClear(this)) { //If this returns false, the clear didn't work if (this.regionManager.handleClear(plot, whenDone, this)) { @@ -231,8 +210,7 @@ public class HybridPlotManager extends ClassicPlotManager { final Location pos2 = plot.getExtendedTopAbs(); // If augmented final boolean canRegen = - (hybridPlotWorld.getType() == PlotAreaType.AUGMENTED) && (hybridPlotWorld.getTerrain() - != PlotAreaTerrainType.NONE) && REGENERATIVE_CLEAR; + (hybridPlotWorld.getType() == PlotAreaType.AUGMENTED) && (hybridPlotWorld.getTerrain() != PlotAreaTerrainType.NONE) && REGENERATIVE_CLEAR; // The component blocks final Pattern plotfloor = hybridPlotWorld.TOP_BLOCK.toPattern(); final Pattern filling = hybridPlotWorld.MAIN_BLOCK.toPattern(); @@ -251,10 +229,8 @@ public class HybridPlotManager extends ClassicPlotManager { queue.setCuboid(pos1.withY(0), pos2.withY(0), bedrock); // Each component has a different layer queue.setCuboid(pos1.withY(1), pos2.withY(hybridPlotWorld.PLOT_HEIGHT - 1), filling); - queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT), - pos2.withY(hybridPlotWorld.PLOT_HEIGHT), plotfloor); - queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT + 1), - pos2.withY(getWorldHeight()), air); + queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT), pos2.withY(hybridPlotWorld.PLOT_HEIGHT), plotfloor); + queue.setCuboid(pos1.withY(hybridPlotWorld.PLOT_HEIGHT + 1), pos2.withY(getWorldHeight()), air); queue.setBiomeCuboid(pos1, pos2, biome); } else { queue.setRegenRegion(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3())); @@ -264,7 +240,7 @@ public class HybridPlotManager extends ClassicPlotManager { return queue.enqueue(); } - public void pastePlotSchematic(QueueCoordinator queue, Location bottom, Location top) { + public void pastePlotSchematic(@Nonnull final QueueCoordinator queue, @Nonnull final Location bottom, @Nonnull final Location top) { if (!hybridPlotWorld.PLOT_SCHEMATIC) { return; } @@ -277,7 +253,7 @@ public class HybridPlotManager extends ClassicPlotManager { * @param plot The plot * @return The location where a sign should be */ - @Override public Location getSignLoc(Plot plot) { + @Override public Location getSignLoc(@Nonnull final @NotNull Plot plot) { return hybridPlotWorld.getSignLocation(plot); } } diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java index b89838836..1a878f290 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotWorld.java @@ -41,7 +41,6 @@ import com.plotsquared.core.queue.GlobalBlockQueue; import com.plotsquared.core.util.EconHandler; import com.plotsquared.core.util.FileUtils; import com.plotsquared.core.util.MathMan; -import com.plotsquared.core.util.RegionManager; import com.plotsquared.core.util.SchematicHandler; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTagBuilder; @@ -124,11 +123,9 @@ public class HybridPlotWorld extends ClassicPlotWorld { Direction direction = MCDirections.fromRotation(rot); if (direction != null) { - Vector3 vector = transform.apply(direction.toVector()) - .subtract(transform.apply(Vector3.ZERO)).normalize(); - Direction newDirection = Direction.findClosest(vector, - Direction.Flag.CARDINAL | Direction.Flag.ORDINAL - | Direction.Flag.SECONDARY_ORDINAL); + Vector3 vector = transform.apply(direction.toVector()).subtract(transform.apply(Vector3.ZERO)).normalize(); + Direction newDirection = + Direction.findClosest(vector, Direction.Flag.CARDINAL | Direction.Flag.ORDINAL | Direction.Flag.SECONDARY_ORDINAL); if (newDirection != null) { CompoundTagBuilder builder = tag.createBuilder(); @@ -215,21 +212,24 @@ public class HybridPlotWorld extends ClassicPlotWorld { // Try to determine root. This means that plot areas can have separate schematic // directories - if (!(root = FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" + - this.getWorldName() + "/" + this.getId())).exists()) { - root = FileUtils.getFile(PlotSquared.platform().getDirectory(), - "schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName()); + if (!(root = + FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName() + "/" + this.getId())) + .exists()) { + root = FileUtils.getFile(PlotSquared.platform().getDirectory(), "schematics/GEN_ROAD_SCHEMATIC/" + this.getWorldName()); } File schematic1File = new File(root, "sideroad.schem"); - if (!schematic1File.exists()) + if (!schematic1File.exists()) { schematic1File = new File(root, "sideroad.schematic"); + } File schematic2File = new File(root, "intersection.schem"); - if (!schematic2File.exists()) + if (!schematic2File.exists()) { schematic2File = new File(root, "intersection.schematic"); + } File schematic3File = new File(root, "plot.schem"); - if (!schematic3File.exists()) + if (!schematic3File.exists()) { schematic3File = new File(root, "plot.schematic"); + } Schematic schematic1 = this.schematicHandler.getSchematic(schematic1File); Schematic schematic2 = this.schematicHandler.getSchematic(schematic2File); Schematic schematic3 = this.schematicHandler.getSchematic(schematic3File); @@ -282,18 +282,15 @@ public class HybridPlotWorld extends ClassicPlotWorld { for (short x = 0; x < w3; x++) { for (short z = 0; z < l3; z++) { for (short y = 0; y < h3; y++) { - BaseBlock id = blockArrayClipboard3.getFullBlock(BlockVector3 - .at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); + BaseBlock id = + blockArrayClipboard3.getFullBlock(BlockVector3.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); if (!id.getBlockType().getMaterial().isAir()) { - addOverlayBlock((short) (x + shift + oddshift + centerShiftX), - (short) (y + plotY), (short) (z + shift + oddshift + centerShiftZ), - id, false, h3); + addOverlayBlock((short) (x + shift + oddshift + centerShiftX), (short) (y + plotY), + (short) (z + shift + oddshift + centerShiftZ), id, false, h3); } } - BiomeType biome = blockArrayClipboard3 - .getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); - addOverlayBiome((short) (x + shift + oddshift + centerShiftX), - (short) (z + shift + oddshift + centerShiftZ), biome); + BiomeType biome = blockArrayClipboard3.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); + addOverlayBiome((short) (x + shift + oddshift + centerShiftX), (short) (z + shift + oddshift + centerShiftZ), biome); } } @@ -322,20 +319,15 @@ public class HybridPlotWorld extends ClassicPlotWorld { for (short x = 0; x < w1; x++) { for (short z = 0; z < l1; z++) { for (short y = 0; y < h1; y++) { - BaseBlock id = blockArrayClipboard1.getFullBlock(BlockVector3 - .at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); + BaseBlock id = blockArrayClipboard1.getFullBlock(BlockVector3.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); if (!id.getBlockType().getMaterial().isAir()) { - addOverlayBlock((short) (x - shift), (short) (y + roadY), - (short) (z + shift + oddshift), id, false, h1); - addOverlayBlock((short) (z + shift + oddshift), (short) (y + roadY), - (short) (shift - x + (oddshift - 1)), id, true, h1); + addOverlayBlock((short) (x - shift), (short) (y + roadY), (short) (z + shift + oddshift), id, false, h1); + addOverlayBlock((short) (z + shift + oddshift), (short) (y + roadY), (short) (shift - x + (oddshift - 1)), id, true, h1); } } - BiomeType biome = blockArrayClipboard1 - .getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); + BiomeType biome = blockArrayClipboard1.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); addOverlayBiome((short) (x - shift), (short) (z + shift + oddshift), biome); - addOverlayBiome((short) (z + shift + oddshift), - (short) (shift - x + (oddshift - 1)), biome); + addOverlayBiome((short) (z + shift + oddshift), (short) (shift - x + (oddshift - 1)), biome); } } @@ -348,22 +340,18 @@ public class HybridPlotWorld extends ClassicPlotWorld { for (short x = 0; x < w2; x++) { for (short z = 0; z < l2; z++) { for (short y = 0; y < h2; y++) { - BaseBlock id = blockArrayClipboard2.getFullBlock(BlockVector3 - .at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); + BaseBlock id = blockArrayClipboard2.getFullBlock(BlockVector3.at(x + min.getBlockX(), y + min.getBlockY(), z + min.getBlockZ())); if (!id.getBlockType().getMaterial().isAir()) { - addOverlayBlock((short) (x - shift), (short) (y + roadY), - (short) (z - shift), id, false, h2); + addOverlayBlock((short) (x - shift), (short) (y + roadY), (short) (z - shift), id, false, h2); } } - BiomeType biome = blockArrayClipboard2 - .getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); + BiomeType biome = blockArrayClipboard2.getBiome(BlockVector2.at(x + min.getBlockX(), z + min.getBlockZ())); addOverlayBiome((short) (x - shift), (short) (z - shift), biome); } } } - public void addOverlayBlock(short x, short y, short z, BaseBlock id, boolean rotate, - int height) { + public void addOverlayBlock(short x, short y, short z, BaseBlock id, boolean rotate, int height) { if (z < 0) { z += this.SIZE; } else if (z >= this.SIZE) { diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index 7936a6029..384eecdcd 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -80,8 +80,7 @@ import java.util.concurrent.atomic.AtomicInteger; public class HybridUtils { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + HybridUtils.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + HybridUtils.class.getSimpleName()); public static HybridUtils manager; public static Set regions; @@ -94,18 +93,17 @@ public class HybridUtils { private final ChunkManager chunkManager; private final GlobalBlockQueue blockQueue; private final WorldUtil worldUtil; - private final RegionManager regionManager; private final SchematicHandler schematicHandler; @Inject public HybridUtils(@Nonnull final PlotAreaManager plotAreaManager, - @Nonnull final ChunkManager chunkManager, @Nonnull final GlobalBlockQueue blockQueue, - @Nonnull final WorldUtil worldUtil, @Nonnull final RegionManager regionManager, - @Nonnull final SchematicHandler schematicHandler) { + @Nonnull final ChunkManager chunkManager, + @Nonnull final GlobalBlockQueue blockQueue, + @Nonnull final WorldUtil worldUtil, + @Nonnull final SchematicHandler schematicHandler) { this.plotAreaManager = plotAreaManager; this.chunkManager = chunkManager; this.blockQueue = blockQueue; this.worldUtil = worldUtil; - this.regionManager = regionManager; this.schematicHandler = schematicHandler; } @@ -114,8 +112,7 @@ public class HybridUtils { plotManager.regenerateAllPlotWalls(); } - public void analyzeRegion(final String world, final CuboidRegion region, - final RunnableVal whenDone) { + public void analyzeRegion(final String world, final CuboidRegion region, final RunnableVal whenDone) { // int diff, int variety, int vertices, int rotation, int height_sd /* * diff: compare to base by looping through all blocks @@ -235,30 +232,23 @@ public class HybridUtils { } else { // check vertices // modifications_adjacent - if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 - && y < 255) { - if (newBlocks[y - 1][x][z].getBlockType().getMaterial() - .isAir()) { + if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 && y < 255) { + if (newBlocks[y - 1][x][z].getBlockType().getMaterial().isAir()) { faces[i]++; } - if (newBlocks[y][x - 1][z].getBlockType().getMaterial() - .isAir()) { + if (newBlocks[y][x - 1][z].getBlockType().getMaterial().isAir()) { faces[i]++; } - if (newBlocks[y][x][z - 1].getBlockType().getMaterial() - .isAir()) { + if (newBlocks[y][x][z - 1].getBlockType().getMaterial().isAir()) { faces[i]++; } - if (newBlocks[y + 1][x][z].getBlockType().getMaterial() - .isAir()) { + if (newBlocks[y + 1][x][z].getBlockType().getMaterial().isAir()) { faces[i]++; } - if (newBlocks[y][x + 1][z].getBlockType().getMaterial() - .isAir()) { + if (newBlocks[y][x + 1][z].getBlockType().getMaterial().isAir()) { faces[i]++; } - if (newBlocks[y][x][z + 1].getBlockType().getMaterial() - .isAir()) { + if (newBlocks[y][x][z + 1].getBlockType().getMaterial().isAir()) { faces[i]++; } } @@ -347,9 +337,7 @@ public class HybridUtils { result.add(whenDone.value.data_sd); result.add(whenDone.value.air_sd); result.add(whenDone.value.variety_sd); - PlotFlag plotFlag = - GlobalFlagContainer.getInstance().getFlag(AnalysisFlag.class) - .createFlagInstance(result); + PlotFlag plotFlag = GlobalFlagContainer.getInstance().getFlag(AnalysisFlag.class).createFlagInstance(result); PlotFlagAddEvent event = new PlotFlagAddEvent(plotFlag, origin); if (event.getEventResult() == Result.DENY) { return; @@ -371,15 +359,13 @@ public class HybridUtils { run.run(); } - public int checkModified(QueueCoordinator queue, int x1, int x2, int y1, int y2, int z1, int z2, - BlockState[] blocks) { + public int checkModified(QueueCoordinator queue, int x1, int x2, int y1, int y2, int z1, int z2, BlockState[] blocks) { 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 block = queue.getBlock(x, y, z); - boolean same = - Arrays.stream(blocks).anyMatch(p -> this.worldUtil.isBlockSame(block, p)); + boolean same = Arrays.stream(blocks).anyMatch(p -> this.worldUtil.isBlockSame(block, p)); if (!same) { count++; } @@ -420,8 +406,7 @@ public class HybridUtils { return scheduleRoadUpdate(plot.getArea(), regions, extend, new HashSet<>()); } - public boolean scheduleRoadUpdate(final PlotArea area, Set regions, - final int extend, Set chunks) { + public boolean scheduleRoadUpdate(final PlotArea area, Set regions, final int extend, Set chunks) { HybridUtils.regions = regions; HybridUtils.area = area; HybridUtils.height = extend; @@ -460,16 +445,12 @@ public class HybridUtils { try { if (chunks.size() < 1024) { if (!HybridUtils.regions.isEmpty()) { - Iterator iterator = - HybridUtils.regions.iterator(); + Iterator iterator = HybridUtils.regions.iterator(); BlockVector2 loc = iterator.next(); iterator.remove(); if (Settings.DEBUG) { - logger - .info("[P2] Updating .mcr: {}, {} (approx 1024 chunks)", - loc.getX(), loc.getZ()); - logger.info("[P2] - Remaining: {}", - HybridUtils.regions.size()); + logger.info("[P2] Updating .mcr: {}, {} (approx 1024 chunks)", loc.getX(), loc.getZ()); + logger.info("[P2] - Remaining: {}", HybridUtils.regions.size()); } chunks.addAll(getChunks(loc)); System.gc(); @@ -479,8 +460,7 @@ public class HybridUtils { TaskManager.getPlatformImplementation().sync(() -> { long start = System.currentTimeMillis(); Iterator iterator = chunks.iterator(); - while (System.currentTimeMillis() - start < 20 && !chunks - .isEmpty()) { + while (System.currentTimeMillis() - start < 20 && !chunks.isEmpty()) { final BlockVector2 chunk = iterator.next(); iterator.remove(); boolean regenedRoads = regenerateRoad(area, chunk, extend); @@ -496,9 +476,8 @@ public class HybridUtils { Iterator iterator = HybridUtils.regions.iterator(); BlockVector2 loc = iterator.next(); iterator.remove(); - logger.error( - "[P2] Error! Could not update '{}/region/r.{}.{}.mca' (Corrupt chunk?)", - area.getWorldHash(), loc.getX(), loc.getZ()); + logger.error("[P2] Error! Could not update '{}/region/r.{}.{}.mca' (Corrupt chunk?)", area.getWorldHash(), loc.getX(), + loc.getZ()); } TaskManager.runTaskLater(task, TaskTime.seconds(1L)); }); @@ -525,37 +504,31 @@ public class HybridUtils { int tz = sz - 1; int ty = get_ey(plotManager, queue, sx, ex, bz, tz, sy); - Set sideRoad = new HashSet<>( - Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ey, sz, ez))); - final Set intersection = new HashSet<>( - Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ty, bz, tz))); + Set sideRoad = new HashSet<>(Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ey, sz, ez))); + final Set intersection = new HashSet<>(Collections.singletonList(RegionUtil.createRegion(sx, ex, sy, ty, bz, tz))); - final String dir = - "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + plot.getArea() - .toString() + File.separator; + final String dir = "schematics" + File.separator + "GEN_ROAD_SCHEMATIC" + File.separator + plot.getArea().toString() + File.separator; this.schematicHandler.getCompoundTag(world, sideRoad, new RunnableVal() { @Override public void run(CompoundTag value) { schematicHandler.save(value, dir + "sideroad.schem"); - schematicHandler - .getCompoundTag(world, intersection, new RunnableVal() { - @Override public void run(CompoundTag value) { - schematicHandler.save(value, dir + "intersection.schem"); - plotworld.ROAD_SCHEMATIC_ENABLED = true; - try { - plotworld.setupSchematics(); - } catch (SchematicHandler.UnsupportedFormatException e) { - e.printStackTrace(); - } + schematicHandler.getCompoundTag(world, intersection, new RunnableVal() { + @Override public void run(CompoundTag value) { + schematicHandler.save(value, dir + "intersection.schem"); + plotworld.ROAD_SCHEMATIC_ENABLED = true; + try { + plotworld.setupSchematics(); + } catch (SchematicHandler.UnsupportedFormatException e) { + e.printStackTrace(); } - }); + } + }); } }); return true; } - public int get_ey(final PlotManager pm, QueueCoordinator queue, int sx, int ex, int sz, int ez, - int sy) { + public int get_ey(final PlotManager pm, QueueCoordinator queue, int sx, int ex, int sz, int ez, int sy) { int ey = sy; for (int x = sx; x <= ex; x++) { for (int z = sz; z <= ez; z++) { @@ -598,8 +571,7 @@ public class HybridUtils { z -= plotWorld.ROAD_OFFSET_Z; final int finalX = x; final int finalZ = z; - QueueCoordinator queue = - this.blockQueue.getNewQueue(worldUtil.getWeWorld(plotWorld.getWorldName())); + QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(plotWorld.getWorldName())); if (id1 == null || id2 == null || id1 != id2) { this.chunkManager.loadChunk(area.getWorldName(), chunk, false).thenRun(() -> { if (id1 != null) { @@ -627,8 +599,7 @@ public class HybridUtils { } boolean condition; if (toCheck.get()) { - condition = manager.getPlotId(finalX + X + plotWorld.ROAD_OFFSET_X, 1, - finalZ + Z + plotWorld.ROAD_OFFSET_Z) == null; + condition = manager.getPlotId(finalX + X + plotWorld.ROAD_OFFSET_X, 1, finalZ + Z + plotWorld.ROAD_OFFSET_Z) == null; } else { boolean gx = absX > plotWorld.PATH_WIDTH_LOWER; boolean gz = absZ > plotWorld.PATH_WIDTH_LOWER; @@ -638,32 +609,27 @@ public class HybridUtils { } if (condition) { BaseBlock[] blocks = plotWorld.G_SCH.get(MathMan.pair(absX, absZ)); - int minY = - Settings.Schematics.PASTE_ROAD_ON_TOP ? plotWorld.SCHEM_Y : 1; + int minY = Settings.Schematics.PASTE_ROAD_ON_TOP ? plotWorld.SCHEM_Y : 1; int maxY = Math.max(extend, blocks.length); for (int y = 0; y < maxY; y++) { if (y > blocks.length - 1) { - queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, - finalZ + Z + plotWorld.ROAD_OFFSET_Z, WEExtent.AIRBASE); + queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, + WEExtent.AIRBASE); } else { BaseBlock block = blocks[y]; if (block != null) { - queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, - minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, block); + queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, block); } else { - queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, - minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, + queue.setBlock(finalX + X + plotWorld.ROAD_OFFSET_X, minY + y, finalZ + Z + plotWorld.ROAD_OFFSET_Z, WEExtent.AIRBASE); } } } BiomeType biome = plotWorld.G_SCH_B.get(MathMan.pair(absX, absZ)); if (biome != null) { - queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, - finalZ + Z + plotWorld.ROAD_OFFSET_Z, biome); + queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, finalZ + Z + plotWorld.ROAD_OFFSET_Z, biome); } else { - queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, - finalZ + Z + plotWorld.ROAD_OFFSET_Z, plotWorld.getPlotBiome()); + queue.setBiome(finalX + X + plotWorld.ROAD_OFFSET_X, finalZ + Z + plotWorld.ROAD_OFFSET_Z, plotWorld.getPlotBiome()); } } } diff --git a/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java index 32ea8154e..0cfc21a95 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/SquarePlotManager.java @@ -34,6 +34,7 @@ import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.HashUtil; import com.plotsquared.core.util.RegionManager; import com.sk89q.worldedit.regions.CuboidRegion; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,26 +48,25 @@ import java.util.Set; */ public abstract class SquarePlotManager extends GridPlotManager { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + SquarePlotManager.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + SquarePlotManager.class.getSimpleName()); private final SquarePlotWorld squarePlotWorld; private final RegionManager regionManager; - public SquarePlotManager(@Nonnull final SquarePlotWorld squarePlotWorld, - @Nonnull final RegionManager regionManager) { + public SquarePlotManager(@Nonnull final SquarePlotWorld squarePlotWorld, @Nonnull final RegionManager regionManager) { super(squarePlotWorld); this.squarePlotWorld = squarePlotWorld; this.regionManager = regionManager; } - @Override public boolean clearPlot(final Plot plot, final Runnable whenDone, - @Nullable QueueCoordinator queue) { + @Override public boolean clearPlot(final @NotNull Plot plot, final @Nullable Runnable whenDone, @Nullable QueueCoordinator queue) { final Set regions = plot.getRegions(); Runnable run = new Runnable() { @Override public void run() { if (regions.isEmpty()) { - whenDone.run(); + if (whenDone != null) { + whenDone.run(); + } return; } Iterator iterator = regions.iterator(); @@ -81,13 +81,13 @@ public abstract class SquarePlotManager extends GridPlotManager { return true; } - @Override public Location getPlotTopLocAbs(PlotId plotId) { + @Override public Location getPlotTopLocAbs(@NotNull PlotId plotId) { int px = plotId.getX(); int pz = plotId.getY(); - int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH - + squarePlotWorld.PLOT_WIDTH))) - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; - int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH - + squarePlotWorld.PLOT_WIDTH))) - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; + int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - (int) Math + .floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; + int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - (int) Math + .floor(squarePlotWorld.ROAD_WIDTH / 2) - 1; return Location.at(squarePlotWorld.getWorldName(), x, Math.min(getWorldHeight(), 255), z); } @@ -135,7 +135,7 @@ public abstract class SquarePlotManager extends GridPlotManager { } } - public PlotId getNearestPlotId(PlotArea plotArea, int x, int y, int z) { + public PlotId getNearestPlotId(@Nonnull PlotArea plotArea, int x, int y, int z) { SquarePlotWorld dpw = (SquarePlotWorld) plotArea; if (dpw.ROAD_OFFSET_X != 0) { x -= dpw.ROAD_OFFSET_X; @@ -196,8 +196,7 @@ public abstract class SquarePlotManager extends GridPlotManager { rz = z % size; } PlotId id = PlotId.of(dx, dz); - boolean[] merged = - new boolean[] {rz <= pathWidthLower, rx > end, rz > end, rx <= pathWidthLower}; + boolean[] merged = new boolean[] {rz <= pathWidthLower, rx > end, rz > end, rx <= pathWidthLower}; int hash = HashUtil.hash(merged); // Not merged, and no need to check if it is if (hash == 0) { @@ -235,8 +234,7 @@ public abstract class SquarePlotManager extends GridPlotManager { return plot.getMerged(Direction.NORTHWEST) ? id : null; } } catch (Exception ignored) { - logger.error("Invalid plot / road width in settings.yml for world: {}", - squarePlotWorld.getWorldName()); + logger.error("Invalid plot / road width in settings.yml for world: {}", squarePlotWorld.getWorldName()); } return null; } @@ -244,16 +242,13 @@ public abstract class SquarePlotManager extends GridPlotManager { /** * Get the bottom plot loc (some basic math). */ - @Override public Location getPlotBottomLocAbs(PlotId plotId) { + @Override public Location getPlotBottomLocAbs(@NotNull PlotId plotId) { int px = plotId.getX(); int pz = plotId.getY(); - int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH - + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH - (int) Math - .floor(squarePlotWorld.ROAD_WIDTH / 2); - int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH - + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH - (int) Math - .floor(squarePlotWorld.ROAD_WIDTH / 2); - return Location - .at(squarePlotWorld.getWorldName(), x, squarePlotWorld.getMinBuildHeight(), z); + int x = (squarePlotWorld.ROAD_OFFSET_X + (px * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH + - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2); + int z = (squarePlotWorld.ROAD_OFFSET_Z + (pz * (squarePlotWorld.ROAD_WIDTH + squarePlotWorld.PLOT_WIDTH))) - squarePlotWorld.PLOT_WIDTH + - (int) Math.floor(squarePlotWorld.ROAD_WIDTH / 2); + return Location.at(squarePlotWorld.getWorldName(), x, squarePlotWorld.getMinBuildHeight(), z); } } diff --git a/Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java b/Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java deleted file mode 100644 index 96ce1e242..000000000 --- a/Core/src/main/java/com/plotsquared/core/inject/annotations/QueuePipeline.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2020 IntellectualSites - * - * 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, see . - */ -package com.plotsquared.core.inject.annotations; - -import com.google.inject.BindingAnnotation; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target({ElementType.PARAMETER, ElementType.FIELD}) -@Retention(RetentionPolicy.RUNTIME) -@BindingAnnotation -public @interface QueuePipeline { -} diff --git a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorBuilderFactory.java b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorBuilderFactory.java index bfcbe206d..c526ae731 100644 --- a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorBuilderFactory.java +++ b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorBuilderFactory.java @@ -34,7 +34,6 @@ import javax.annotation.Nonnull; public interface ChunkCoordinatorBuilderFactory { - @Inject @Nonnull ChunkCoordinatorBuilder create( - @Assisted @NotNull ChunkCoordinatorFactory chunkCoordinatorFactory); + @Inject @Nonnull ChunkCoordinatorBuilder create(@Assisted @NotNull ChunkCoordinatorFactory chunkCoordinatorFactory); } diff --git a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java index df87be525..aeb62d659 100644 --- a/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java +++ b/Core/src/main/java/com/plotsquared/core/inject/factory/ChunkCoordinatorFactory.java @@ -35,9 +35,13 @@ import java.util.function.Consumer; public interface ChunkCoordinatorFactory { - @Nonnull ChunkCoordinator create(final long maxIterationTime, final int initialBatchSize, - @Nonnull final Consumer chunkConsumer, @Nonnull final World world, - @Nonnull final Collection requestedChunks, @Nonnull final Runnable whenDone, - @Nonnull final Consumer throwableConsumer, final boolean unloadAfter); + @Nonnull ChunkCoordinator create(final long maxIterationTime, + final int initialBatchSize, + @Nonnull final Consumer chunkConsumer, + @Nonnull final World world, + @Nonnull final Collection requestedChunks, + @Nonnull final Runnable whenDone, + @Nonnull final Consumer throwableConsumer, + final boolean unloadAfter); } diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index 9636b2c7e..2c3c462e3 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -140,14 +140,13 @@ public class Plot { private static final Logger logger = LoggerFactory.getLogger("P2/" + Plot.class.getSimpleName()); private static final DecimalFormat FLAG_DECIMAL_FORMAT = new DecimalFormat("0"); + private static Set connected_cache; + private static Set regions_cache; static { FLAG_DECIMAL_FORMAT.setMaximumFractionDigits(340); } - private static Set connected_cache; - private static Set regions_cache; - /** * Plot flag container */ @@ -272,9 +271,18 @@ public class Plot { * @param merged an array giving merged plots * @see Plot#getPlot(Location) for existing plots */ - public Plot(@Nonnull PlotId id, UUID owner, HashSet trusted, HashSet members, - HashSet denied, String alias, BlockLoc position, Collection> flags, - PlotArea area, boolean[] merged, long timestamp, int temp) { + public Plot(@Nonnull PlotId id, + UUID owner, + HashSet trusted, + HashSet members, + HashSet denied, + String alias, + BlockLoc position, + Collection> flags, + PlotArea area, + boolean[] merged, + long timestamp, + int temp) { this.id = id; this.area = area; this.owner = owner; @@ -306,8 +314,7 @@ public class Plot { * @param message If a message should be sent to the player if a plot cannot be found * @return The plot if only 1 result is found, or null */ - @Nullable public static Plot getPlotFromString(PlotPlayer player, String arg, - boolean message) { + @Nullable public static Plot getPlotFromString(PlotPlayer player, String arg, boolean message) { if (arg == null) { if (player == null) { if (message) { @@ -329,8 +336,7 @@ public class Plot { String[] split = arg.split(";|,"); PlotId id; if (split.length == 4) { - area = PlotSquared.get().getPlotAreaManager() - .getPlotAreaByString(split[0] + ';' + split[1]); + area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(split[0] + ';' + split[1]); id = PlotId.fromString(split[2] + ';' + split[3]); } else if (split.length == 3) { area = PlotSquared.get().getPlotAreaManager().getPlotAreaByString(split[0]); @@ -409,8 +415,7 @@ public class Plot { return null; } - @Nonnull private static Location[] getCorners(@Nonnull final String world, - @Nonnull final CuboidRegion region) { + @Nonnull private static Location[] getCorners(@Nonnull final String world, @Nonnull final CuboidRegion region) { final BlockVector3 min = region.getMinimumPoint(); final BlockVector3 max = region.getMaximumPoint(); return new Location[] {Location.at(world, min), Location.at(world, max)}; @@ -609,8 +614,7 @@ public class Plot { UUID last = this.getOwner(); owners.add(this.getOwner()); for (Plot current : array) { - if (last == null || current.getOwner().getMostSignificantBits() != last - .getMostSignificantBits()) { + if (last == null || current.getOwner().getMostSignificantBits() != last.getMostSignificantBits()) { owners.add(current.getOwner()); last = current.getOwner(); } @@ -652,8 +656,8 @@ public class Plot { * @return boolean false if the player is allowed to enter */ public boolean isDenied(UUID uuid) { - return this.denied != null && (this.denied.contains(DBFunc.EVERYONE) && !this.isAdded(uuid) - || !this.isAdded(uuid) && this.denied.contains(uuid)); + return this.denied != null && (this.denied.contains(DBFunc.EVERYONE) && !this.isAdded(uuid) || !this.isAdded(uuid) && this.denied + .contains(uuid)); } /** @@ -777,8 +781,7 @@ public class Plot { * @return true if this plot is merged, otherwise false */ public boolean isMerged() { - return getSettings().getMerged(0) || getSettings().getMerged(2) || getSettings() - .getMerged(1) || getSettings().getMerged(3); + return getSettings().getMerged(0) || getSettings().getMerged(2) || getSettings().getMerged(1) || getSettings().getMerged(3); } /** @@ -829,10 +832,8 @@ public class Plot { int i2 = 0; if (this.getSettings().getMerged(i2)) { if (this.getSettings().getMerged(i)) { - if (this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))) - .getMerged(i2)) { - return this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2))) - .getMerged(i); + if (this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))).getMerged(i2)) { + return this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2))).getMerged(i); } } } @@ -842,9 +843,8 @@ public class Plot { case 6: i = dir - 4; i2 = dir - 3; - return this.getSettings().getMerged(i2) && this.getSettings().getMerged(i) - && this.area.getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))) - .getMerged(i2) && this.area + return this.getSettings().getMerged(i2) && this.getSettings().getMerged(i) && this.area + .getPlotAbs(this.id.getRelative(Direction.getFromIndex(i))).getMerged(i2) && this.area .getPlotAbs(this.id.getRelative(Direction.getFromIndex(i2))).getMerged(i); } @@ -1045,8 +1045,8 @@ public class Plot { if (isDelete) { this.removeSign(); } - PlotUnlinkEvent event = this.eventDispatcher.callUnlink(getArea(), this, true, !isDelete, - isDelete ? PlotUnlinkEvent.REASON.DELETE : PlotUnlinkEvent.REASON.CLEAR); + PlotUnlinkEvent event = this.eventDispatcher + .callUnlink(getArea(), this, true, !isDelete, isDelete ? PlotUnlinkEvent.REASON.DELETE : PlotUnlinkEvent.REASON.CLEAR); if (event.getEventResult() != Result.DENY) { this.unlinkPlot(event.isCreateRoad(), event.isCreateSign()); } @@ -1074,9 +1074,7 @@ public class Plot { Plot current = queue.poll(); if (Plot.this.area.getTerrain() != PlotAreaTerrainType.NONE) { try { - regionManager - .regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, - this); + regionManager.regenerateRegion(current.getBottomAbs(), current.getTopAbs(), false, this); } catch (UnsupportedOperationException exception) { MainUtil.sendMessage(null, "Please ask md_5 to fix regenerateChunk() because it breaks plugins. We apologize for the inconvenience"); @@ -1191,17 +1189,11 @@ public class Plot { if (this.area.allowSigns()) { Location location = manager.getSignLoc(this); String id = this.id.toString(); - String[] lines = - new String[] {Captions.OWNER_SIGN_LINE_1.formatted().replaceAll("%id%", id), - Captions.OWNER_SIGN_LINE_2.formatted().replaceAll("%id%", id).replaceAll( - "%plr%", name), - Captions.OWNER_SIGN_LINE_3.formatted().replaceAll("%id%", id).replaceAll( - "%plr%", name), - Captions.OWNER_SIGN_LINE_4.formatted().replaceAll("%id%", id).replaceAll( - "%plr%", name)}; - this.worldUtil - .setSign(this.getWorldName(), location.getX(), location.getY(), location.getZ(), - lines); + String[] lines = new String[] {Captions.OWNER_SIGN_LINE_1.formatted().replaceAll("%id%", id), + Captions.OWNER_SIGN_LINE_2.formatted().replaceAll("%id%", id).replaceAll("%plr%", name), + Captions.OWNER_SIGN_LINE_3.formatted().replaceAll("%id%", id).replaceAll("%plr%", name), + Captions.OWNER_SIGN_LINE_4.formatted().replaceAll("%id%", id).replaceAll("%plr%", name)}; + this.worldUtil.setSign(this.getWorldName(), location.getX(), location.getY(), location.getZ(), lines); } } @@ -1284,14 +1276,12 @@ public class Plot { * @param ignorePluginFlags Whether or not to ignore {@link InternalFlag internal flags} * @return Collection containing all the flags that matched the given criteria */ - public Collection> getApplicableFlags(final boolean plotOnly, - final boolean ignorePluginFlags) { + public Collection> getApplicableFlags(final boolean plotOnly, final boolean ignorePluginFlags) { if (!hasOwner()) { return Collections.emptyList(); } final Map, PlotFlag> flags = new HashMap<>(); - if (!plotOnly && getArea() != null && !getArea().getFlagContainer().getFlagMap() - .isEmpty()) { + if (!plotOnly && getArea() != null && !getArea().getFlagContainer().getFlagMap().isEmpty()) { final Map, PlotFlag> flagMap = getArea().getFlagContainer().getFlagMap(); flags.putAll(flagMap); } @@ -1449,8 +1439,7 @@ public class Plot { if (Settings.Backup.DELETE_ON_UNCLAIM) { // Destroy all backups when the plot is unclaimed - Objects.requireNonNull(PlotSquared.platform()).getBackupManager() - .getProfile(current).destroy(); + Objects.requireNonNull(PlotSquared.platform()).getBackupManager().getProfile(current).destroy(); } getArea().removePlot(getId()); @@ -1478,9 +1467,8 @@ public class Plot { Location[] corners = getCorners(); Location top = corners[0]; Location bot = corners[1]; - Location location = Location - .at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), - MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ())); + Location location = Location.at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), MathMan.average(bot.getY(), top.getY()), + MathMan.average(bot.getZ(), top.getZ())); if (!isLoaded()) { result.accept(location); return; @@ -1501,14 +1489,12 @@ public class Plot { Location[] corners = getCorners(); Location top = corners[0]; Location bot = corners[1]; - Location location = Location - .at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), - MathMan.average(bot.getY(), top.getY()), MathMan.average(bot.getZ(), top.getZ())); + Location location = Location.at(this.getWorldName(), MathMan.average(bot.getX(), top.getX()), MathMan.average(bot.getY(), top.getY()), + MathMan.average(bot.getZ(), top.getZ())); if (!isLoaded()) { return location; } - int y = this.worldUtil - .getHighestBlockSynchronous(getWorldName(), location.getX(), location.getZ()); + int y = this.worldUtil.getHighestBlockSynchronous(getWorldName(), location.getX(), location.getZ()); if (area.allowSigns()) { y = Math.max(y, getManager().getSignLoc(this).getY()); } @@ -1520,8 +1506,7 @@ public class Plot { */ @Deprecated public Location getSideSynchronous() { CuboidRegion largest = getLargestRegion(); - int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) - + largest.getMinimumPoint().getX(); + int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX(); int z = largest.getMinimumPoint().getZ() - 1; PlotManager manager = getManager(); int y = isLoaded() ? this.worldUtil.getHighestBlockSynchronous(getWorldName(), x, z) : 62; @@ -1533,8 +1518,7 @@ public class Plot { public void getSide(Consumer result) { CuboidRegion largest = getLargestRegion(); - int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) - + largest.getMinimumPoint().getX(); + int x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX(); int z = largest.getMinimumPoint().getZ() - 1; PlotManager manager = getManager(); if (isLoaded()) { @@ -1564,16 +1548,14 @@ public class Plot { } else { Location bottom = this.getBottomAbs(); Location location = Location - .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), - bottom.getZ() + home.getZ(), home.getYaw(), home.getPitch()); + .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), bottom.getZ() + home.getZ(), home.getYaw(), + home.getPitch()); if (!isLoaded()) { return location; } - if (!this.worldUtil.getBlockSynchronous(location).getBlockType().getMaterial() - .isAir()) { - location = location.withY(Math.max(1 + this.worldUtil - .getHighestBlockSynchronous(this.getWorldName(), location.getX(), - location.getZ()), bottom.getY())); + if (!this.worldUtil.getBlockSynchronous(location).getBlockType().getMaterial().isAir()) { + location = location.withY( + Math.max(1 + this.worldUtil.getHighestBlockSynchronous(this.getWorldName(), location.getX(), location.getZ()), bottom.getY())); } return location; } @@ -1589,17 +1571,16 @@ public class Plot { } else { Location bottom = this.getBottomAbs(); Location location = Location - .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), - bottom.getZ() + home.getZ(), home.getYaw(), home.getPitch()); + .at(bottom.getWorldName(), bottom.getX() + home.getX(), bottom.getY() + home.getY(), bottom.getZ() + home.getZ(), home.getYaw(), + home.getPitch()); if (!isLoaded()) { result.accept(location); return; } this.worldUtil.getBlock(location, block -> { if (!block.getBlockType().getMaterial().isAir()) { - this.worldUtil - .getHighestBlock(this.getWorldName(), location.getX(), location.getZ(), - y -> result.accept(location.withY(Math.max(1 + y, bottom.getY())))); + this.worldUtil.getHighestBlock(this.getWorldName(), location.getX(), location.getZ(), + y -> result.accept(location.withY(Math.max(1 + y, bottom.getY())))); } else { result.accept(location); } @@ -1645,21 +1626,15 @@ public class Plot { if (loc.getX() == Integer.MAX_VALUE && loc.getZ() == Integer.MAX_VALUE) { // center CuboidRegion largest = plot.getLargestRegion(); - x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() - >> 1) + largest.getMinimumPoint().getX(); - z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ() - >> 1) + largest.getMinimumPoint().getZ(); + x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX(); + z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ() >> 1) + largest.getMinimumPoint().getZ(); } else { // specific Location bot = plot.getBottomAbs(); x = bot.getX() + loc.getX(); z = bot.getZ() + loc.getZ(); } - int y = loc.getY() < 1 ? - (isLoaded() ? - this.worldUtil.getHighestBlockSynchronous(plot.getWorldName(), x, z) + 1 : - 63) : - loc.getY(); + int y = loc.getY() < 1 ? (isLoaded() ? this.worldUtil.getHighestBlockSynchronous(plot.getWorldName(), x, z) + 1 : 63) : loc.getY(); return Location.at(plot.getWorldName(), x, y, z); } // Side @@ -1675,10 +1650,8 @@ public class Plot { if (loc.getX() == Integer.MAX_VALUE && loc.getZ() == Integer.MAX_VALUE) { // center CuboidRegion largest = plot.getLargestRegion(); - x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() - >> 1) + largest.getMinimumPoint().getX(); - z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ() - >> 1) + largest.getMinimumPoint().getZ(); + x = (largest.getMaximumPoint().getX() >> 1) - (largest.getMinimumPoint().getX() >> 1) + largest.getMinimumPoint().getX(); + z = (largest.getMaximumPoint().getZ() >> 1) - (largest.getMinimumPoint().getZ() >> 1) + largest.getMinimumPoint().getZ(); } else { // specific Location bot = plot.getBottomAbs(); @@ -1687,8 +1660,7 @@ public class Plot { } if (loc.getY() < 1) { if (isLoaded()) { - this.worldUtil.getHighestBlock(plot.getWorldName(), x, z, - y -> result.accept(Location.at(plot.getWorldName(), x, y + 1, z))); + this.worldUtil.getHighestBlock(plot.getWorldName(), x, z, y -> result.accept(Location.at(plot.getWorldName(), x, y + 1, z))); } else { result.accept(Location.at(plot.getWorldName(), x, 63, z)); } @@ -1704,10 +1676,8 @@ public class Plot { public double getVolume() { double count = 0; for (CuboidRegion region : getRegions()) { - count += - (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * ( - region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1) - * MAX_HEIGHT; + count += (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * ( + region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1) * MAX_HEIGHT; } return count; } @@ -1790,14 +1760,11 @@ public class Plot { * This should not need to be called */ public void refreshChunks() { - QueueCoordinator queue = this.blockQueue - .getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(getWorldName())); + QueueCoordinator queue = this.blockQueue.getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(getWorldName())); HashSet chunks = new HashSet<>(); for (CuboidRegion region : Plot.this.getRegions()) { - for (int x = region.getMinimumPoint().getX() >> 4; - x <= region.getMaximumPoint().getX() >> 4; x++) { - for (int z = region.getMinimumPoint().getZ() >> 4; - z <= region.getMaximumPoint().getZ() >> 4; z++) { + for (int x = region.getMinimumPoint().getX() >> 4; x <= region.getMaximumPoint().getX() >> 4; x++) { + for (int z = region.getMinimumPoint().getZ() >> 4; z <= region.getMaximumPoint().getZ() >> 4; z++) { if (chunks.add(BlockVector2.at(x, z))) { worldUtil.refreshChunk(x, z, getWorldName()); } @@ -1816,8 +1783,7 @@ public class Plot { } Location location = manager.getSignLoc(this); QueueCoordinator queue = this.blockQueue.getNewQueue(worldUtil.getWeWorld(getWorldName())); - queue.setBlock(location.getX(), location.getY(), location.getZ(), - BlockTypes.AIR.getDefaultState()); + queue.setBlock(location.getX(), location.getY(), location.getZ(), BlockTypes.AIR.getDefaultState()); queue.enqueue(); } @@ -1829,8 +1795,7 @@ public class Plot { this.setSign("unknown"); return; } - this.impromptuPipeline - .getSingle(this.getOwnerAbs(), (username, sign) -> this.setSign(username)); + this.impromptuPipeline.getSingle(this.getOwnerAbs(), (username, sign) -> this.setSign(username)); } /** @@ -1852,14 +1817,12 @@ public class Plot { return claim(player, teleport, schematic, true); } - public boolean claim(@Nonnull final PlotPlayer player, boolean teleport, String schematic, - boolean updateDB) { + public boolean claim(@Nonnull final PlotPlayer player, boolean teleport, String schematic, boolean updateDB) { if (updateDB) { if (!create(player.getUUID(), true)) { - logger.error( - "[P2] Player {} attempted to claim plot {}, but the database failed to update", - player.getName(), this.getId().toCommaSeparatedString()); + logger.error("[P2] Player {} attempted to claim plot {}, but the database failed to update", player.getName(), + this.getId().toCommaSeparatedString()); return false; } } else { @@ -1888,16 +1851,15 @@ public class Plot { e.printStackTrace(); return true; } - schematicHandler.paste(sch, this, 0, 1, 0, Settings.Schematics.PASTE_ON_TOP, - new RunnableVal() { - @Override public void run(Boolean value) { - if (value) { - MainUtil.sendMessage(player, Captions.SCHEMATIC_PASTE_SUCCESS); - } else { - MainUtil.sendMessage(player, Captions.SCHEMATIC_PASTE_FAILED); - } + schematicHandler.paste(sch, this, 0, 1, 0, Settings.Schematics.PASTE_ON_TOP, new RunnableVal() { + @Override public void run(Boolean value) { + if (value) { + MainUtil.sendMessage(player, Captions.SCHEMATIC_PASTE_SUCCESS); + } else { + MainUtil.sendMessage(player, Captions.SCHEMATIC_PASTE_FAILED); } - }); + } + }); } plotworld.getPlotManager().claimPlot(this); return true; @@ -1935,11 +1897,9 @@ public class Plot { DBFunc.createPlotAndSettings(this, () -> { PlotArea plotworld = Plot.this.area; if (notify && plotworld.isAutoMerge()) { - final PlotPlayer player = PlotSquared.platform().getPlayerManager() - .getPlayerIfExists(uuid); + final PlotPlayer player = PlotSquared.platform().getPlayerManager().getPlayerIfExists(uuid); - PlotMergeEvent event = this.eventDispatcher - .callMerge(this, Direction.ALL, Integer.MAX_VALUE, player); + PlotMergeEvent event = this.eventDispatcher.callMerge(this, Direction.ALL, Integer.MAX_VALUE, player); if (event.getEventResult() == Result.DENY) { if (player != null) { @@ -1952,8 +1912,7 @@ public class Plot { }); return true; } - logger.info("[P2] Failed to add plot {} to plot area {}", - this.getId().toCommaSeparatedString(), this.area.toString()); + logger.info("[P2] Failed to add plot {} to plot area {}", this.getId().toCommaSeparatedString(), this.area.toString()); return false; } @@ -1961,8 +1920,7 @@ public class Plot { * Sets components such as border, wall, floor. * (components are generator specific) */ - @Deprecated public boolean setComponent(String component, String blocks, - QueueCoordinator queue) { + @Deprecated public boolean setComponent(String component, String blocks, QueueCoordinator queue) { BlockBucket parsed = ConfigurationUtil.BLOCK_BUCKET.parseString(blocks); if (parsed != null && parsed.isEmpty()) { return false; @@ -1976,8 +1934,7 @@ public class Plot { * Retrieve the biome of the plot. */ public void getBiome(Consumer result) { - this.getCenter(location -> this.worldUtil - .getBiome(location.getWorldName(), location.getX(), location.getZ(), result)); + this.getCenter(location -> this.worldUtil.getBiome(location.getWorldName(), location.getX(), location.getZ(), result)); } //TODO Better documentation needed. @@ -1987,8 +1944,7 @@ public class Plot { */ @Deprecated public BiomeType getBiomeSynchronous() { final Location location = this.getCenterSynchronous(); - return this.worldUtil - .getBiomeSynchronous(location.getWorldName(), location.getX(), location.getZ()); + return this.worldUtil.getBiomeSynchronous(location.getWorldName(), location.getX(), location.getZ()); } /** @@ -2120,16 +2076,14 @@ public class Plot { * - Used when a plot is merged
*/ public void removeRoadEast() { - if (this.area.getType() != PlotAreaType.NORMAL - && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { + if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { Plot other = this.getRelative(Direction.EAST); Location bot = other.getBottomAbs(); Location top = this.getTopAbs(); Location pos1 = Location.at(this.getWorldName(), top.getX(), 0, bot.getZ()); Location pos2 = Location.at(this.getWorldName(), bot.getX(), MAX_HEIGHT, top.getZ()); this.regionManager.regenerateRegion(pos1, pos2, true, null); - } else if (this.area.getTerrain() - != PlotAreaTerrainType.ALL) { // no road generated => no road to remove + } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove this.area.getPlotManager().removeRoadEast(this); } } @@ -2289,10 +2243,8 @@ public class Plot { } } else { TaskManager.runTaskAsync(() -> { - String name = Plot.this.id + "," + Plot.this.area + ',' + - PlayerManager.getName(Plot.this.getOwnerAbs()); - boolean result = schematicHandler.save(value, - Settings.Paths.SCHEMATICS + File.separator + name + ".schem"); + String name = Plot.this.id + "," + Plot.this.area + ',' + PlayerManager.getName(Plot.this.getOwnerAbs()); + boolean result = schematicHandler.save(value, Settings.Paths.SCHEMATICS + File.separator + name + ".schem"); if (whenDone != null) { whenDone.value = result; TaskManager.runTask(whenDone); @@ -2339,8 +2291,7 @@ public class Plot { return false; } Plot other = (Plot) obj; - return this.hashCode() == other.hashCode() && this.id.equals(other.id) - && this.area == other.area; + return this.hashCode() == other.hashCode() && this.id.equals(other.id) && this.area == other.area; } /** @@ -2400,8 +2351,9 @@ public class Plot { if (value) { Plot other = this.getRelative(direction).getBasePlot(false); if (!other.equals(this.getBasePlot(false))) { - Plot base = other.id.getY() < this.id.getY() - || other.id.getY() == this.id.getY() && other.id.getX() < this.id.getX() ? other : this.origin; + Plot base = other.id.getY() < this.id.getY() || other.id.getY() == this.id.getY() && other.id.getX() < this.id.getX() ? + other : + this.origin; this.origin.origin = base; other.origin = base; this.origin = base; @@ -2474,8 +2426,7 @@ public class Plot { public boolean canClaim(@Nonnull PlotPlayer player) { PlotCluster cluster = this.getCluster(); if (cluster != null) { - if (!cluster.isAdded(player.getUUID()) && !Permissions - .hasPermission(player, "plots.admin.command.claim")) { + if (!cluster.isAdded(player.getUUID()) && !Permissions.hasPermission(player, "plots.admin.command.claim")) { return false; } } @@ -2491,16 +2442,14 @@ public class Plot { * - Used when a plot is merged
*/ public void removeRoadSouth() { - if (this.area.getType() != PlotAreaType.NORMAL - && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { + if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { Plot other = this.getRelative(Direction.SOUTH); Location bot = other.getBottomAbs(); Location top = this.getTopAbs(); Location pos1 = Location.at(this.getWorldName(), bot.getX(), 0, top.getZ()); Location pos2 = Location.at(this.getWorldName(), top.getX(), MAX_HEIGHT, bot.getZ()); this.regionManager.regenerateRegion(pos1, pos2, true, null); - } else if (this.area.getTerrain() - != PlotAreaTerrainType.ALL) { // no road generated => no road to remove + } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove this.getManager().removeRoadSouth(this); } } @@ -2520,8 +2469,7 @@ public class Plot { return false; } Set connected = this.getConnectedPlots(); - HashSet merged = - connected.stream().map(Plot::getId).collect(Collectors.toCollection(HashSet::new)); + HashSet merged = connected.stream().map(Plot::getId).collect(Collectors.toCollection(HashSet::new)); ArrayDeque frontier = new ArrayDeque<>(connected); Plot current; boolean toReturn = false; @@ -2534,10 +2482,8 @@ public class Plot { Set plots; if ((dir == Direction.ALL || dir == Direction.NORTH) && !getMerged(Direction.NORTH)) { Plot other = current.getRelative(Direction.NORTH); - if (other != null && other.isOwner(uuid) && ( - other.getBasePlot(false).equals(current.getBasePlot(false)) - || (plots = other.getConnectedPlots()).size() <= max && frontier - .addAll(plots) && (max -= plots.size()) != -1)) { + if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) + || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { current.mergePlot(other, removeRoads); merged.add(current.getId()); merged.add(other.getId()); @@ -2551,13 +2497,10 @@ public class Plot { } } } - if (max >= 0 && (dir == Direction.ALL || dir == Direction.EAST) && !current - .getMerged(Direction.EAST)) { + if (max >= 0 && (dir == Direction.ALL || dir == Direction.EAST) && !current.getMerged(Direction.EAST)) { Plot other = current.getRelative(Direction.EAST); - if (other != null && other.isOwner(uuid) && ( - other.getBasePlot(false).equals(current.getBasePlot(false)) - || (plots = other.getConnectedPlots()).size() <= max && frontier - .addAll(plots) && (max -= plots.size()) != -1)) { + if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) + || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { current.mergePlot(other, removeRoads); merged.add(current.getId()); merged.add(other.getId()); @@ -2571,13 +2514,10 @@ public class Plot { } } } - if (max >= 0 && (dir == Direction.ALL || dir == Direction.SOUTH) && !getMerged( - Direction.SOUTH)) { + if (max >= 0 && (dir == Direction.ALL || dir == Direction.SOUTH) && !getMerged(Direction.SOUTH)) { Plot other = current.getRelative(Direction.SOUTH); - if (other != null && other.isOwner(uuid) && ( - other.getBasePlot(false).equals(current.getBasePlot(false)) - || (plots = other.getConnectedPlots()).size() <= max && frontier - .addAll(plots) && (max -= plots.size()) != -1)) { + if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) + || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { current.mergePlot(other, removeRoads); merged.add(current.getId()); merged.add(other.getId()); @@ -2591,13 +2531,10 @@ public class Plot { } } } - if (max >= 0 && (dir == Direction.ALL || dir == Direction.WEST) && !getMerged( - Direction.WEST)) { + if (max >= 0 && (dir == Direction.ALL || dir == Direction.WEST) && !getMerged(Direction.WEST)) { Plot other = current.getRelative(Direction.WEST); - if (other != null && other.isOwner(uuid) && ( - other.getBasePlot(false).equals(current.getBasePlot(false)) - || (plots = other.getConnectedPlots()).size() <= max && frontier - .addAll(plots) && (max -= plots.size()) != -1)) { + if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) + || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { current.mergePlot(other, removeRoads); merged.add(current.getId()); merged.add(other.getId()); @@ -2625,8 +2562,7 @@ public class Plot { final FlagContainer flagContainer1 = this.getFlagContainer(); final FlagContainer flagContainer2 = plot.getFlagContainer(); if (!flagContainer1.equals(flagContainer2)) { - boolean greater = - flagContainer1.getFlagMap().size() > flagContainer2.getFlagMap().size(); + boolean greater = flagContainer1.getFlagMap().size() > flagContainer2.getFlagMap().size(); if (greater) { flagContainer1.addAll(flagContainer2.getFlagMap().values()); } else { @@ -2669,14 +2605,12 @@ public class Plot { * Remove the SE road (only effects terrain) */ public void removeRoadSouthEast() { - if (this.area.getType() != PlotAreaType.NORMAL - && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { + if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { Plot other = this.getRelative(1, 1); Location pos1 = this.getTopAbs().add(1, 0, 1).withY(0); Location pos2 = other.getBottomAbs().subtract(1, 0, 1).withY(MAX_HEIGHT); this.regionManager.regenerateRegion(pos1, pos2, true, null); - } else if (this.area.getTerrain() - != PlotAreaTerrainType.ALL) { // no road generated => no road to remove + } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove this.area.getPlotManager().removeRoadSouthEast(this); } } @@ -2864,14 +2798,12 @@ public class Plot { PlotId top = PlotId.of(current.getId().getX(), current.getId().getY()); while (merge) { merge = false; - List ids = Lists.newArrayList((Iterable) - PlotId.PlotRangeIterator.range(PlotId.of(bot.getX(), bot.getY() - 1), - PlotId.of(top.getX(), bot.getY() - 1))); + List ids = Lists.newArrayList((Iterable) PlotId.PlotRangeIterator + .range(PlotId.of(bot.getX(), bot.getY() - 1), PlotId.of(top.getX(), bot.getY() - 1))); boolean tmp = true; for (PlotId id : ids) { Plot plot = this.area.getPlotAbs(id); - if (plot == null || !plot.getMerged(Direction.SOUTH) || visited - .contains(plot.getId())) { + if (plot == null || !plot.getMerged(Direction.SOUTH) || visited.contains(plot.getId())) { tmp = false; } } @@ -2879,14 +2811,12 @@ public class Plot { merge = true; bot = PlotId.of(bot.getX(), bot.getY() - 1); } - ids = Lists.newArrayList((Iterable) - PlotId.PlotRangeIterator.range(PlotId.of(top.getX() + 1, bot.getY()), - PlotId.of(top.getX() + 1, top.getY()))); + ids = Lists.newArrayList((Iterable) PlotId.PlotRangeIterator + .range(PlotId.of(top.getX() + 1, bot.getY()), PlotId.of(top.getX() + 1, top.getY()))); tmp = true; for (PlotId id : ids) { Plot plot = this.area.getPlotAbs(id); - if (plot == null || !plot.getMerged(Direction.WEST) || visited - .contains(plot.getId())) { + if (plot == null || !plot.getMerged(Direction.WEST) || visited.contains(plot.getId())) { tmp = false; } } @@ -2894,14 +2824,12 @@ public class Plot { merge = true; top = PlotId.of(top.getX() + 1, top.getY()); } - ids = Lists.newArrayList((Iterable) - PlotId.PlotRangeIterator.range(PlotId.of(bot.getX(), top.getY() + 1), - PlotId.of(top.getX(), top.getY() + 1))); + ids = Lists.newArrayList((Iterable) PlotId.PlotRangeIterator + .range(PlotId.of(bot.getX(), top.getY() + 1), PlotId.of(top.getX(), top.getY() + 1))); tmp = true; for (PlotId id : ids) { Plot plot = this.area.getPlotAbs(id); - if (plot == null || !plot.getMerged(Direction.NORTH) || visited - .contains(plot.getId())) { + if (plot == null || !plot.getMerged(Direction.NORTH) || visited.contains(plot.getId())) { tmp = false; } } @@ -2909,14 +2837,12 @@ public class Plot { merge = true; top = PlotId.of(top.getX(), top.getY() + 1); } - ids = Lists.newArrayList((Iterable) - PlotId.PlotRangeIterator.range(PlotId.of(bot.getX() - 1, bot.getY()), - PlotId.of(bot.getX() - 1, top.getY()))); + ids = Lists.newArrayList((Iterable) PlotId.PlotRangeIterator + .range(PlotId.of(bot.getX() - 1, bot.getY()), PlotId.of(bot.getX() - 1, top.getY()))); tmp = true; for (PlotId id : ids) { Plot plot = this.area.getPlotAbs(id); - if (plot == null || !plot.getMerged(Direction.EAST) || visited - .contains(plot.getId())) { + if (plot == null || !plot.getMerged(Direction.EAST) || visited.contains(plot.getId())) { tmp = false; } } @@ -2927,8 +2853,7 @@ public class Plot { } Location gtopabs = this.area.getPlotAbs(top).getTopAbs(); Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs(); - visited.addAll(Lists.newArrayList((Iterable) - PlotId.PlotRangeIterator.range(bot, top))); + visited.addAll(Lists.newArrayList((Iterable) PlotId.PlotRangeIterator.range(bot, top))); for (int x = bot.getX(); x <= top.getX(); x++) { Plot plot = this.area.getPlotAbs(PlotId.of(x, top.getY())); if (plot.getMerged(Direction.SOUTH)) { @@ -2937,8 +2862,7 @@ public class Plot { Location botabs = plot.getBottomAbs(); Location topabs = plot.getTopAbs(); BlockVector3 pos1 = BlockVector3.at(botabs.getX(), 0, topabs.getZ() + 1); - BlockVector3 pos2 = - BlockVector3.at(topabs.getX(), Plot.MAX_HEIGHT - 1, toploc.getZ()); + BlockVector3 pos2 = BlockVector3.at(topabs.getX(), Plot.MAX_HEIGHT - 1, toploc.getZ()); regions.add(new CuboidRegion(pos1, pos2)); if (plot.getMerged(Direction.SOUTHEAST)) { pos1 = BlockVector3.at(topabs.getX() + 1, 0, topabs.getZ() + 1); @@ -2957,8 +2881,7 @@ public class Plot { Location botabs = plot.getBottomAbs(); Location topabs = plot.getTopAbs(); BlockVector3 pos1 = BlockVector3.at(topabs.getX() + 1, 0, botabs.getZ()); - BlockVector3 pos2 = - BlockVector3.at(toploc.getX(), Plot.MAX_HEIGHT - 1, topabs.getZ()); + BlockVector3 pos2 = BlockVector3.at(toploc.getX(), Plot.MAX_HEIGHT - 1, topabs.getZ()); regions.add(new CuboidRegion(pos1, pos2)); if (plot.getMerged(Direction.SOUTHEAST)) { pos1 = BlockVector3.at(topabs.getX() + 1, 0, topabs.getZ() + 1); @@ -2969,8 +2892,7 @@ public class Plot { } } BlockVector3 pos1 = BlockVector3.at(gbotabs.getX(), 0, gbotabs.getZ()); - BlockVector3 pos2 = - BlockVector3.at(gtopabs.getX(), Plot.MAX_HEIGHT - 1, gtopabs.getZ()); + BlockVector3 pos2 = BlockVector3.at(gtopabs.getX(), Plot.MAX_HEIGHT - 1, gtopabs.getZ()); regions.add(new CuboidRegion(pos1, pos2)); } return regions; @@ -2986,9 +2908,8 @@ public class Plot { CuboidRegion max = null; double area = Double.NEGATIVE_INFINITY; for (CuboidRegion region : regions) { - double current = - (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * ( - region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1); + double current = (region.getMaximumPoint().getX() - (double) region.getMinimumPoint().getX() + 1) * ( + region.getMaximumPoint().getZ() - (double) region.getMinimumPoint().getZ() + 1); if (current > area) { max = region; area = current; @@ -3016,12 +2937,9 @@ public class Plot { if (players.isEmpty()) { return; } - final String string = - Captions.PLOT_DEBUG.getTranslated().replace("%plot%", this.toString()) - .replace("%message%", message); + final String string = Captions.PLOT_DEBUG.getTranslated().replace("%plot%", this.toString()).replace("%message%", message); for (final PlotPlayer player : players) { - if (isOwner(player.getUUID()) || Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_DEBUG_OTHER)) { + if (isOwner(player.getUUID()) || Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_DEBUG_OTHER)) { player.sendMessage(string); } } @@ -3037,8 +2955,7 @@ public class Plot { public List getAllCorners() { Area area = new Area(); for (CuboidRegion region : this.getRegions()) { - Rectangle2D rect = new Rectangle2D.Double(region.getMinimumPoint().getX() - 0.6, - region.getMinimumPoint().getZ() - 0.6, + Rectangle2D rect = new Rectangle2D.Double(region.getMinimumPoint().getX() - 0.6, region.getMinimumPoint().getZ() - 0.6, region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + 1.2, region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + 1.2); Area rectArea = new Area(rect); @@ -3074,26 +2991,22 @@ public class Plot { * @param cause the cause of the teleport * @param resultConsumer Called with the result of the teleportation */ - public void teleportPlayer(final PlotPlayer player, TeleportCause cause, - Consumer resultConsumer) { + public void teleportPlayer(final PlotPlayer player, TeleportCause cause, Consumer resultConsumer) { Plot plot = this.getBasePlot(false); - Result result = - this.eventDispatcher.callTeleport(player, player.getLocation(), plot).getEventResult(); + Result result = this.eventDispatcher.callTeleport(player, player.getLocation(), plot).getEventResult(); if (result == Result.DENY) { sendMessage(player, Captions.EVENT_DENIED, "Teleport"); resultConsumer.accept(false); return; } final Consumer locationConsumer = location -> { - if (Settings.Teleport.DELAY == 0 || Permissions - .hasPermission(player, "plots.teleport.delay.bypass")) { + if (Settings.Teleport.DELAY == 0 || Permissions.hasPermission(player, "plots.teleport.delay.bypass")) { MainUtil.sendMessage(player, Captions.TELEPORTED_TO_PLOT); player.teleport(location, cause); resultConsumer.accept(true); return; } - MainUtil - .sendMessage(player, Captions.TELEPORT_IN_SECONDS, Settings.Teleport.DELAY + ""); + MainUtil.sendMessage(player, Captions.TELEPORT_IN_SECONDS, Settings.Teleport.DELAY + ""); final String name = player.getName(); TaskManager.addToTeleportQueue(name); TaskManager.runTaskLater(() -> { @@ -3103,7 +3016,8 @@ public class Plot { try { MainUtil.sendMessage(player, Captions.TELEPORTED_TO_PLOT); player.teleport(location, cause); - } catch (final Exception ignored) {} + } catch (final Exception ignored) { + } }, TaskTime.seconds(Settings.Teleport.DELAY)); resultConsumer.accept(true); }; @@ -3124,12 +3038,11 @@ public class Plot { return false; } if (!isMerged()) { - return PlotSquared.platform().getPlayerManager() - .getPlayerIfExists(Objects.requireNonNull(this.getOwnerAbs())) != null; + return PlotSquared.platform().getPlayerManager().getPlayerIfExists(Objects.requireNonNull(this.getOwnerAbs())) != null; } for (final Plot current : getConnectedPlots()) { - if (current.hasOwner() && PlotSquared.platform().getPlayerManager() - .getPlayerIfExists(Objects.requireNonNull(current.getOwnerAbs())) != null) { + if (current.hasOwner() + && PlotSquared.platform().getPlayerManager().getPlayerIfExists(Objects.requireNonNull(current.getOwnerAbs())) != null) { return true; } } @@ -3145,10 +3058,8 @@ public class Plot { * @param blocks Pattern to use the generation * @return True if the component was set successfully */ - public boolean setComponent(String component, Pattern blocks, - @Nullable QueueCoordinator queue) { - PlotComponentSetEvent event = - this.eventDispatcher.callComponentSet(this, component, blocks); + public boolean setComponent(String component, Pattern blocks, @Nullable QueueCoordinator queue) { + PlotComponentSetEvent event = this.eventDispatcher.callComponentSet(this, component, blocks); component = event.getComponent(); blocks = event.getPattern(); return this.getManager().setComponent(this.getId(), component, blocks, queue); @@ -3157,8 +3068,7 @@ public class Plot { public int getDistanceFromOrigin() { Location bot = getManager().getPlotBottomLocAbs(id); Location top = getManager().getPlotTopLocAbs(id); - return Math.max(Math.max(Math.abs(bot.getX()), Math.abs(bot.getZ())), - Math.max(Math.abs(top.getX()), Math.abs(top.getZ()))); + return Math.max(Math.max(Math.abs(bot.getX()), Math.abs(bot.getZ())), Math.max(Math.abs(top.getX()), Math.abs(top.getZ()))); } /** @@ -3246,10 +3156,8 @@ public class Plot { * @param allowSwap whether to swap plots * @return success */ - public CompletableFuture move(final Plot destination, final Runnable whenDone, - boolean allowSwap) { - final PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(), - destination.getId().getY() - this.getId().getY()); + public CompletableFuture move(final Plot destination, final Runnable whenDone, boolean allowSwap) { + final PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(), destination.getId().getY() - this.getId().getY()); Location db = destination.getBottomAbs(); Location ob = this.getBottomAbs(); final int offsetX = db.getX() - ob.getX(); @@ -3315,8 +3223,7 @@ public class Plot { Location[] corners = getCorners(getWorldName(), region); Location pos1 = corners[0]; Location pos2 = corners[1]; - Location pos3 = - pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); + Location pos3 = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); regionManager.swap(pos1, pos2, pos3, this); } } @@ -3326,8 +3233,7 @@ public class Plot { @Override public void run() { if (regions.isEmpty()) { Plot plot = destination.getRelative(0, 0); - Plot originPlot = originArea - .getPlotAbs(PlotId.of(plot.id.getX() - offset.getX(), plot.id.getY() - offset.getY())); + Plot originPlot = originArea.getPlotAbs(PlotId.of(plot.id.getX() - offset.getX(), plot.id.getY() - offset.getY())); final Runnable clearDone = () -> { for (final Plot current : plot.getConnectedPlots()) { getManager().claimPlot(current); @@ -3347,8 +3253,7 @@ public class Plot { Location[] corners = getCorners(getWorldName(), region); final Location pos1 = corners[0]; final Location pos2 = corners[1]; - Location newPos = - pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); + Location newPos = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); regionManager.copyRegion(pos1, pos2, newPos, task); } }.run(); @@ -3365,8 +3270,7 @@ public class Plot { * @return */ public boolean copy(final Plot destination, final Runnable whenDone) { - PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(), - destination.getId().getY() - this.getId().getY()); + PlotId offset = PlotId.of(destination.getId().getX() - this.getId().getX(), destination.getId().getY() - this.getId().getY()); Location db = destination.getBottomAbs(); Location ob = this.getBottomAbs(); final int offsetX = db.getX() - ob.getX(); @@ -3395,8 +3299,7 @@ public class Plot { other.getFlagContainer().addAll(plot.getFlagContainer().getFlagMap().values()); // Update the database for (final PlotFlag flag : existingFlags) { - final PlotFlag newFlag = - other.getFlagContainer().queryLocal(flag.getClass()); + final PlotFlag newFlag = other.getFlagContainer().queryLocal(flag.getClass()); if (other.getFlagContainer().queryLocal(flag.getClass()) == null) { DBFunc.removeFlag(other, flag); } else { @@ -3442,8 +3345,7 @@ public class Plot { Location[] corners = getCorners(getWorldName(), region); Location pos1 = corners[0]; Location pos2 = corners[1]; - Location newPos = - pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); + Location newPos = pos1.add(offsetX, 0, offsetZ).withWorld(destination.getWorldName()); regionManager.copyRegion(pos1, pos2, newPos, this); } }; @@ -3506,112 +3408,102 @@ public class Plot { int num = this.getConnectedPlots().size(); String alias = !this.getAlias().isEmpty() ? this.getAlias() : Captions.NONE.getTranslated(); Location bot = this.getCorners()[0]; - PlotSquared.platform().getWorldUtil() - .getBiome(this.getWorldName(), bot.getX(), bot.getZ(), biome -> { - String info = iInfo; - String trusted = PlayerManager.getPlayerList(this.getTrusted()); - String members = PlayerManager.getPlayerList(this.getMembers()); - String denied = PlayerManager.getPlayerList(this.getDenied()); - String seen; - if (Settings.Enabled_Components.PLOT_EXPIRY && ExpireManager.IMP != null) { - if (this.isOnline()) { - seen = Captions.NOW.getTranslated(); + PlotSquared.platform().getWorldUtil().getBiome(this.getWorldName(), bot.getX(), bot.getZ(), biome -> { + String info = iInfo; + String trusted = PlayerManager.getPlayerList(this.getTrusted()); + String members = PlayerManager.getPlayerList(this.getMembers()); + String denied = PlayerManager.getPlayerList(this.getDenied()); + String seen; + if (Settings.Enabled_Components.PLOT_EXPIRY && ExpireManager.IMP != null) { + if (this.isOnline()) { + seen = Captions.NOW.getTranslated(); + } else { + int time = (int) (ExpireManager.IMP.getAge(this) / 1000); + if (time != 0) { + seen = TimeUtil.secToTime(time); } else { - int time = (int) (ExpireManager.IMP.getAge(this) / 1000); - if (time != 0) { - seen = TimeUtil.secToTime(time); - } else { - seen = Captions.UNKNOWN.getTranslated(); - } - } - } else { - seen = Captions.NEVER.getTranslated(); - } - - String description = this.getFlag(DescriptionFlag.class); - if (description.isEmpty()) { - description = Captions.PLOT_NO_DESCRIPTION.getTranslated(); - } - - StringBuilder flags = new StringBuilder(); - Collection> flagCollection = this.getApplicableFlags(true); - if (flagCollection.isEmpty()) { - flags.append(Captions.NONE.getTranslated()); - } else { - String prefix = " "; - for (final PlotFlag flag : flagCollection) { - Object value; - if (flag instanceof DoubleFlag && !Settings.General.SCIENTIFIC) { - value = FLAG_DECIMAL_FORMAT.format(flag.getValue()); - } else { - value = flag.toString(); - } - flags.append(prefix).append(CaptionUtility - .format(player, Captions.PLOT_FLAG_LIST.getTranslated(), flag.getName(), - CaptionUtility.formatRaw(player, value.toString(), ""))); - prefix = ", "; + seen = Captions.UNKNOWN.getTranslated(); } } - boolean build = this.isAdded(player.getUUID()); - String owner = this.getOwners().isEmpty() ? "unowned" : PlayerManager.getPlayerList(this.getOwners()); - if (this.getArea() != null) { - info = info.replace("%area%", - this.getArea().getWorldName() + (this.getArea().getId() == null ? - "" : - "(" + this.getArea().getId() + ")")); - } else { - info = info.replace("%area%", Captions.NONE.getTranslated()); + } else { + seen = Captions.NEVER.getTranslated(); + } + + String description = this.getFlag(DescriptionFlag.class); + if (description.isEmpty()) { + description = Captions.PLOT_NO_DESCRIPTION.getTranslated(); + } + + StringBuilder flags = new StringBuilder(); + Collection> flagCollection = this.getApplicableFlags(true); + if (flagCollection.isEmpty()) { + flags.append(Captions.NONE.getTranslated()); + } else { + String prefix = " "; + for (final PlotFlag flag : flagCollection) { + Object value; + if (flag instanceof DoubleFlag && !Settings.General.SCIENTIFIC) { + value = FLAG_DECIMAL_FORMAT.format(flag.getValue()); + } else { + value = flag.toString(); + } + flags.append(prefix).append(CaptionUtility.format(player, Captions.PLOT_FLAG_LIST.getTranslated(), flag.getName(), + CaptionUtility.formatRaw(player, value.toString(), ""))); + prefix = ", "; } - info = info.replace("%id%", this.getId().toString()); - info = info.replace("%alias%", alias); - info = info.replace("%num%", String.valueOf(num)); - info = info.replace("%desc%", description); - info = info.replace("%biome%", biome.toString().toLowerCase()); - info = info.replace("%owner%", owner); - info = info.replace("%members%", members); - info = info.replace("%player%", player.getName()); - info = info.replace("%trusted%", trusted); - info = info.replace("%helpers%", members); - info = info.replace("%denied%", denied); - info = info.replace("%seen%", seen); - info = info.replace("%flags%", flags); - info = info.replace("%build%", String.valueOf(build)); - if (info.contains("%rating%")) { - final String newInfo = info; - TaskManager.runTaskAsync(() -> { - String info1; - if (Settings.Ratings.USE_LIKES) { - info1 = newInfo.replaceAll("%rating%", - String.format("%.0f%%", Like.getLikesPercentage(this) * 100D)); - } else { - int max = 10; - if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES - .isEmpty()) { - max = 8; - } - if (full && Settings.Ratings.CATEGORIES != null - && Settings.Ratings.CATEGORIES.size() > 1) { - double[] ratings = this.getAverageRatings(); - String rating = ""; - String prefix = ""; - for (int i = 0; i < ratings.length; i++) { - rating += - prefix + Settings.Ratings.CATEGORIES.get(i) + '=' + String - .format("%.1f", ratings[i]); - prefix = ","; - } - info1 = newInfo.replaceAll("%rating%", rating); - } else { - info1 = newInfo.replaceAll("%rating%", - String.format("%.1f", this.getAverageRating()) + '/' + max); - } + } + boolean build = this.isAdded(player.getUUID()); + String owner = this.getOwners().isEmpty() ? "unowned" : PlayerManager.getPlayerList(this.getOwners()); + if (this.getArea() != null) { + info = info.replace("%area%", + this.getArea().getWorldName() + (this.getArea().getId() == null ? "" : "(" + this.getArea().getId() + ")")); + } else { + info = info.replace("%area%", Captions.NONE.getTranslated()); + } + info = info.replace("%id%", this.getId().toString()); + info = info.replace("%alias%", alias); + info = info.replace("%num%", String.valueOf(num)); + info = info.replace("%desc%", description); + info = info.replace("%biome%", biome.toString().toLowerCase()); + info = info.replace("%owner%", owner); + info = info.replace("%members%", members); + info = info.replace("%player%", player.getName()); + info = info.replace("%trusted%", trusted); + info = info.replace("%helpers%", members); + info = info.replace("%denied%", denied); + info = info.replace("%seen%", seen); + info = info.replace("%flags%", flags); + info = info.replace("%build%", String.valueOf(build)); + if (info.contains("%rating%")) { + final String newInfo = info; + TaskManager.runTaskAsync(() -> { + String info1; + if (Settings.Ratings.USE_LIKES) { + info1 = newInfo.replaceAll("%rating%", String.format("%.0f%%", Like.getLikesPercentage(this) * 100D)); + } else { + int max = 10; + if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) { + max = 8; } - future.complete(info1); - }); - return; - } - future.complete(info); - }); + if (full && Settings.Ratings.CATEGORIES != null && Settings.Ratings.CATEGORIES.size() > 1) { + double[] ratings = this.getAverageRatings(); + String rating = ""; + String prefix = ""; + for (int i = 0; i < ratings.length; i++) { + rating += prefix + Settings.Ratings.CATEGORIES.get(i) + '=' + String.format("%.1f", ratings[i]); + prefix = ","; + } + info1 = newInfo.replaceAll("%rating%", rating); + } else { + info1 = newInfo.replaceAll("%rating%", String.format("%.1f", this.getAverageRating()) + '/' + max); + } + } + future.complete(info1); + }); + return; + } + future.complete(info); + }); return future; } diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java b/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java index b42c66e19..8a1413a35 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java @@ -32,6 +32,7 @@ import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.FileBytes; import com.sk89q.worldedit.function.pattern.Pattern; +import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.Collections; @@ -42,7 +43,7 @@ public abstract class PlotManager { private final PlotArea plotArea; - public PlotManager(PlotArea plotArea) { + public PlotManager(@Nonnull PlotArea plotArea) { this.plotArea = plotArea; } @@ -55,35 +56,33 @@ public abstract class PlotManager { public abstract PlotId getPlotId(int x, int y, int z); // If you have a circular plot, just return the corner if it were a square - public abstract Location getPlotBottomLocAbs(PlotId plotId); + public abstract Location getPlotBottomLocAbs(@Nonnull PlotId plotId); // the same applies here - public abstract Location getPlotTopLocAbs(PlotId plotId); + public abstract Location getPlotTopLocAbs(@Nonnull PlotId plotId); /* * Plot clearing (return false if you do not support some method) */ - public boolean clearPlot(Plot plot, Runnable whenDone) { + public boolean clearPlot(@Nonnull Plot plot, @Nullable Runnable whenDone) { return clearPlot(plot, whenDone, null); } - public boolean claimPlot(Plot plot) { + public boolean claimPlot(@Nonnull Plot plot) { return claimPlot(plot, null); } - public boolean unClaimPlot(Plot plot, Runnable whenDone) { + public boolean unClaimPlot(@Nonnull Plot plot, @Nullable Runnable whenDone) { return unClaimPlot(plot, whenDone, null); } - public abstract boolean clearPlot(Plot plot, Runnable whenDone, - @Nullable QueueCoordinator queue); + public abstract boolean clearPlot(@Nonnull Plot plot, @Nullable Runnable whenDone, @Nullable QueueCoordinator queue); - public abstract boolean claimPlot(Plot plot, @Nullable QueueCoordinator queue); + public abstract boolean claimPlot(@Nonnull Plot plot, @Nullable QueueCoordinator queue); - public abstract boolean unClaimPlot(Plot plot, Runnable whenDone, - @Nullable QueueCoordinator queue); + public abstract boolean unClaimPlot(@Nonnull Plot plot, @Nullable Runnable whenDone, @Nullable QueueCoordinator queue); /** * Retrieves the location of where a sign should be for a plot. @@ -91,90 +90,90 @@ public abstract class PlotManager { * @param plot The plot * @return The location where a sign should be */ - public abstract Location getSignLoc(Plot plot); + public abstract Location getSignLoc(@Nonnull Plot plot); /* * Plot set functions (return false if you do not support the specific set * method). */ - public abstract String[] getPlotComponents(PlotId plotId); + public abstract String[] getPlotComponents(@Nonnull PlotId plotId); - public boolean setComponent(PlotId plotId, String component, Pattern blocks) { + public boolean setComponent(@Nonnull PlotId plotId, @Nonnull String component, @Nonnull Pattern blocks) { return setComponent(plotId, component, blocks, null); } - public abstract boolean setComponent(PlotId plotId, String component, Pattern blocks, - @Nullable QueueCoordinator queue); + public abstract boolean setComponent(@Nonnull PlotId plotId, + @Nonnull String component, + @Nonnull Pattern blocks, + @Nullable QueueCoordinator queue); /* * PLOT MERGING (return false if your generator does not support plot * merging). */ - public boolean createRoadEast(Plot plot) { + public boolean createRoadEast(@Nonnull Plot plot) { return createRoadEast(plot, null); } - public boolean createRoadSouth(Plot plot) { + public boolean createRoadSouth(@Nonnull Plot plot) { return createRoadSouth(plot, null); } - public boolean createRoadSouthEast(Plot plot) { + public boolean createRoadSouthEast(@Nonnull Plot plot) { return createRoadSouthEast(plot, null); } - public boolean removeRoadEast(Plot plot) { + public boolean removeRoadEast(@Nonnull Plot plot) { return removeRoadEast(plot, null); } - public boolean removeRoadSouth(Plot plot) { + public boolean removeRoadSouth(@Nonnull Plot plot) { return removeRoadSouth(plot, null); } - public boolean removeRoadSouthEast(Plot plot) { + public boolean removeRoadSouthEast(@Nonnull Plot plot) { return removeRoadSouthEast(plot, null); } - public boolean startPlotMerge(List plotIds) { + public boolean startPlotMerge(@Nonnull List plotIds) { return startPlotMerge(plotIds, null); } - public boolean startPlotUnlink(List plotIds) { + public boolean startPlotUnlink(@Nonnull List plotIds) { return startPlotUnlink(plotIds, null); } - public boolean finishPlotMerge(List plotIds) { + public boolean finishPlotMerge(@Nonnull List plotIds) { return finishPlotMerge(plotIds, null); } - public boolean finishPlotUnlink(List plotIds) { + public boolean finishPlotUnlink(@Nonnull List plotIds) { return finishPlotUnlink(plotIds, null); } - public abstract boolean createRoadEast(Plot plot, @Nullable QueueCoordinator queue); + public abstract boolean createRoadEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue); - public abstract boolean createRoadSouth(Plot plot, @Nullable QueueCoordinator queue); + public abstract boolean createRoadSouth(@Nonnull Plot plot, @Nullable QueueCoordinator queue); - public abstract boolean createRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue); + public abstract boolean createRoadSouthEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue); - public abstract boolean removeRoadEast(Plot plot, @Nullable QueueCoordinator queue); + public abstract boolean removeRoadEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue); - public abstract boolean removeRoadSouth(Plot plot, @Nullable QueueCoordinator queue); + public abstract boolean removeRoadSouth(@Nonnull Plot plot, @Nullable QueueCoordinator queue); - public abstract boolean removeRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue); + public abstract boolean removeRoadSouthEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue); - public abstract boolean startPlotMerge(List plotIds, @Nullable QueueCoordinator queue); + public abstract boolean startPlotMerge(@Nonnull List plotIds, @Nullable QueueCoordinator queue); - public abstract boolean startPlotUnlink(List plotIds, @Nullable QueueCoordinator queue); + public abstract boolean startPlotUnlink(@Nonnull List plotIds, @Nullable QueueCoordinator queue); - public abstract boolean finishPlotMerge(List plotIds, @Nullable QueueCoordinator queue); + public abstract boolean finishPlotMerge(@Nonnull List plotIds, @Nullable QueueCoordinator queue); - public abstract boolean finishPlotUnlink(List plotIds, - @Nullable QueueCoordinator queue); + public abstract boolean finishPlotUnlink(@Nonnull List plotIds, @Nullable QueueCoordinator queue); public void exportTemplate() throws IOException { - HashSet files = new HashSet<>(Collections.singletonList( - new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", - Template.getBytes(plotArea)))); + HashSet files = + new HashSet<>(Collections.singletonList(new FileBytes(Settings.Paths.TEMPLATES + "/tmp-data.yml", Template.getBytes(plotArea)))); Template.zipAll(plotArea.getWorldName(), files); } diff --git a/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java b/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java index f35f164ee..cffa305a1 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlotManager.java @@ -35,6 +35,7 @@ import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.FileUtils; import com.plotsquared.core.util.task.TaskManager; import com.sk89q.worldedit.function.pattern.Pattern; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -55,19 +56,17 @@ public class SinglePlotManager extends PlotManager { return PlotId.of(0, 0); } - @Override public Location getPlotBottomLocAbs(@Nonnull final PlotId plotId) { + @Override public Location getPlotBottomLocAbs(@Nonnull final @NotNull PlotId plotId) { return Location.at(plotId.toCommaSeparatedString(), -30000000, 0, -30000000); } - @Override public Location getPlotTopLocAbs(@Nonnull final PlotId plotId) { + @Override public Location getPlotTopLocAbs(@Nonnull final @NotNull PlotId plotId) { return Location.at(plotId.toCommaSeparatedString(), 30000000, 0, 30000000); } - @Override - public boolean clearPlot(Plot plot, final Runnable whenDone, @Nullable QueueCoordinator queue) { + @Override public boolean clearPlot(@NotNull Plot plot, final Runnable whenDone, @Nullable QueueCoordinator queue) { PlotSquared.platform().getSetupUtils().unload(plot.getWorldName(), false); - final File worldFolder = - new File(PlotSquared.platform().getWorldContainer(), plot.getWorldName()); + final File worldFolder = new File(PlotSquared.platform().getWorldContainer(), plot.getWorldName()); TaskManager.getPlatformImplementation().taskAsync(() -> { FileUtils.deleteDirectory(worldFolder); if (whenDone != null) { @@ -77,73 +76,68 @@ public class SinglePlotManager extends PlotManager { return true; } - @Override public boolean claimPlot(Plot plot, @Nullable QueueCoordinator queue) { + @Override public boolean claimPlot(@NotNull Plot plot, @Nullable QueueCoordinator queue) { // TODO return true; } - @Override - public boolean unClaimPlot(Plot plot, Runnable whenDone, @Nullable QueueCoordinator queue) { + @Override public boolean unClaimPlot(@NotNull Plot plot, Runnable whenDone, @Nullable QueueCoordinator queue) { if (whenDone != null) { whenDone.run(); } return true; } - @Override public Location getSignLoc(Plot plot) { + @Override public Location getSignLoc(@NotNull Plot plot) { return null; } - @Override public String[] getPlotComponents(PlotId plotId) { + @Override public String[] getPlotComponents(@NotNull PlotId plotId) { return new String[0]; } - @Override public boolean setComponent(PlotId plotId, String component, Pattern blocks, - @Nullable QueueCoordinator queue) { - return false; - } - - @Override public boolean createRoadEast(Plot plot, @Nullable QueueCoordinator queue) { - return false; - } - - @Override public boolean createRoadSouth(Plot plot, @Nullable QueueCoordinator queue) { - return false; - } - - @Override public boolean createRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { - return false; - } - - @Override public boolean removeRoadEast(Plot plot, @Nullable QueueCoordinator queue) { - return false; - } - - @Override public boolean removeRoadSouth(Plot plot, @Nullable QueueCoordinator queue) { - return false; - } - - @Override public boolean removeRoadSouthEast(Plot plot, @Nullable QueueCoordinator queue) { - return false; - } - @Override - public boolean startPlotMerge(List plotIds, @Nullable QueueCoordinator queue) { + public boolean setComponent(@NotNull PlotId plotId, @NotNull String component, @NotNull Pattern blocks, @Nullable QueueCoordinator queue) { return false; } - @Override - public boolean startPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean createRoadEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) { return false; } - @Override - public boolean finishPlotMerge(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean createRoadSouth(@NotNull Plot plot, @Nullable QueueCoordinator queue) { return false; } - @Override - public boolean finishPlotUnlink(List plotIds, @Nullable QueueCoordinator queue) { + @Override public boolean createRoadSouthEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) { + return false; + } + + @Override public boolean removeRoadEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) { + return false; + } + + @Override public boolean removeRoadSouth(@NotNull Plot plot, @Nullable QueueCoordinator queue) { + return false; + } + + @Override public boolean removeRoadSouthEast(@NotNull Plot plot, @Nullable QueueCoordinator queue) { + return false; + } + + @Override public boolean startPlotMerge(@NotNull List plotIds, @Nullable QueueCoordinator queue) { + return false; + } + + @Override public boolean startPlotUnlink(@NotNull List plotIds, @Nullable QueueCoordinator queue) { + return false; + } + + @Override public boolean finishPlotMerge(@NotNull List plotIds, @Nullable QueueCoordinator queue) { + return false; + } + + @Override public boolean finishPlotUnlink(@NotNull List plotIds, @Nullable QueueCoordinator queue) { return false; } diff --git a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java index 87fe6d634..beb1ae0ea 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java @@ -40,8 +40,7 @@ public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator private final PlotArea area; - public AreaBoundDelegateQueueCoordinator(@Nonnull final PlotArea area, - @Nullable final QueueCoordinator parent) { + public AreaBoundDelegateQueueCoordinator(@Nonnull final PlotArea area, @Nullable final QueueCoordinator parent) { super(parent); this.area = Objects.requireNonNull(area); } @@ -50,42 +49,42 @@ public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator return this.area; } - @Override public boolean setBlock(int x, int y, int z, BlockState id) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) { if (area.contains(x, z)) { return super.setBlock(x, y, z, id); } return false; } - @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) { if (area.contains(x, z)) { return super.setBlock(x, y, z, id); } return false; } - @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { if (area.contains(x, z)) { return super.setBlock(x, y, z, pattern); } return false; } - @Override public boolean setBiome(int x, int z, BiomeType biome) { + @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biome) { if (area.contains(x, z)) { return super.setBiome(x, z, biome); } return false; } - @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { + @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome) { if (area.contains(x, z)) { return super.setBiome(x, y, z, biome); } return false; } - @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { + @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) { if (area.contains(x, z)) { return super.setTile(x, y, z, tag); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index 3e00deee5..8a4ae98ec 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -48,8 +48,7 @@ import java.util.function.Consumer; public abstract class BasicQueueCoordinator extends QueueCoordinator { private final World world; - private final ConcurrentHashMap blockChunks = - new ConcurrentHashMap<>(); + private final ConcurrentHashMap blockChunks = new ConcurrentHashMap<>(); private final List readRegion = new ArrayList<>(); private long modified; private LocalChunk lastWrappedChunk; @@ -63,16 +62,15 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { private CuboidRegion regenRegion = null; private Consumer consumer = null; private boolean unloadAfter = true; - private GlobalBlockQueue globalBlockQueue; - public BasicQueueCoordinator(World world) { + public BasicQueueCoordinator(@Nonnull World world) { this.world = world; this.modified = System.currentTimeMillis(); } @Override public abstract BlockState getBlock(int x, int y, int z); - @Override public final World getWorld() { + @Override public final @Nonnull World getWorld() { return world; } @@ -88,7 +86,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z)); } - @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) { if ((y > 255) || (y < 0)) { return false; } @@ -97,14 +95,14 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return true; } - @Override public boolean setBlock(int x, int y, int z, BlockState id) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) { // Trying to mix BlockState and BaseBlock leads to all kinds of issues. // Since BaseBlock has more features than BlockState, simply convert // all BlockStates to BaseBlocks return setBlock(x, y, z, id.toBaseBlock()); } - @Override public boolean setBiome(int x, int z, BiomeType biomeType) { + @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biomeType) { LocalChunk chunk = getChunk(x >> 4, z >> 4); for (int y = 0; y < 256; y++) { chunk.setBiome(x & 15, y, z & 15, biomeType); @@ -113,7 +111,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return true; } - @Override public final boolean setBiome(int x, int y, int z, BiomeType biomeType) { + @Override public final boolean setBiome(int x, int y, int z, @Nonnull BiomeType biomeType) { LocalChunk chunk = getChunk(x >> 4, z >> 4); chunk.setBiome(x & 15, y, z & 15, biomeType); settingBiomes = true; @@ -124,7 +122,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return this.settingBiomes; } - @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { + @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) { LocalChunk chunk = getChunk(x >> 4, z >> 4); chunk.setTile(x, y, z, tag); settingTiles = true; @@ -135,7 +133,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return this.settingTiles; } - @Override public boolean setEntity(Entity entity) { + @Override public boolean setEntity(@Nonnull Entity entity) { if (entity.getState() == null || entity.getState().getType() == EntityTypes.PLAYER) { return false; } @@ -145,15 +143,15 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return true; } - @Override public List getReadChunks() { + @Override public @Nonnull List getReadChunks() { return this.readRegion; } - @Override public void addReadChunk(BlockVector2 chunk) { + @Override public void addReadChunk(@Nonnull BlockVector2 chunk) { this.readRegion.add(chunk); } - @Override public void addReadChunks(Set readRegion) { + @Override public void addReadChunks(@Nonnull Set readRegion) { this.readRegion.addAll(readRegion); } @@ -161,7 +159,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return this.regenRegion != null ? this.regenRegion.clone() : null; } - @Override public void setRegenRegion(CuboidRegion regenRegion) { + @Override public void setRegenRegion(@Nonnull CuboidRegion regenRegion) { this.regenRegion = regenRegion; } @@ -219,7 +217,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { return this.consumer; } - public final void setChunkConsumer(Consumer consumer) { + public final void setChunkConsumer(@Nonnull Consumer consumer) { this.consumer = consumer; } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java index 980e8ee78..2eac2ba2b 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java @@ -53,8 +53,7 @@ public class ChunkCoordinatorBuilder { private int initialBatchSize = 4; private boolean unloadAfter = true; - @Inject - public ChunkCoordinatorBuilder(@Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory) { + @Inject public ChunkCoordinatorBuilder(@Nonnull ChunkCoordinatorFactory chunkCoordinatorFactory) { this.chunkCoordinatorFactory = chunkCoordinatorFactory; } @@ -64,18 +63,16 @@ public class ChunkCoordinatorBuilder { } @Nonnull public ChunkCoordinatorBuilder withChunk(@Nonnull final BlockVector2 chunkLocation) { - this.requestedChunks - .add(Preconditions.checkNotNull(chunkLocation, "Chunk location may not be null")); + this.requestedChunks.add(Preconditions.checkNotNull(chunkLocation, "Chunk location may not be null")); return this; } - @Nonnull public ChunkCoordinatorBuilder withChunks( - @Nonnull final Collection chunkLocations) { + @Nonnull public ChunkCoordinatorBuilder withChunks(@Nonnull final Collection chunkLocations) { chunkLocations.forEach(this::withChunk); return this; } - @Nonnull public ChunkCoordinatorBuilder withRegion(Location pos1, Location pos2) { + @Nonnull public ChunkCoordinatorBuilder withRegion(@Nonnull Location pos1, @Nonnull Location pos2) { final int p1x = pos1.getX(); final int p1z = pos1.getZ(); final int p2x = pos2.getX(); @@ -96,10 +93,8 @@ public class ChunkCoordinatorBuilder { return this; } - @Nonnull public ChunkCoordinatorBuilder withConsumer( - @Nonnull final Consumer chunkConsumer) { - this.chunkConsumer = - Preconditions.checkNotNull(chunkConsumer, "Chunk consumer may not be null"); + @Nonnull public ChunkCoordinatorBuilder withConsumer(@Nonnull final Consumer chunkConsumer) { + this.chunkConsumer = Preconditions.checkNotNull(chunkConsumer, "Chunk consumer may not be null"); return this; } @@ -123,10 +118,8 @@ public class ChunkCoordinatorBuilder { return this; } - @Nonnull public ChunkCoordinatorBuilder withThrowableConsumer( - @Nonnull final Consumer throwableConsumer) { - this.throwableConsumer = - Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null"); + @Nonnull public ChunkCoordinatorBuilder withThrowableConsumer(@Nonnull final Consumer throwableConsumer) { + this.throwableConsumer = Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null"); return this; } @@ -141,8 +134,8 @@ public class ChunkCoordinatorBuilder { Preconditions.checkNotNull(this.whenDone, "No final action was supplied"); Preconditions.checkNotNull(this.throwableConsumer, "No throwable consumer was supplied"); return chunkCoordinatorFactory - .create(this.maxIterationTime, this.initialBatchSize, this.chunkConsumer, this.world, - this.requestedChunks, this.whenDone, this.throwableConsumer, this.unloadAfter); + .create(this.maxIterationTime, this.initialBatchSize, this.chunkConsumer, this.world, this.requestedChunks, this.whenDone, + this.throwableConsumer, this.unloadAfter); } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java index 820cffa61..f03c8f25c 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java @@ -45,7 +45,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { private final BlockVector3 bot; private final BlockVector3 top; - public ChunkQueueCoordinator(BlockVector3 bot, BlockVector3 top, boolean biomes) { + public ChunkQueueCoordinator(@Nonnull BlockVector3 bot, @Nonnull BlockVector3 top, boolean biomes) { super(null, Location.at("", 0, 0, 0), Location.at("", 15, 255, 15)); this.width = top.getX() - bot.getX() + 1; this.length = top.getZ() - bot.getZ() + 1; @@ -55,11 +55,11 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { this.top = top; } - public BlockState[][][] getBlocks() { + @Nonnull public BlockState[][][] getBlocks() { return result; } - @Override public boolean setBiome(int x, int z, BiomeType biomeType) { + @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biomeType) { if (this.biomeResult != null) { for (int y = 0; y < 256; y++) { this.storeCacheBiome(x, y, z, biomeType); @@ -69,7 +69,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { return false; } - @Override public boolean setBiome(int x, int y, int z, BiomeType biomeType) { + @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biomeType) { if (this.biomeResult != null) { this.storeCacheBiome(x, y, z, biomeType); return true; @@ -77,17 +77,17 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { return false; } - @Override public boolean setBlock(int x, int y, int z, BlockState id) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) { this.storeCache(x, y, z, id); return true; } - @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { this.storeCache(x, y, z, pattern.apply(BlockVector3.at(x, y, z)).toImmutableState()); return true; } - private void storeCache(final int x, final int y, final int z, final BlockState id) { + private void storeCache(final int x, final int y, final int z, @Nonnull final BlockState id) { BlockState[][] resultY = result[y]; if (resultY == null) { result[y] = resultY = new BlockState[length][]; @@ -99,7 +99,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { resultYZ[x] = id; } - private void storeCacheBiome(final int x, final int y, final int z, final BiomeType id) { + private void storeCacheBiome(final int x, final int y, final int z, @Nonnull final BiomeType id) { BiomeType[][] resultY = biomeResult[y]; if (resultY == null) { biomeResult[y] = resultY = new BiomeType[length][]; @@ -111,7 +111,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { resultYZ[x] = id; } - @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull final BaseBlock id) { this.storeCache(x, y, z, id.toImmutableState()); return true; } @@ -131,11 +131,11 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { return super.getWorld(); } - @Override public Location getMax() { + @Override @Nonnull public Location getMax() { return Location.at(getWorld().getName(), top.getX(), top.getY(), top.getZ()); } - @Override public Location getMin() { + @Override @Nonnull public Location getMin() { return Location.at(getWorld().getName(), bot.getX(), bot.getY(), bot.getZ()); } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index 23af47151..86a21c874 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -34,7 +34,11 @@ import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import org.jetbrains.annotations.NotNull; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.Consumer; @@ -68,42 +72,42 @@ public class DelegateQueueCoordinator extends QueueCoordinator { } } - @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { if (parent != null) { return parent.setBlock(x, y, z, pattern); } return false; } - @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) { if (parent != null) { return parent.setBlock(x, y, z, id); } return false; } - @Override public boolean setBlock(int x, int y, int z, BlockState id) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) { if (parent != null) { return parent.setBlock(x, y, z, id); } return false; } - @Override public BlockState getBlock(int x, int y, int z) { + @Override @Nullable public BlockState getBlock(int x, int y, int z) { if (parent != null) { return parent.getBlock(x, y, z); } return null; } - @Override public boolean setBiome(int x, int z, BiomeType biome) { + @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biome) { if (parent != null) { return parent.setBiome(x, z, biome); } return false; } - @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { + @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome) { if (parent != null) { return parent.setBiome(x, y, z, biome); } @@ -117,7 +121,7 @@ public class DelegateQueueCoordinator extends QueueCoordinator { return false; } - @Override public boolean setEntity(Entity entity) { + @Override public boolean setEntity(@Nonnull Entity entity) { if (parent != null) { return parent.setEntity(entity); } @@ -130,14 +134,14 @@ public class DelegateQueueCoordinator extends QueueCoordinator { } } - @Override public World getWorld() { + @Override @Nullable public World getWorld() { if (parent != null) { return parent.getWorld(); } return null; } - @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { + @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) { if (parent != null) { return parent.setTile(x, y, z, tag); } @@ -176,26 +180,26 @@ public class DelegateQueueCoordinator extends QueueCoordinator { } } - @Override public void setChunkConsumer(Consumer consumer) { + @Override public void setChunkConsumer(@Nonnull Consumer consumer) { if (parent != null) { parent.setChunkConsumer(consumer); } } - @Override public List getReadChunks() { + @Override @Nonnull public List getReadChunks() { if (parent != null) { return parent.getReadChunks(); } - return null; + return new ArrayList<>(); } - @Override public void addReadChunks(Set readChunks) { + @Override public void addReadChunks(@Nonnull Set readChunks) { if (parent != null) { parent.addReadChunks(readChunks); } } - @Override public void addReadChunk(BlockVector2 chunk) { + @Override public void addReadChunk(@Nonnull BlockVector2 chunk) { if (parent != null) { parent.addReadChunk(chunk); } @@ -214,14 +218,14 @@ public class DelegateQueueCoordinator extends QueueCoordinator { } } - @Override public CuboidRegion getRegenRegion() { + @Override @Nullable public CuboidRegion getRegenRegion() { if (parent != null) { return parent.getRegenRegion(); } return null; } - @Override public void setRegenRegion(CuboidRegion regenRegion) { + @Override public void setRegenRegion(@Nonnull CuboidRegion regenRegion) { if (parent != null) { parent.setRegenRegion(regenRegion); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java index e5d69406e..23385bd65 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java @@ -28,6 +28,7 @@ package com.plotsquared.core.queue; import com.plotsquared.core.PlotSquared; import com.sk89q.worldedit.world.World; +import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; @@ -37,12 +38,12 @@ public class GlobalBlockQueue { private final ConcurrentLinkedDeque activeQueues; private QueueProvider provider; - public GlobalBlockQueue(QueueProvider provider) { + public GlobalBlockQueue(@Nonnull QueueProvider provider) { this.provider = provider; this.activeQueues = new ConcurrentLinkedDeque<>(); } - public QueueCoordinator getNewQueue(World world) { + @Nonnull public QueueCoordinator getNewQueue(@Nonnull World world) { QueueCoordinator queue = provider.getNewQueue(world); // Auto-inject into the queue PlotSquared.platform().getInjector().injectMembers(queue); @@ -53,7 +54,7 @@ public class GlobalBlockQueue { return this.provider; } - public void setQueueProvider(QueueProvider provider) { + public void setQueueProvider(@Nonnull QueueProvider provider) { this.provider = provider; } @@ -64,7 +65,7 @@ public class GlobalBlockQueue { * @param queue {@link QueueCoordinator} instance to start. * @return true if added to queue, false otherwise */ - public boolean enqueue(QueueCoordinator queue) { + public boolean enqueue(@Nonnull QueueCoordinator queue) { boolean success = false; if (queue.size() > 0 && !activeQueues.contains(queue)) { success = activeQueues.add(queue); @@ -73,12 +74,12 @@ public class GlobalBlockQueue { return success; } - public void dequeue(QueueCoordinator queue) { + public void dequeue(@Nonnull QueueCoordinator queue) { queue.cancel(); activeQueues.remove(queue); } - public List getActiveQueues() { + @Nonnull public List getActiveQueues() { return new ArrayList<>(activeQueues); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java index 59a10f943..999f36ccb 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocalChunk.java @@ -34,6 +34,7 @@ import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; +import javax.annotation.Nonnull; import java.util.HashMap; public class LocalChunk { @@ -46,7 +47,7 @@ public class LocalChunk { private final HashMap tiles = new HashMap<>(); private final HashMap entities = new HashMap<>(); - public LocalChunk(QueueCoordinator parent, int x, int z) { + public LocalChunk(@Nonnull QueueCoordinator parent, int x, int z) { this.parent = parent; this.x = x; this.z = z; @@ -54,7 +55,7 @@ public class LocalChunk { biomes = new BiomeType[16][]; } - public QueueCoordinator getParent() { + @Nonnull public QueueCoordinator getParent() { return this.parent; } @@ -66,19 +67,19 @@ public class LocalChunk { return this.z; } - public BaseBlock[][] getBaseblocks() { + @Nonnull public BaseBlock[][] getBaseblocks() { return this.baseblocks; } - public BiomeType[][] getBiomes() { + @Nonnull public BiomeType[][] getBiomes() { return this.biomes; } - public HashMap getTiles() { + @Nonnull public HashMap getTiles() { return this.tiles; } - public void setBiome(final int x, final int y, final int z, final BiomeType biomeType) { + public void setBiome(final int x, final int y, final int z, @Nonnull final BiomeType biomeType) { final int i = y >> 4; final int j = ChunkUtil.getJ(x, y, z); BiomeType[] array = this.biomes[i]; @@ -92,7 +93,7 @@ public class LocalChunk { return MathMan.pair((short) x, (short) z); } - public void setBlock(final int x, final int y, final int z, final BaseBlock baseBlock) { + public void setBlock(final int x, final int y, final int z, @Nonnull final BaseBlock baseBlock) { final int i = y >> 4; final int j = ChunkUtil.getJ(x, y, z); BaseBlock[] array = baseblocks[i]; @@ -102,15 +103,15 @@ public class LocalChunk { array[j] = baseBlock; } - public void setTile(final int x, final int y, final int z, final CompoundTag tag) { + public void setTile(final int x, final int y, final int z, @Nonnull final CompoundTag tag) { tiles.put(BlockVector3.at(x, y, z), tag); } - public void setEntity(Location location, BaseEntity entity) { + public void setEntity(@Nonnull Location location, @Nonnull BaseEntity entity) { this.entities.put(location, entity); } - public HashMap getEntities() { + @Nonnull public HashMap getEntities() { return this.entities; } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java index e9766a53c..c2f95a875 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java @@ -32,6 +32,7 @@ import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import javax.annotation.Nonnull; import javax.annotation.Nullable; public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordinator { @@ -40,22 +41,14 @@ public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordin private final int blockX; private final int blockZ; - public LocationOffsetDelegateQueueCoordinator(final boolean[][] canPlace, final int blockX, - final int blockZ, @Nullable QueueCoordinator parent) { + public LocationOffsetDelegateQueueCoordinator(final boolean[][] canPlace, final int blockX, final int blockZ, @Nullable QueueCoordinator parent) { super(parent); this.canPlace = canPlace; this.blockX = blockX; this.blockZ = blockZ; } - @Override public boolean setBlock(int x, int y, int z, BlockState id) { - if (canPlace[x - blockX][z - blockZ]) { - return super.setBlock(x, y, z, id); - } - return false; - } - - @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) { try { if (canPlace[x - blockX][z - blockZ]) { return super.setBlock(x, y, z, id); @@ -66,20 +59,49 @@ public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordin return false; } - @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) { + try { + if (canPlace[x - blockX][z - blockZ]) { + return super.setBlock(x, y, z, id); + } + } catch (final Exception e) { + throw e; + } + return false; + } + + @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { final BlockVector3 blockVector3 = BlockVector3.at(x + blockX, y, z + blockZ); return this.setBlock(x, y, z, pattern.apply(blockVector3)); } - @Override public boolean setBiome(int x, int z, BiomeType biome) { - return super.setBiome(x, z, biome); + @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biome) { + boolean result = true; + for (int y = 0; y < 256; y++) { + result &= this.setBiome(x, z, biome); + } + return result; } - @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { - return super.setBiome(x, y, z, biome); + @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome) { + try { + if (canPlace[x - blockX][z - blockZ]) { + return super.setBiome(x, y, z, biome); + } + } catch (final Exception e) { + throw e; + } + return false; } - @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { - return super.setTile(x, y, z, tag); + @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) { + try { + if (canPlace[x - blockX][z - blockZ]) { + return super.setTile(x, y, z, tag); + } + } catch (final Exception e) { + throw e; + } + return false; } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java index e69ea308b..c352efd4c 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java @@ -30,35 +30,37 @@ import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; +import javax.annotation.Nonnull; + public class OffsetQueueCoordinator extends DelegateQueueCoordinator { private final int ox; private final int oy; private final int oz; - public OffsetQueueCoordinator(QueueCoordinator parent, int ox, int oy, int oz) { + public OffsetQueueCoordinator(@Nonnull QueueCoordinator parent, int ox, int oy, int oz) { super(parent); this.ox = ox; this.oy = oy; this.oz = oz; } - @Override public boolean setBiome(int x, int z, BiomeType biome) { + @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biome) { return super.setBiome(ox + x, oz + z, biome); } - @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { + @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome) { return super.setBiome(ox + x, oy + y, oz + z, biome); } - @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) { return super.setBlock(ox + x, oy + y, oz + z, id); } - @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { + @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { return super.setBlock(ox + x, oy + y, oz + z, pattern); } - @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { + @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) { return super.setTile(ox + x, oy + y, oz + z, tag); } } diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index f3b0f63c1..0dc596cb6 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -38,7 +38,6 @@ import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -80,7 +79,7 @@ public abstract class QueueCoordinator { return chunkObject; } - public void setChunkObject(@NotNull Object chunkObject) { + public void setChunkObject(@Nonnull Object chunkObject) { this.chunkObject = chunkObject; } @@ -92,51 +91,51 @@ public abstract class QueueCoordinator { * @param z the z coordinate from 0 to 15 inclusive * @param id the id to set the block to */ - public abstract boolean setBlock(final int x, final int y, final int z, final BlockState id); + public abstract boolean setBlock(final int x, final int y, final int z, @Nonnull final BlockState id); - public abstract boolean setBlock(final int x, final int y, final int z, final BaseBlock id); + public abstract boolean setBlock(final int x, final int y, final int z, @Nonnull final BaseBlock id); public boolean setBlock(final int x, final int y, final int z, @Nonnull final Pattern pattern) { return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z)); } - public abstract boolean setTile(int x, int y, int z, CompoundTag tag); + public abstract boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag); public abstract boolean isSettingTiles(); - public abstract BlockState getBlock(int x, int y, int z); + @Nullable public abstract BlockState getBlock(int x, int y, int z); - @Deprecated public abstract boolean setBiome(int x, int z, BiomeType biome); + @Deprecated public abstract boolean setBiome(int x, int z, @Nonnull BiomeType biome); - public abstract boolean setBiome(int x, int y, int z, BiomeType biome); + public abstract boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome); public abstract boolean isSettingBiomes(); - public void addEntities(List entities) { + public void addEntities(@Nonnull List entities) { for (Entity e : entities) { this.setEntity(e); } } - public abstract boolean setEntity(Entity entity); + public abstract boolean setEntity(@Nonnull Entity entity); - public abstract List getReadChunks(); + @Nonnull public abstract List getReadChunks(); - public abstract void addReadChunks(Set readChunks); + public abstract void addReadChunks(@Nonnull Set readChunks); - public abstract void addReadChunk(BlockVector2 chunk); + public abstract void addReadChunk(@Nonnull BlockVector2 chunk); public abstract boolean isUnloadAfter(); public abstract void setUnloadAfter(boolean unloadAfter); - public abstract CuboidRegion getRegenRegion(); + @Nullable public abstract CuboidRegion getRegenRegion(); - public abstract void setRegenRegion(CuboidRegion regenRegion); + public abstract void setRegenRegion(@Nonnull CuboidRegion regenRegion); public abstract void regenChunk(int x, int z); - public abstract World getWorld(); + @Nullable public abstract World getWorld(); public final void setModified() { setModified(System.currentTimeMillis()); @@ -150,11 +149,11 @@ public abstract class QueueCoordinator { public abstract void cancel(); - public abstract void setCompleteTask(Runnable whenDone); + public abstract void setCompleteTask(@Nullable Runnable whenDone); - public abstract void setChunkConsumer(Consumer consumer); + public abstract void setChunkConsumer(@Nonnull Consumer consumer); - public void setCuboid(Location pos1, Location pos2, BlockState block) { + public void setCuboid(@Nonnull Location pos1, @Nonnull Location pos2, @Nonnull BlockState block) { int yMin = Math.min(pos1.getY(), pos2.getY()); int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); int xMin = Math.min(pos1.getX(), pos2.getX()); @@ -170,7 +169,7 @@ public abstract class QueueCoordinator { } } - public void setCuboid(Location pos1, Location pos2, Pattern blocks) { + public void setCuboid(@Nonnull Location pos1, @Nonnull Location pos2, @Nonnull Pattern blocks) { int yMin = Math.min(pos1.getY(), pos2.getY()); int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); int xMin = Math.min(pos1.getX(), pos2.getX()); @@ -186,7 +185,7 @@ public abstract class QueueCoordinator { } } - public void setBiomeCuboid(Location pos1, Location pos2, BiomeType biome) { + public void setBiomeCuboid(@Nonnull Location pos1, @Nonnull Location pos2, @Nonnull BiomeType biome) { int yMin = Math.min(pos1.getY(), pos2.getY()); int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); int xMin = Math.min(pos1.getX(), pos2.getX()); diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java index 4c234b0c7..412883f0b 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java @@ -27,11 +27,13 @@ package com.plotsquared.core.queue; import com.sk89q.worldedit.world.World; +import javax.annotation.Nonnull; + public abstract class QueueProvider { - public static QueueProvider of(final Class primary) { + public static QueueProvider of(@Nonnull final Class primary) { return new QueueProvider() { - @Override public QueueCoordinator getNewQueue(World world) { + @Override public QueueCoordinator getNewQueue(@Nonnull World world) { try { return (QueueCoordinator) primary.getConstructors()[0].newInstance(world); } catch (Throwable e) { @@ -42,5 +44,5 @@ public abstract class QueueProvider { }; } - public abstract QueueCoordinator getNewQueue(World world); + public abstract QueueCoordinator getNewQueue(@Nonnull World world); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java index 6a4589b4f..396119763 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java @@ -32,6 +32,9 @@ import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + public class ScopedQueueCoordinator extends DelegateQueueCoordinator { private final int minX; private final int minY; @@ -45,7 +48,7 @@ public class ScopedQueueCoordinator extends DelegateQueueCoordinator { private final int dy; private final int dz; - public ScopedQueueCoordinator(QueueCoordinator parent, Location min, Location max) { + public ScopedQueueCoordinator(@Nullable QueueCoordinator parent, @Nonnull Location min, @Nonnull Location max) { super(parent); this.minX = min.getX(); this.minY = min.getY(); @@ -60,13 +63,12 @@ public class ScopedQueueCoordinator extends DelegateQueueCoordinator { this.dz = maxZ - minZ; } - @Override public boolean setBiome(int x, int z, BiomeType biome) { + @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biome) { return x >= 0 && x <= dx && z >= 0 && z <= dz && super.setBiome(x + minX, z + minZ, biome); } - @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { - return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super - .setBiome(x + minX, y + minY, z + minZ, biome); + @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome) { + return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super.setBiome(x + minX, y + minY, z + minZ, biome); } public void fillBiome(BiomeType biome) { @@ -79,31 +81,27 @@ public class ScopedQueueCoordinator extends DelegateQueueCoordinator { } } - @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { - return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super - .setBlock(x + minX, y + minY, z + minZ, id); + @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) { + return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super.setBlock(x + minX, y + minY, z + minZ, id); } - @Override public boolean setBlock(int x, int y, int z, BlockState id) { - return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super - .setBlock(x + minX, y + minY, z + minZ, id); + @Override public boolean setBlock(int x, int y, int z, @Nonnull BlockState id) { + return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super.setBlock(x + minX, y + minY, z + minZ, id); } - @Override public boolean setBlock(int x, int y, int z, Pattern pattern) { - return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super - .setBlock(x + minX, y + minY, z + minZ, pattern); + @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { + return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super.setBlock(x + minX, y + minY, z + minZ, pattern); } - @Override public boolean setTile(int x, int y, int z, CompoundTag tag) { - return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super - .setTile(x + minX, y + minY, z + minZ, tag); + @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) { + return x >= 0 && x <= dx && y >= 0 && y <= dy && z >= 0 && z <= dz && super.setTile(x + minX, y + minY, z + minZ, tag); } - public Location getMin() { + @Nonnull public Location getMin() { return Location.at(this.getWorld().getName(), this.minX, this.minY, this.minZ); } - public Location getMax() { + @Nonnull public Location getMax() { return Location.at(this.getWorld().getName(), this.maxX, this.maxY, this.maxZ); } diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java index d9bfb4cd3..91d7a282f 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkManager.java @@ -38,22 +38,19 @@ import java.util.concurrent.ConcurrentHashMap; public abstract class ChunkManager { - private static final Map> forceChunks = - new ConcurrentHashMap<>(); - private static final Map> addChunks = - new ConcurrentHashMap<>(); + private static final Map> forceChunks = new ConcurrentHashMap<>(); + private static final Map> addChunks = new ConcurrentHashMap<>(); public static void setChunkInPlotArea(RunnableVal force, - RunnableVal add, String world, BlockVector2 loc) { - QueueCoordinator queue = PlotSquared.platform().getGlobalBlockQueue() - .getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); - if (PlotSquared.get().getPlotAreaManager().isAugmented(world) && PlotSquared.get() - .isNonStandardGeneration(world, loc)) { + RunnableVal add, + String world, + BlockVector2 loc) { + QueueCoordinator queue = PlotSquared.platform().getGlobalBlockQueue().getNewQueue(PlotSquared.platform().getWorldUtil().getWeWorld(world)); + if (PlotSquared.get().getPlotAreaManager().isAugmented(world) && PlotSquared.get().isNonStandardGeneration(world, loc)) { int blockX = loc.getX() << 4; int blockZ = loc.getZ() << 4; ScopedQueueCoordinator scoped = - new ScopedQueueCoordinator(queue, Location.at(world, blockX, 0, blockZ), - Location.at(world, blockX + 15, 255, blockZ + 15)); + new ScopedQueueCoordinator(queue, Location.at(world, blockX, 0, blockZ), Location.at(world, blockX + 15, 255, blockZ + 15)); if (force != null) { force.run(scoped); } else { @@ -94,7 +91,6 @@ public abstract class ChunkManager { return false; } - @Deprecated - public abstract CompletableFuture loadChunk(String world, BlockVector2 loc, boolean force); + @Deprecated public abstract CompletableFuture loadChunk(String world, BlockVector2 loc, boolean force); } diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java index d60cb0f6b..c602b1691 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java @@ -30,6 +30,8 @@ import com.sk89q.worldedit.math.BlockVector2; import lombok.experimental.UtilityClass; import org.jetbrains.annotations.Range; +import javax.annotation.Nonnull; + /** * This cache is used for world generation and just saves a bit of calculation time when checking if something is in the plot area. */ @@ -41,10 +43,10 @@ public class ChunkUtil { * Cache of mapping x,y,z coordinates to the chunk array
* - Used for efficient world generation
*/ - private static short[] x_loc; - private static short[][] y_loc; - private static short[] z_loc; - private static short[][][] CACHE_J = null; + private static final short[] x_loc; + private static final short[][] y_loc; + private static final short[] z_loc; + private static final short[][][] CACHE_J; static { x_loc = new short[4096]; @@ -126,7 +128,7 @@ public class ChunkUtil { * @param chunk BlockVector2 of chunk coordinates * @return true if the region pos1-pos2 contains the chunk */ - public static boolean isWholeChunk(Location pos1, Location pos2, BlockVector2 chunk) { + public static boolean isWholeChunk(@Nonnull Location pos1, @Nonnull Location pos2, @Nonnull BlockVector2 chunk) { int x1 = pos1.getX(); int z1 = pos1.getZ(); int x2 = pos2.getX(); diff --git a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java index 537425ba6..e2d6255d8 100644 --- a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java @@ -54,15 +54,13 @@ import java.util.Set; public abstract class RegionManager { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + RegionManager.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + RegionManager.class.getSimpleName()); public static RegionManager manager = null; private final WorldUtil worldUtil; private final GlobalBlockQueue blockQueue; - @Inject - public RegionManager(@Nonnull WorldUtil worldUtil, @Nonnull GlobalBlockQueue blockQueue) { + @Inject public RegionManager(@Nonnull WorldUtil worldUtil, @Nonnull GlobalBlockQueue blockQueue) { this.worldUtil = worldUtil; this.blockQueue = blockQueue; } @@ -83,13 +81,10 @@ public abstract class RegionManager { */ public abstract int[] countEntities(Plot plot); - public void deleteRegionFiles(final String world, final Collection chunks, - final Runnable whenDone) { + public void deleteRegionFiles(final String world, final Collection chunks, final Runnable whenDone) { TaskManager.runTaskAsync(() -> { for (BlockVector2 loc : chunks) { - String directory = - world + File.separator + "region" + File.separator + "r." + loc.getX() + "." - + loc.getZ() + ".mca"; + String directory = world + File.separator + "region" + File.separator + "r." + loc.getX() + "." + loc.getZ() + ".mca"; File file = new File(PlotSquared.platform().getWorldContainer(), directory); logger.info("[P2] - Deleting file: {} (max 1024 chunks)", file.getName()); if (file.exists()) { @@ -100,18 +95,20 @@ public abstract class RegionManager { }); } - public boolean setCuboids(final PlotArea area, final Set regions, - final Pattern blocks, int minY, int maxY, @Nullable QueueCoordinator queue) { + public boolean setCuboids(final PlotArea area, + final Set regions, + final Pattern blocks, + int minY, + int maxY, + @Nullable QueueCoordinator queue) { boolean enqueue = false; if (queue == null) { queue = area.getQueue(); enqueue = true; } for (CuboidRegion region : regions) { - Location pos1 = Location.at(area.getWorldName(), region.getMinimumPoint().getX(), minY, - region.getMinimumPoint().getZ()); - Location pos2 = Location.at(area.getWorldName(), region.getMaximumPoint().getX(), maxY, - region.getMaximumPoint().getZ()); + Location pos1 = Location.at(area.getWorldName(), region.getMinimumPoint().getX(), minY, region.getMinimumPoint().getZ()); + Location pos2 = Location.at(area.getWorldName(), region.getMaximumPoint().getX(), maxY, region.getMaximumPoint().getZ()); queue.setCuboid(pos1, pos2, blocks); } return !enqueue || queue.enqueue(); @@ -136,20 +133,17 @@ public abstract class RegionManager { /** * Copy a region to a new location (in the same world) */ - public boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, - final Runnable whenDone) { + public boolean copyRegion(final Location pos1, final Location pos2, final Location newPos, final Runnable whenDone) { final int relX = newPos.getX() - pos1.getX(); final int relZ = newPos.getZ() - pos1.getZ(); final com.sk89q.worldedit.world.World oldWorld = worldUtil.getWeWorld(pos1.getWorldName()); - final com.sk89q.worldedit.world.World newWorld = - worldUtil.getWeWorld(newPos.getWorldName()); + final com.sk89q.worldedit.world.World newWorld = worldUtil.getWeWorld(newPos.getWorldName()); final QueueCoordinator copyFrom = blockQueue.getNewQueue(oldWorld); - final BasicQueueCoordinator copyTo = - (BasicQueueCoordinator) blockQueue.getNewQueue(newWorld); + final BasicQueueCoordinator copyTo = (BasicQueueCoordinator) blockQueue.getNewQueue(newWorld); copyFromTo(pos1, pos2, relX, relZ, oldWorld, copyFrom, copyTo, false); copyFrom.setCompleteTask(copyTo::enqueue); - copyFrom.addReadChunks(new CuboidRegion(BlockVector3.at(pos1.getX(), 0, pos1.getZ()), - BlockVector3.at(pos2.getX(), 0, pos2.getZ())).getChunks()); + copyFrom + .addReadChunks(new CuboidRegion(BlockVector3.at(pos1.getX(), 0, pos1.getZ()), BlockVector3.at(pos2.getX(), 0, pos2.getZ())).getChunks()); copyTo.setCompleteTask(whenDone); copyFrom.enqueue(); return true; @@ -160,8 +154,7 @@ public abstract class RegionManager { * - pos1 and pos2 are in the same plot
* It can be harmful to the world if parameters outside this scope are provided */ - public abstract boolean regenerateRegion(Location pos1, Location pos2, boolean ignoreAugment, - Runnable whenDone); + public abstract boolean regenerateRegion(Location pos1, Location pos2, boolean ignoreAugment, Runnable whenDone); public abstract void clearAllEntities(Location pos1, Location pos2); @@ -176,11 +169,9 @@ public abstract class RegionManager { QueueCoordinator fromQueue2 = blockQueue.getNewQueue(world2); fromQueue1.setUnloadAfter(false); fromQueue2.setUnloadAfter(false); - fromQueue1.addReadChunks( - new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks()); - fromQueue2.addReadChunks(new CuboidRegion(swapPos.getBlockVector3(), BlockVector3 - .at(swapPos.getX() + pos2.getX() - pos1.getX(), 0, - swapPos.getZ() + pos2.getZ() - pos1.getZ())).getChunks()); + fromQueue1.addReadChunks(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3()).getChunks()); + fromQueue2.addReadChunks(new CuboidRegion(swapPos.getBlockVector3(), + BlockVector3.at(swapPos.getX() + pos2.getX() - pos1.getX(), 0, swapPos.getZ() + pos2.getZ() - pos1.getZ())).getChunks()); QueueCoordinator toQueue1 = blockQueue.getNewQueue(world1); QueueCoordinator toQueue2 = blockQueue.getNewQueue(world2); @@ -192,8 +183,14 @@ public abstract class RegionManager { toQueue2.setCompleteTask(whenDone); } - private void copyFromTo(Location pos1, Location pos2, int relX, int relZ, World world1, - QueueCoordinator fromQueue, QueueCoordinator toQueue, boolean removeEntities) { + private void copyFromTo(Location pos1, + Location pos2, + int relX, + int relZ, + World world1, + QueueCoordinator fromQueue, + QueueCoordinator toQueue, + boolean removeEntities) { fromQueue.setChunkConsumer(chunk -> { int cx = chunk.getX(); int cz = chunk.getZ(); @@ -214,8 +211,7 @@ public abstract class RegionManager { } } } - Region region = new CuboidRegion(BlockVector3.at(cbx + bx, 0, cbz + bz), - BlockVector3.at(cbx + tx, 255, cbz + tz)); + Region region = new CuboidRegion(BlockVector3.at(cbx + bx, 0, cbz + bz), BlockVector3.at(cbx + tx, 255, cbz + tz)); toQueue.addEntities(world1.getEntities(region)); if (removeEntities) { for (Entity entity : world1.getEntities(region)) { @@ -225,12 +221,11 @@ public abstract class RegionManager { }); } - public void setBiome(final CuboidRegion region, final int extendBiome, final BiomeType biome, - final String world, final Runnable whenDone) { - Location pos1 = Location.at(world, region.getMinimumPoint().getX() - extendBiome, - region.getMinimumPoint().getY(), region.getMinimumPoint().getZ() - extendBiome); - Location pos2 = Location.at(world, region.getMaximumPoint().getX() + extendBiome, - region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome); + public void setBiome(final CuboidRegion region, final int extendBiome, final BiomeType biome, final String world, final Runnable whenDone) { + Location pos1 = Location + .at(world, region.getMinimumPoint().getX() - extendBiome, region.getMinimumPoint().getY(), region.getMinimumPoint().getZ() - extendBiome); + Location pos2 = Location + .at(world, region.getMaximumPoint().getX() + extendBiome, region.getMaximumPoint().getY(), region.getMaximumPoint().getZ() + extendBiome); final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world)); final int minX = pos1.getX(); @@ -241,9 +236,7 @@ public abstract class RegionManager { queue.setChunkConsumer(blockVector2 -> { final int cx = blockVector2.getX() << 4; final int cz = blockVector2.getZ() << 4; - WorldUtil - .setBiome(world, Math.max(minX, cx), Math.max(minZ, cz), Math.min(maxX, cx + 15), - Math.min(maxZ, cz + 15), biome); + WorldUtil.setBiome(world, Math.max(minX, cx), Math.max(minZ, cz), Math.min(maxX, cx + 15), Math.min(maxZ, cz + 15), biome); worldUtil.refreshChunk(blockVector2.getBlockX(), blockVector2.getBlockZ(), world); }); queue.setCompleteTask(whenDone); diff --git a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java index 3c8bec5c6..d02284930 100644 --- a/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java +++ b/Core/src/main/java/com/plotsquared/core/util/SchematicHandler.java @@ -105,8 +105,7 @@ import java.util.zip.GZIPOutputStream; public abstract class SchematicHandler { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + SchematicHandler.class.getSimpleName()); + private static final Logger logger = LoggerFactory.getLogger("P2/" + SchematicHandler.class.getSimpleName()); public static SchematicHandler manager; private final WorldUtil worldUtil; private boolean exportAll = false; @@ -115,9 +114,11 @@ public abstract class SchematicHandler { this.worldUtil = worldUtil; } - public static void upload(@Nullable UUID uuid, @Nullable final String file, - @Nonnull final String extension, @Nullable final RunnableVal writeTask, - @Nonnull final RunnableVal whenDone) { + public static void upload(@Nullable UUID uuid, + @Nullable final String file, + @Nonnull final String extension, + @Nullable final RunnableVal writeTask, + @Nonnull final RunnableVal whenDone) { if (writeTask == null) { TaskManager.runTask(whenDone); return; @@ -147,23 +148,16 @@ public abstract class SchematicHandler { con.setDoOutput(true); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try (OutputStream output = con.getOutputStream(); - PrintWriter writer = new PrintWriter( - new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) { + PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true)) { String CRLF = "\r\n"; writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); - writer.append( - "Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName()) - .append(CRLF); + writer.append("Content-Type: text/plain; charset=" + StandardCharsets.UTF_8.displayName()).append(CRLF); String param = "value"; writer.append(CRLF).append(param).append(CRLF).flush(); writer.append("--" + boundary).append(CRLF); - writer.append( - "Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" - + filename + '"').append(CRLF); - writer - .append("Content-Type: " + URLConnection.guessContentTypeFromName(filename)) - .append(CRLF); + writer.append("Content-Disposition: form-data; name=\"schematicFile\"; filename=\"" + filename + '"').append(CRLF); + writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(filename)).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); writeTask.value = new AbstractDelegateOutputStream(output) { @@ -193,8 +187,7 @@ public abstract class SchematicHandler { }); } - public boolean exportAll(Collection collection, final File outputDir, - final String namingScheme, final Runnable ifSuccess) { + public boolean exportAll(Collection collection, final File outputDir, final String namingScheme, final Runnable ifSuccess) { if (this.exportAll) { return false; } @@ -223,14 +216,10 @@ public abstract class SchematicHandler { final String name; if (namingScheme == null) { - name = - plot.getId().getX() + ";" + plot.getId().getY() + ',' + plot.getArea() + ',' - + owner; + name = plot.getId().getX() + ";" + plot.getId().getY() + ',' + plot.getArea() + ',' + owner; } else { - name = namingScheme.replaceAll("%id%", plot.getId().toString()) - .replaceAll("%idx%", plot.getId().getX() + "") - .replaceAll("%idy%", plot.getId().getY() + "") - .replaceAll("%world%", plot.getArea().toString()); + name = namingScheme.replaceAll("%id%", plot.getId().toString()).replaceAll("%idx%", plot.getId().getX() + "") + .replaceAll("%idy%", plot.getId().getY() + "").replaceAll("%world%", plot.getArea().toString()); } final String directory; @@ -245,8 +234,7 @@ public abstract class SchematicHandler { @Override public void run(final CompoundTag value) { if (value != null) { TaskManager.runTaskAsync(() -> { - boolean result = - save(value, directory + File.separator + name + ".schem"); + boolean result = save(value, directory + File.separator + name + ".schem"); if (!result) { logger.error("[P2] Failed to save {}", plot.getId()); } @@ -268,9 +256,13 @@ public abstract class SchematicHandler { * @param xOffset offset x to paste it from plot origin * @param zOffset offset z to paste it from plot origin */ - public void paste(final Schematic schematic, final Plot plot, final int xOffset, - final int yOffset, final int zOffset, final boolean autoHeight, - final RunnableVal whenDone) { + public void paste(final Schematic schematic, + final Plot plot, + final int xOffset, + final int yOffset, + final int zOffset, + final boolean autoHeight, + final RunnableVal whenDone) { TaskManager.runTask(() -> { if (whenDone != null) { @@ -287,10 +279,8 @@ public abstract class SchematicHandler { final int HEIGHT = dimension.getY(); // Validate dimensions CuboidRegion region = plot.getLargestRegion(); - if (((region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + xOffset - + 1) < WIDTH) || ( - (region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + zOffset - + 1) < LENGTH) || (HEIGHT > 256)) { + if (((region.getMaximumPoint().getX() - region.getMinimumPoint().getX() + xOffset + 1) < WIDTH) || ( + (region.getMaximumPoint().getZ() - region.getMinimumPoint().getZ() + zOffset + 1) < LENGTH) || (HEIGHT > 256)) { TaskManager.runTask(whenDone); return; } @@ -307,8 +297,7 @@ public abstract class SchematicHandler { y_offset_actual = yOffset + ((ClassicPlotWorld) pw).PLOT_HEIGHT; } else { y_offset_actual = yOffset + 1 + this.worldUtil - .getHighestBlockSynchronous(plot.getWorldName(), - region.getMinimumPoint().getX() + 1, + .getHighestBlockSynchronous(plot.getWorldName(), region.getMinimumPoint().getX() + 1, region.getMinimumPoint().getZ() + 1); } } @@ -317,8 +306,7 @@ public abstract class SchematicHandler { } final Location pos1 = Location - .at(plot.getWorldName(), region.getMinimumPoint().getX() + xOffset, - y_offset_actual, region.getMinimumPoint().getZ() + zOffset); + .at(plot.getWorldName(), region.getMinimumPoint().getX() + xOffset, y_offset_actual, region.getMinimumPoint().getZ() + zOffset); final Location pos2 = pos1.add(WIDTH - 1, HEIGHT - 1, LENGTH - 1); final int p1x = pos1.getX(); @@ -341,12 +329,10 @@ public abstract class SchematicHandler { for (int rx = 0; rx < blockArrayClipboard.getDimensions().getX(); rx++) { int xx = p1x + xOffset + rx; int zz = p1z + zOffset + rz; - BaseBlock id = - blockArrayClipboard.getFullBlock(BlockVector3.at(rx, ry, rz)); + BaseBlock id = blockArrayClipboard.getFullBlock(BlockVector3.at(rx, ry, rz)); queue.setBlock(xx, yy, zz, id); if (ry == 0) { - BiomeType biome = - blockArrayClipboard.getBiome(BlockVector3.at(rx, ry, rz)); + BiomeType biome = blockArrayClipboard.getBiome(BlockVector3.at(rx, ry, rz)); queue.setBiome(xx, yy, zz, biome); } } @@ -364,8 +350,7 @@ public abstract class SchematicHandler { }); } - public abstract boolean restoreTile(QueueCoordinator queue, CompoundTag tag, int x, int y, - int z); + public abstract boolean restoreTile(QueueCoordinator queue, CompoundTag tag, int x, int y, int z); /** * Get a schematic @@ -374,8 +359,7 @@ public abstract class SchematicHandler { * @return schematic if found, else null */ public Schematic getSchematic(String name) throws UnsupportedFormatException { - File parent = - FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS); + File parent = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS); if (!parent.exists()) { if (!parent.mkdir()) { throw new RuntimeException("Could not create schematic parent directory"); @@ -384,11 +368,9 @@ public abstract class SchematicHandler { if (!name.endsWith(".schem") && !name.endsWith(".schematic")) { name = name + ".schem"; } - File file = FileUtils.getFile(PlotSquared.platform().getDirectory(), - Settings.Paths.SCHEMATICS + File.separator + name); + File file = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS + File.separator + name); if (!file.exists()) { - file = FileUtils.getFile(PlotSquared.platform().getDirectory(), - Settings.Paths.SCHEMATICS + File.separator + name); + file = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS + File.separator + name); } return getSchematic(file); } @@ -399,12 +381,10 @@ public abstract class SchematicHandler { * @return Immutable collection with schematic names */ public Collection getSchematicNames() { - final File parent = - FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS); + final File parent = FileUtils.getFile(PlotSquared.platform().getDirectory(), Settings.Paths.SCHEMATICS); final List names = new ArrayList<>(); if (parent.exists()) { - final String[] rawNames = - parent.list((dir, name) -> name.endsWith(".schematic") || name.endsWith(".schem")); + final String[] rawNames = parent.list((dir, name) -> name.endsWith(".schematic") || name.endsWith(".schem")); if (rawNames != null) { final List transformed = Arrays.stream(rawNames) //.map(rawName -> rawName.substring(0, rawName.length() - 10)) @@ -434,8 +414,7 @@ public abstract class SchematicHandler { e.printStackTrace(); } } else { - throw new UnsupportedFormatException( - "This schematic format is not recognised or supported."); + throw new UnsupportedFormatException("This schematic format is not recognised or supported."); } return null; } @@ -453,14 +432,12 @@ public abstract class SchematicHandler { public Schematic getSchematic(@Nonnull InputStream is) { try { - SpongeSchematicReader schematicReader = - new SpongeSchematicReader(new NBTInputStream(new GZIPInputStream(is))); + SpongeSchematicReader schematicReader = new SpongeSchematicReader(new NBTInputStream(new GZIPInputStream(is))); Clipboard clip = schematicReader.read(); return new Schematic(clip); } catch (IOException ignored) { try { - MCEditSchematicReader schematicReader = - new MCEditSchematicReader(new NBTInputStream(new GZIPInputStream(is))); + MCEditSchematicReader schematicReader = new MCEditSchematicReader(new NBTInputStream(new GZIPInputStream(is))); Clipboard clip = schematicReader.read(); return new Schematic(clip); } catch (IOException e) { @@ -477,8 +454,7 @@ public abstract class SchematicHandler { URL url = new URL(website); URLConnection connection = new URL(url.toString()).openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); - try (BufferedReader reader = new BufferedReader( - new InputStreamReader(connection.getInputStream()))) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { rawJSON = reader.lines().collect(Collectors.joining()); } JSONArray array = new JSONArray(rawJSON); @@ -501,8 +477,7 @@ public abstract class SchematicHandler { } upload(uuid, file, "schem", new RunnableVal() { @Override public void run(OutputStream output) { - try (NBTOutputStream nos = new NBTOutputStream( - new GZIPOutputStream(output, true))) { + try (NBTOutputStream nos = new NBTOutputStream(new GZIPOutputStream(output, true))) { nos.writeNamedTag("Schematic", tag); } catch (IOException e1) { e1.printStackTrace(); @@ -525,8 +500,7 @@ public abstract class SchematicHandler { try { File tmp = FileUtils.getFile(PlotSquared.platform().getDirectory(), path); tmp.getParentFile().mkdirs(); - try (NBTOutputStream nbtStream = new NBTOutputStream( - new GZIPOutputStream(new FileOutputStream(tmp)))) { + try (NBTOutputStream nbtStream = new NBTOutputStream(new GZIPOutputStream(new FileOutputStream(tmp)))) { nbtStream.writeNamedTag("Schematic", tag); } } catch (FileNotFoundException e) { @@ -538,8 +512,7 @@ public abstract class SchematicHandler { return true; } - public void getCompoundTag(final String world, final Set regions, - final RunnableVal whenDone) { + public void getCompoundTag(final String world, final Set regions, final RunnableVal whenDone) { // async TaskManager.runTaskAsync(() -> { // Main positions @@ -547,17 +520,15 @@ public abstract class SchematicHandler { final Location bot = corners[0]; final Location top = corners[1]; - CuboidRegion cuboidRegion = - new CuboidRegion(this.worldUtil.getWeWorld(world), bot.getBlockVector3(), - top.getBlockVector3()); + CuboidRegion cuboidRegion = new CuboidRegion(this.worldUtil.getWeWorld(world), bot.getBlockVector3(), top.getBlockVector3()); final int width = cuboidRegion.getWidth(); int height = cuboidRegion.getHeight(); final int length = cuboidRegion.getLength(); Map schematic = new HashMap<>(); schematic.put("Version", new IntTag(2)); - schematic.put("DataVersion", new IntTag(WorldEdit.getInstance().getPlatformManager() - .queryCapability(Capability.WORLD_EDITING).getDataVersion())); + schematic.put("DataVersion", + new IntTag(WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING).getDataVersion())); Map metadata = new HashMap<>(); metadata.put("WEOffsetX", new IntTag(0)); @@ -592,14 +563,12 @@ public abstract class SchematicHandler { schematic.put("Palette", new CompoundTag(paletteTag)); schematic.put("BlockData", new ByteArrayTag(buffer.toByteArray())); - schematic - .put("TileEntities", new ListTag(CompoundTag.class, tileEntities)); + schematic.put("TileEntities", new ListTag(CompoundTag.class, tileEntities)); schematic.put("BiomePaletteMax", new IntTag(biomePalette.size())); Map biomePaletteTag = new HashMap<>(); - biomePalette.forEach( - (key, value) -> biomePaletteTag.put(key, new IntTag(value))); + biomePalette.forEach((key, value) -> biomePaletteTag.put(key, new IntTag(value))); schematic.put("BiomePalette", new CompoundTag(biomePaletteTag)); schematic.put("BiomeData", new ByteArrayTag(biomeBuffer.toByteArray())); @@ -630,33 +599,23 @@ public abstract class SchematicHandler { final Runnable zTask = new Runnable() { @Override public void run() { long zstart = System.currentTimeMillis(); - while (ziter.hasNext() - && System.currentTimeMillis() - zstart < 20) { + while (ziter.hasNext() && System.currentTimeMillis() - zstart < 20) { final int z = ziter.next(); - Iterator xiter = - IntStream.range(p1x, p2x + 1).iterator(); + Iterator xiter = IntStream.range(p1x, p2x + 1).iterator(); final Runnable xTask = new Runnable() { @Override public void run() { long xstart = System.currentTimeMillis(); final int ry = y - sy; final int rz = z - p1z; - while (xiter.hasNext() - && System.currentTimeMillis() - xstart - < 20) { + while (xiter.hasNext() && System.currentTimeMillis() - xstart < 20) { final int x = xiter.next(); final int rx = x - p1x; - BlockVector3 point = - BlockVector3.at(x, y, z); - BaseBlock block = cuboidRegion.getWorld() - .getFullBlock(point); + BlockVector3 point = BlockVector3.at(x, y, z); + BaseBlock block = cuboidRegion.getWorld().getFullBlock(point); if (block.getNbtData() != null) { - Map values = - new HashMap<>(); - for (Map.Entry entry : block - .getNbtData().getValue() - .entrySet()) { - values.put(entry.getKey(), - entry.getValue()); + Map values = new HashMap<>(); + for (Map.Entry entry : block.getNbtData().getValue().entrySet()) { + values.put(entry.getKey(), entry.getValue()); } // Remove 'id' if it exists. We want 'Id' values.remove("id"); @@ -666,16 +625,12 @@ public abstract class SchematicHandler { values.remove("y"); values.remove("z"); - values.put("Id", - new StringTag(block.getNbtId())); - values.put("Pos", new IntArrayTag( - new int[] {rx, ry, rz})); + values.put("Id", new StringTag(block.getNbtId())); + values.put("Pos", new IntArrayTag(new int[] {rx, ry, rz})); - tileEntities - .add(new CompoundTag(values)); + tileEntities.add(new CompoundTag(values)); } - String blockKey = - block.toImmutableState().getAsString(); + String blockKey = block.toImmutableState().getAsString(); int blockId; if (palette.containsKey(blockKey)) { blockId = palette.get(blockKey); @@ -694,8 +649,7 @@ public abstract class SchematicHandler { continue; } BlockVector2 pt = BlockVector2.at(x, z); - BiomeType biome = - cuboidRegion.getWorld().getBiome(pt); + BiomeType biome = cuboidRegion.getWorld().getBiome(pt); String biomeStr = biome.getId(); int biomeId; if (biomePalette.containsKey(biomeStr)) { diff --git a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java index 35b3bc5ef..5f7d64e83 100644 --- a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java @@ -127,8 +127,7 @@ public abstract class WorldUtil { * @param name Block name * @return Comparison result containing the closets matching block */ - @Nonnull public abstract StringComparison.ComparisonResult getClosestBlock( - @Nonnull String name); + @Nonnull public abstract StringComparison.ComparisonResult getClosestBlock(@Nonnull String name); /** * Get the biome in a given chunk, asynchronously @@ -138,8 +137,7 @@ public abstract class WorldUtil { * @param z Chunk Z coordinate * @param result Result consumer */ - public abstract void getBiome(@Nonnull String world, int x, int z, - @Nonnull Consumer result); + public abstract void getBiome(@Nonnull String world, int x, int z, @Nonnull Consumer result); /** * Get the biome in a given chunk, asynchronously @@ -150,8 +148,7 @@ public abstract class WorldUtil { * @return Biome * @deprecated Use {@link #getBiome(String, int, int, Consumer)} */ - @Deprecated @Nonnull public abstract BiomeType getBiomeSynchronous(@Nonnull String world, int x, - int z); + @Deprecated @Nonnull public abstract BiomeType getBiomeSynchronous(@Nonnull String world, int x, int z); /** * Get the block at a given location (asynchronously) @@ -178,8 +175,7 @@ public abstract class WorldUtil { * @param z Z coordinate * @param result Result consumer */ - public abstract void getHighestBlock(@Nonnull String world, int x, int z, - @Nonnull IntConsumer result); + public abstract void getHighestBlock(@Nonnull String world, int x, int z, @Nonnull IntConsumer result); /** @@ -191,8 +187,7 @@ public abstract class WorldUtil { * @return Result * @deprecated Use {@link #getHighestBlock(String, int, int, IntConsumer)} */ - @Deprecated @Nonnegative public abstract int getHighestBlockSynchronous(@Nonnull String world, - int x, int z); + @Deprecated @Nonnegative public abstract int getHighestBlockSynchronous(@Nonnull String world, int x, int z); /** * Set the text in a sign @@ -203,8 +198,7 @@ public abstract class WorldUtil { * @param z Z coordinate * @param lines Sign text */ - public abstract void setSign(@Nonnull String world, int x, int y, int z, - @Nonnull String[] lines); + public abstract void setSign(@Nonnull String world, int x, int y, int z, @Nonnull String[] lines); /** * Set the biome in a region @@ -213,8 +207,7 @@ public abstract class WorldUtil { * @param region Region * @param biome New biome */ - public abstract void setBiomes(@Nonnull String world, @Nonnull CuboidRegion region, - @Nonnull BiomeType biome); + public abstract void setBiomes(@Nonnull String world, @Nonnull CuboidRegion region, @Nonnull BiomeType biome); /** * Get the WorldEdit {@link com.sk89q.worldedit.world.World} corresponding to a world name @@ -233,82 +226,72 @@ public abstract class WorldUtil { */ public abstract void refreshChunk(int x, int z, String world); - public void upload(@Nonnull final Plot plot, @Nullable final UUID uuid, - @Nullable final String file, @Nonnull final RunnableVal whenDone) { - plot.getHome( - home -> SchematicHandler.upload(uuid, file, "zip", new RunnableVal() { - @Override public void run(OutputStream output) { - try (final ZipOutputStream zos = new ZipOutputStream(output)) { - File dat = getDat(plot.getWorldName()); - Location spawn = getSpawn(plot.getWorldName()); - if (dat != null) { - ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName()); - zos.putNextEntry(ze); - try (NBTInputStream nis = new NBTInputStream( - new GZIPInputStream(new FileInputStream(dat)))) { - CompoundTag tag = (CompoundTag) nis.readNamedTag().getTag(); - CompoundTag data = (CompoundTag) tag.getValue().get("Data"); - Map map = ReflectionUtils.getMap(data.getValue()); - map.put("SpawnX", new IntTag(home.getX())); - map.put("SpawnY", new IntTag(home.getY())); - map.put("SpawnZ", new IntTag(home.getZ())); - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - try (NBTOutputStream out = new NBTOutputStream( - new GZIPOutputStream(baos, true))) { - //TODO Find what this should be called - out.writeNamedTag("Schematic????", tag); - } - zos.write(baos.toByteArray()); + public void upload(@Nonnull final Plot plot, @Nullable final UUID uuid, @Nullable final String file, @Nonnull final RunnableVal whenDone) { + plot.getHome(home -> SchematicHandler.upload(uuid, file, "zip", new RunnableVal() { + @Override public void run(OutputStream output) { + try (final ZipOutputStream zos = new ZipOutputStream(output)) { + File dat = getDat(plot.getWorldName()); + Location spawn = getSpawn(plot.getWorldName()); + if (dat != null) { + ZipEntry ze = new ZipEntry("world" + File.separator + dat.getName()); + zos.putNextEntry(ze); + try (NBTInputStream nis = new NBTInputStream(new GZIPInputStream(new FileInputStream(dat)))) { + CompoundTag tag = (CompoundTag) nis.readNamedTag().getTag(); + CompoundTag data = (CompoundTag) tag.getValue().get("Data"); + Map map = ReflectionUtils.getMap(data.getValue()); + map.put("SpawnX", new IntTag(home.getX())); + map.put("SpawnY", new IntTag(home.getY())); + map.put("SpawnZ", new IntTag(home.getZ())); + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + try (NBTOutputStream out = new NBTOutputStream(new GZIPOutputStream(baos, true))) { + //TODO Find what this should be called + out.writeNamedTag("Schematic????", tag); } + zos.write(baos.toByteArray()); } } - setSpawn(spawn); - byte[] buffer = new byte[1024]; - for (Plot current : plot.getConnectedPlots()) { - Location bot = current.getBottomAbs(); - Location top = current.getTopAbs(); - int brx = bot.getX() >> 9; - int brz = bot.getZ() >> 9; - int trx = top.getX() >> 9; - int trz = top.getZ() >> 9; - Set files = getChunkChunks(bot.getWorldName()); - for (BlockVector2 mca : files) { - if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz - && mca.getZ() <= trz) { - final File file = - getMcr(plot.getWorldName(), mca.getX(), mca.getZ()); - if (file != null) { - //final String name = "r." + (x - cx) + "." + (z - cz) + ".mca"; - String name = file.getName(); - final ZipEntry ze = new ZipEntry( - "world" + File.separator + "region" + File.separator - + name); - zos.putNextEntry(ze); - try (FileInputStream in = new FileInputStream(file)) { - int len; - while ((len = in.read(buffer)) > 0) { - zos.write(buffer, 0, len); - } - } - zos.closeEntry(); - } - } - } - } - zos.closeEntry(); - zos.flush(); - zos.finish(); - } catch (IOException e) { - e.printStackTrace(); } + setSpawn(spawn); + byte[] buffer = new byte[1024]; + for (Plot current : plot.getConnectedPlots()) { + Location bot = current.getBottomAbs(); + Location top = current.getTopAbs(); + int brx = bot.getX() >> 9; + int brz = bot.getZ() >> 9; + int trx = top.getX() >> 9; + int trz = top.getZ() >> 9; + Set files = getChunkChunks(bot.getWorldName()); + for (BlockVector2 mca : files) { + if (mca.getX() >= brx && mca.getX() <= trx && mca.getZ() >= brz && mca.getZ() <= trz) { + final File file = getMcr(plot.getWorldName(), mca.getX(), mca.getZ()); + if (file != null) { + //final String name = "r." + (x - cx) + "." + (z - cz) + ".mca"; + String name = file.getName(); + final ZipEntry ze = new ZipEntry("world" + File.separator + "region" + File.separator + name); + zos.putNextEntry(ze); + try (FileInputStream in = new FileInputStream(file)) { + int len; + while ((len = in.read(buffer)) > 0) { + zos.write(buffer, 0, len); + } + } + zos.closeEntry(); + } + } + } + } + zos.closeEntry(); + zos.flush(); + zos.finish(); + } catch (IOException e) { + e.printStackTrace(); } - }, whenDone)); + } + }, whenDone)); } @Nullable final File getDat(@Nonnull final String world) { - File file = new File( - PlotSquared.platform().getWorldContainer() + File.separator + world + File.separator - + "level.dat"); + File file = new File(PlotSquared.platform().getWorldContainer() + File.separator + world + File.separator + "level.dat"); if (file.exists()) { return file; } @@ -316,8 +299,8 @@ public abstract class WorldUtil { } @Nullable private File getMcr(@Nonnull final String world, final int x, final int z) { - final File file = new File(PlotSquared.platform().getWorldContainer(), - world + File.separator + "region" + File.separator + "r." + x + '.' + z + ".mca"); + final File file = + new File(PlotSquared.platform().getWorldContainer(), world + File.separator + "region" + File.separator + "r." + x + '.' + z + ".mca"); if (file.exists()) { return file; } @@ -326,12 +309,10 @@ public abstract class WorldUtil { public Set getChunkChunks(String world) { - File folder = - new File(PlotSquared.platform().getWorldContainer(), world + File.separator + "region"); + File folder = new File(PlotSquared.platform().getWorldContainer(), world + File.separator + "region"); File[] regionFiles = folder.listFiles(); if (regionFiles == null) { - throw new RuntimeException( - "Could not find worlds folder: " + folder + " ? (no read access?)"); + throw new RuntimeException("Could not find worlds folder: " + folder + " ? (no read access?)"); } HashSet chunks = new HashSet<>(); for (File file : regionFiles) { @@ -413,7 +394,6 @@ public abstract class WorldUtil { * @param chunk Chunk coordinates * @return Tile entity count */ - @Nonnegative public abstract int getTileEntityCount(@Nonnull String world, - @Nonnull BlockVector2 chunk); + @Nonnegative public abstract int getTileEntityCount(@Nonnull String world, @Nonnull BlockVector2 chunk); } From 7aaa075ba816413e2f1ba7e15c4d030589731855 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 24 Jul 2020 17:00:08 +0100 Subject: [PATCH 42/49] Javadoc, some cleanup --- .../bukkit/queue/BukkitQueueCoordinator.java | 7 +- .../plotsquared/bukkit/queue/GenChunk.java | 33 ++++- .../core/generator/AugmentedUtils.java | 2 + .../AreaBoundDelegateQueueCoordinator.java | 6 + .../core/queue/BasicQueueCoordinator.java | 41 +++++- .../core/queue/ChunkCoordinatorBuilder.java | 37 +++++ .../core/queue/ChunkQueueCoordinator.java | 5 +- .../core/queue/DelegateQueueCoordinator.java | 11 +- .../core/queue/GlobalBlockQueue.java | 3 + ...ocationOffsetDelegateQueueCoordinator.java | 3 + .../core/queue/OffsetQueueCoordinator.java | 66 --------- .../core/queue/QueueCoordinator.java | 132 +++++++++++++++++- .../plotsquared/core/queue/QueueProvider.java | 3 + .../core/queue/ScopedQueueCoordinator.java | 3 + 14 files changed, 268 insertions(+), 84 deletions(-) delete mode 100644 Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java index 510b63e7a..460d6ac1e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitQueueCoordinator.java @@ -67,7 +67,6 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { private org.bukkit.World bukkitWorld; @Inject private ChunkCoordinatorBuilderFactory chunkCoordinatorBuilderFactory; @Inject private ChunkCoordinatorFactory chunkCoordinatorFactory; - private Runnable whenDone; private ChunkCoordinator chunkCoordinator; @Inject public BukkitQueueCoordinator(@Nonnull World world) { @@ -198,7 +197,7 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { } chunkCoordinator = chunkCoordinatorBuilderFactory.create(chunkCoordinatorFactory).inWorld(getWorld()).withChunks(getBlockChunks().keySet()).withChunks(read) - .withInitialBatchSize(3).withMaxIterationTime(40).withThrowableConsumer(Throwable::printStackTrace).withFinalAction(whenDone) + .withInitialBatchSize(3).withMaxIterationTime(40).withThrowableConsumer(Throwable::printStackTrace).withFinalAction(getCompleteTask()) .withConsumer(consumer).unloadAfter(isUnloadAfter()).build(); return super.enqueue(); } @@ -239,8 +238,4 @@ public class BukkitQueueCoordinator extends BasicQueueCoordinator { } } - @Override public void setCompleteTask(Runnable whenDone) { - this.whenDone = whenDone; - } - } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java index 195882d81..e9a22a575 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/GenChunk.java @@ -71,6 +71,9 @@ public class GenChunk extends ScopedQueueCoordinator { return this.chunkData; } + /** + * Set the internal Bukkit chunk data + */ public void setChunkData(@Nonnull ChunkData chunkData) { this.chunkData = chunkData; } @@ -85,10 +88,17 @@ public class GenChunk extends ScopedQueueCoordinator { return chunk; } + /** + * Set the chunk being represented + */ public void setChunk(@Nonnull Chunk chunk) { this.chunk = chunk; } + + /** + * Set the world and XZ of the chunk being represented via {@link ChunkWrapper} + */ public void setChunk(@Nonnull ChunkWrapper wrap) { chunk = null; world = wrap.world; @@ -101,9 +111,11 @@ public class GenChunk extends ScopedQueueCoordinator { return; } Biome biome = BukkitAdapter.adapt(biomeType); - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - this.biomeGrid.setBiome(x, z, biome); + for (int y = 0; y < 256; y++) { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + this.biomeGrid.setBiome(x, y, z, biome); + } } } } @@ -134,9 +146,22 @@ public class GenChunk extends ScopedQueueCoordinator { return setBiome(x, z, BukkitAdapter.adapt(biomeType)); } + /** + * Set the in the whole column of XZ + */ public boolean setBiome(int x, int z, @Nonnull Biome biome) { if (this.biomeGrid != null) { - this.biomeGrid.setBiome(x, z, biome); + for (int y = 0; y < 256; y++) { + this.setBiome(x, y, z, biome); + } + return true; + } + return false; + } + + public boolean setBiome(int x, int y, int z, @Nonnull Biome biome) { + if (this.biomeGrid != null) { + this.biomeGrid.setBiome(x, y, z, biome); return true; } return false; diff --git a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java index f888f9bd9..1b42889ca 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/AugmentedUtils.java @@ -162,6 +162,8 @@ public class AugmentedUtils { new ScopedQueueCoordinator(secondaryMask, Location.at(world, blockX, 0, blockZ), Location.at(world, blockX + 15, 255, blockZ + 15)); generator.generateChunk(scoped, area); generator.populateChunk(scoped, area); + scoped.setForceSync(true); + scoped.enqueue(); } if (enqueue) { queue.enqueue(); diff --git a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java index beb1ae0ea..7d7c4aff6 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/AreaBoundDelegateQueueCoordinator.java @@ -36,6 +36,9 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Objects; +/** + * Queue Coordinator that only sets blocks with the specified PlotArea + */ public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator { private final PlotArea area; @@ -45,6 +48,9 @@ public class AreaBoundDelegateQueueCoordinator extends DelegateQueueCoordinator this.area = Objects.requireNonNull(area); } + /** + * Gets the plot area block settings is limited to + */ public PlotArea getArea() { return this.area; } diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index 8a4ae98ec..684eea7f6 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -39,12 +39,16 @@ import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.entity.EntityTypes; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; +/** + * Standard block setting queue that allows block setting across numerous chunks, without limits. + */ public abstract class BasicQueueCoordinator extends QueueCoordinator { private final World world; @@ -62,6 +66,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { private CuboidRegion regenRegion = null; private Consumer consumer = null; private boolean unloadAfter = true; + private Runnable whenDone; public BasicQueueCoordinator(@Nonnull World world) { this.world = world; @@ -193,35 +198,61 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { this.unloadAfter = unloadAfter; } + /** + * Gets the int[x,z] chunk coordinates where regeneration should start from + */ public int[] getRegenStart() { return regenStart; } + /** + * Gets the int[x,z] chunk coordinates where regeneration should finish + */ public int[] getRegenEnd() { return regenEnd; } + /** + * Whether the queue has a start/end to chunk regeneration + */ public boolean isRegen() { return regen; } - public ConcurrentHashMap getBlockChunks() { + /** + * Gets the map of ChunkCoordinates in {@link BlockVector2} form against the {@link LocalChunk} of cached chunks to be written + */ + @Nonnull public ConcurrentHashMap getBlockChunks() { return this.blockChunks; } - public final void setChunk(LocalChunk chunk) { + /** + * Forces an {@link LocalChunk} into the list of chunks to be written. Overwrites existing chunks in the map + */ + public final void setChunk(@Nonnull LocalChunk chunk) { this.blockChunks.put(BlockVector2.at(chunk.getX(), chunk.getZ()), chunk); } - public final Consumer getChunkConsumer() { + @Override @Nullable public final Consumer getChunkConsumer() { return this.consumer; } - public final void setChunkConsumer(@Nonnull Consumer consumer) { + @Override public final void setChunkConsumer(@Nonnull Consumer consumer) { this.consumer = consumer; } - private LocalChunk getChunk(final int chunkX, final int chunkZ) { + @Override public Runnable getCompleteTask() { + return this.whenDone; + } + + @Override public void setCompleteTask(Runnable whenDone) { + this.whenDone = whenDone; + } + + /** + * Get the {@link LocalChunk} from the queue at the given chunk coordinates. Returns a new instance if one doesn't exist + */ + @Nonnull private LocalChunk getChunk(final int chunkX, final int chunkZ) { if (chunkX != lastX || chunkZ != lastZ) { lastX = chunkX; lastZ = chunkZ; diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java index 2eac2ba2b..2ead29881 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinatorBuilder.java @@ -40,6 +40,9 @@ import java.util.LinkedList; import java.util.List; import java.util.function.Consumer; +/** + * Builds a {@link ChunkCoordinator} instance + */ public class ChunkCoordinatorBuilder { private final List requestedChunks = new LinkedList<>(); @@ -57,21 +60,33 @@ public class ChunkCoordinatorBuilder { this.chunkCoordinatorFactory = chunkCoordinatorFactory; } + /** + * Set the world + */ @Nonnull public ChunkCoordinatorBuilder inWorld(@Nonnull final World world) { this.world = Preconditions.checkNotNull(world, "World may not be null"); return this; } + /** + * Add a chunk to be accessed + */ @Nonnull public ChunkCoordinatorBuilder withChunk(@Nonnull final BlockVector2 chunkLocation) { this.requestedChunks.add(Preconditions.checkNotNull(chunkLocation, "Chunk location may not be null")); return this; } + /** + * Add a Collection of chunks to be accessed + */ @Nonnull public ChunkCoordinatorBuilder withChunks(@Nonnull final Collection chunkLocations) { chunkLocations.forEach(this::withChunk); return this; } + /** + * Add chunks within a region to be accessed + */ @Nonnull public ChunkCoordinatorBuilder withRegion(@Nonnull Location pos1, @Nonnull Location pos2) { final int p1x = pos1.getX(); final int p1z = pos1.getZ(); @@ -93,11 +108,17 @@ public class ChunkCoordinatorBuilder { return this; } + /** + * Set the consumer to be used when a chunk is loaded + */ @Nonnull public ChunkCoordinatorBuilder withConsumer(@Nonnull final Consumer chunkConsumer) { this.chunkConsumer = Preconditions.checkNotNull(chunkConsumer, "Chunk consumer may not be null"); return this; } + /** + * Set the Runnable to run when all chunks have been accessed + */ @Nonnull public ChunkCoordinatorBuilder withFinalAction(@Nullable final Runnable whenDone) { if (whenDone == null) { return this; @@ -106,28 +127,44 @@ public class ChunkCoordinatorBuilder { return this; } + /** + * Set the max time taken while iterating over and accessing loaded chunks + */ @Nonnull public ChunkCoordinatorBuilder withMaxIterationTime(final long maxIterationTime) { Preconditions.checkArgument(maxIterationTime > 0, "Max iteration time must be positive"); this.maxIterationTime = maxIterationTime; return this; } + /** + * Set the initial batch size to be used for loading chunks + */ @Nonnull public ChunkCoordinatorBuilder withInitialBatchSize(final int initialBatchSize) { Preconditions.checkArgument(initialBatchSize > 0, "Initial batch size must be positive"); this.initialBatchSize = initialBatchSize; return this; } + /** + * Set the consumer to be used to handle {@link Throwable}s + */ @Nonnull public ChunkCoordinatorBuilder withThrowableConsumer(@Nonnull final Consumer throwableConsumer) { this.throwableConsumer = Preconditions.checkNotNull(throwableConsumer, "Throwable consumer may not be null"); return this; } + /** + * Set whether the chunks should be allow to unload after being accessed. This should only be used where the chunks are read from + * and then written to from a separate queue where they're consequently unloaded. + */ @Nonnull public ChunkCoordinatorBuilder unloadAfter(final boolean unloadAfter) { this.unloadAfter = unloadAfter; return this; } + /** + * Create a new {@link ChunkCoordinator} instance based on the values in the Builder instance. + */ @Nonnull public ChunkCoordinator build() { Preconditions.checkNotNull(this.world, "No world was supplied"); Preconditions.checkNotNull(this.chunkConsumer, "No chunk consumer was supplied"); diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java index f03c8f25c..d04a0c798 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkQueueCoordinator.java @@ -36,6 +36,9 @@ import com.sk89q.worldedit.world.block.BlockState; import javax.annotation.Nonnull; import javax.annotation.Nullable; +/** + * Queue that is limited to a single chunk + */ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { public final BiomeType[][][] biomeResult; @@ -127,7 +130,7 @@ public class ChunkQueueCoordinator extends ScopedQueueCoordinator { return null; } - @Override @Nonnull public World getWorld() { + @Override @Nullable public World getWorld() { return super.getWorld(); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index 86a21c874..7a97f4c39 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -34,7 +34,6 @@ import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -43,6 +42,9 @@ import java.util.List; import java.util.Set; import java.util.function.Consumer; +/** + * Queue that delegates to a parent queue. + */ public class DelegateQueueCoordinator extends QueueCoordinator { private final QueueCoordinator parent; @@ -180,6 +182,13 @@ public class DelegateQueueCoordinator extends QueueCoordinator { } } + @Nullable @Override public Consumer getChunkConsumer() { + if (parent != null) { + return parent.getChunkConsumer(); + } + return null; + } + @Override public void setChunkConsumer(@Nonnull Consumer consumer) { if (parent != null) { parent.setChunkConsumer(consumer); diff --git a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java index 23385bd65..a251aced7 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java +++ b/Core/src/main/java/com/plotsquared/core/queue/GlobalBlockQueue.java @@ -43,6 +43,9 @@ public class GlobalBlockQueue { this.activeQueues = new ConcurrentLinkedDeque<>(); } + /** + * Get a new {@link QueueCoordinator} for the given world. + */ @Nonnull public QueueCoordinator getNewQueue(@Nonnull World world) { QueueCoordinator queue = provider.getNewQueue(world); // Auto-inject into the queue diff --git a/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java index c2f95a875..fd86f7eb2 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/LocationOffsetDelegateQueueCoordinator.java @@ -35,6 +35,9 @@ import com.sk89q.worldedit.world.block.BlockState; import javax.annotation.Nonnull; import javax.annotation.Nullable; +/** + * Offsets input coordinates and delegates to a parent queue + */ public class LocationOffsetDelegateQueueCoordinator extends DelegateQueueCoordinator { private final boolean[][] canPlace; diff --git a/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java deleted file mode 100644 index c352efd4c..000000000 --- a/Core/src/main/java/com/plotsquared/core/queue/OffsetQueueCoordinator.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2020 IntellectualSites - * - * 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, see . - */ -package com.plotsquared.core.queue; - -import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.function.pattern.Pattern; -import com.sk89q.worldedit.world.biome.BiomeType; -import com.sk89q.worldedit.world.block.BaseBlock; - -import javax.annotation.Nonnull; - -public class OffsetQueueCoordinator extends DelegateQueueCoordinator { - private final int ox; - private final int oy; - private final int oz; - - public OffsetQueueCoordinator(@Nonnull QueueCoordinator parent, int ox, int oy, int oz) { - super(parent); - this.ox = ox; - this.oy = oy; - this.oz = oz; - } - - @Override public boolean setBiome(int x, int z, @Nonnull BiomeType biome) { - return super.setBiome(ox + x, oz + z, biome); - } - - @Override public boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome) { - return super.setBiome(ox + x, oy + y, oz + z, biome); - } - - @Override public boolean setBlock(int x, int y, int z, @Nonnull BaseBlock id) { - return super.setBlock(ox + x, oy + y, oz + z, id); - } - - @Override public boolean setBlock(int x, int y, int z, @Nonnull Pattern pattern) { - return super.setBlock(ox + x, oy + y, oz + z, pattern); - } - - @Override public boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag) { - return super.setTile(ox + x, oy + y, oz + z, tag); - } -} diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index 0dc596cb6..91738bd40 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -56,6 +56,9 @@ public abstract class QueueCoordinator { PlotSquared.platform().getInjector().injectMembers(this); } + /** + * Get a {@link ScopedQueueCoordinator} limited to the chunk at the specific chunk Coordinates + */ public ScopedQueueCoordinator getForChunk(int x, int z) { int bx = x << 4; int bz = z << 4; @@ -63,22 +66,40 @@ public abstract class QueueCoordinator { Location.at(getWorld().getName(), bx + 15, 255, bz + 255)); } + /** + * Get the size of the queue in chunks + */ public abstract int size(); + /** + * Set when the queue was last modified + */ public abstract void setModified(long modified); + /** + * Returns true if the queue should be forced to be synchronous when enqueued. + */ public boolean isForceSync() { return forceSync; } + /** + * Set whether the queue should be forced to be synchronous + */ public void setForceSync(boolean forceSync) { this.forceSync = forceSync; } + /** + * Get the Chunk Object set to the queue + */ @Nullable public Object getChunkObject() { return chunkObject; } + /** + * Set a chunk object (e.g. the Bukkit Chunk object) to the queue + */ public void setChunkObject(@Nonnull Object chunkObject) { this.chunkObject = chunkObject; } @@ -89,70 +110,173 @@ public abstract class QueueCoordinator { * @param x the x coordinate from from 0 to 15 inclusive * @param y the y coordinate from from 0 (inclusive) - maxHeight(exclusive) * @param z the z coordinate from 0 to 15 inclusive - * @param id the id to set the block to + * @param id the BlockState to set the block to */ public abstract boolean setBlock(final int x, final int y, final int z, @Nonnull final BlockState id); + /** + * Sets the block at the coordinates provided to the given id. + * + * @param x the x coordinate from from 0 to 15 inclusive + * @param y the y coordinate from from 0 (inclusive) - maxHeight(exclusive) + * @param z the z coordinate from 0 to 15 inclusive + * @param id the BaseBlock to set the block to + */ public abstract boolean setBlock(final int x, final int y, final int z, @Nonnull final BaseBlock id); + /** + * Sets the block at the coordinates provided to the given id. + * + * @param x the x coordinate from from 0 to 15 inclusive + * @param y the y coordinate from from 0 (inclusive) - maxHeight(exclusive) + * @param z the z coordinate from 0 to 15 inclusive + * @param pattern the pattern to set the block to + */ public boolean setBlock(final int x, final int y, final int z, @Nonnull final Pattern pattern) { return setBlock(x, y, z, PatternUtil.apply(pattern, x, y, z)); } + /** + * Sets a tile entity at the coordinates provided to the given CompoundTag + * + * @param x the x coordinate from from 0 to 15 inclusive + * @param y the y coordinate from from 0 (inclusive) - maxHeight(exclusive) + * @param z the z coordinate from 0 to 15 inclusive + * @param tag the CompoundTag to set the tile to + */ public abstract boolean setTile(int x, int y, int z, @Nonnull CompoundTag tag); + /** + * Whether the queue has any tiles being set + */ public abstract boolean isSettingTiles(); + /** + * Get a block at the given coordinates. + */ @Nullable public abstract BlockState getBlock(int x, int y, int z); + /** + * Set a biome in XZ. This will likely set to the whole column + */ @Deprecated public abstract boolean setBiome(int x, int z, @Nonnull BiomeType biome); + /** + * Set a biome in XYZ + */ public abstract boolean setBiome(int x, int y, int z, @Nonnull BiomeType biome); + /** + * Whether the queue has any biomes to be set + */ public abstract boolean isSettingBiomes(); + /** + * Add entities to be created + */ public void addEntities(@Nonnull List entities) { for (Entity e : entities) { this.setEntity(e); } } + /** + * Add an entity to be created + */ public abstract boolean setEntity(@Nonnull Entity entity); + /** + * Get the list of chunks that are added manually. This usually indicated the queue is "read only". + */ @Nonnull public abstract List getReadChunks(); + /** + * Add a set of {@link BlockVector2} Chunk coordinates to the Read Chunks list + */ public abstract void addReadChunks(@Nonnull Set readChunks); + /** + * Add a {@link BlockVector2} Chunk coordinate to the Read Chunks list + */ public abstract void addReadChunk(@Nonnull BlockVector2 chunk); + /** + * Whether chunks should be unloaded after being accessed + */ public abstract boolean isUnloadAfter(); + /** + * Set whether chunks should be unloaded after being accessed + */ public abstract void setUnloadAfter(boolean unloadAfter); + /** + * Get the {@link CuboidRegion} designated for direct regeneration + */ @Nullable public abstract CuboidRegion getRegenRegion(); + /** + * Set the {@link CuboidRegion} designated for direct regeneration + */ public abstract void setRegenRegion(@Nonnull CuboidRegion regenRegion); + /** + * Set a specific chunk at the chunk coordinates XZ to be regenerated. + */ public abstract void regenChunk(int x, int z); + /** + * Get the world the queue is writing to + */ @Nullable public abstract World getWorld(); + /** + * Set the queue as having been modified now + */ public final void setModified() { setModified(System.currentTimeMillis()); } + /** + * Enqueue the queue with the {@link GlobalBlockQueue} + */ public boolean enqueue() { return blockQueue.enqueue(this); } + /** + * Start the queue + */ public abstract void start(); + /** + * Cancel the queue. Not yet implemented. + */ public abstract void cancel(); + /** + * Get the task to be run when all chunks have been accessed + */ + public abstract Runnable getCompleteTask(); + + /** + * Set the task to be run when all chunks have been accessed + */ public abstract void setCompleteTask(@Nullable Runnable whenDone); + /** + * Return the chunk consumer set to the queue or null if one is not set + */ + @Nullable public abstract Consumer getChunkConsumer(); + + /** + * Set the Consumer that will + */ public abstract void setChunkConsumer(@Nonnull Consumer consumer); + /** + * Fill a cuboid between two positions with a BlockState + */ public void setCuboid(@Nonnull Location pos1, @Nonnull Location pos2, @Nonnull BlockState block) { int yMin = Math.min(pos1.getY(), pos2.getY()); int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); @@ -169,6 +293,9 @@ public abstract class QueueCoordinator { } } + /** + * Fill a cuboid between two positions with a Pattern + */ public void setCuboid(@Nonnull Location pos1, @Nonnull Location pos2, @Nonnull Pattern blocks) { int yMin = Math.min(pos1.getY(), pos2.getY()); int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); @@ -185,6 +312,9 @@ public abstract class QueueCoordinator { } } + /** + * Fill a cuboid between two positions with a BiomeType + */ public void setBiomeCuboid(@Nonnull Location pos1, @Nonnull Location pos2, @Nonnull BiomeType biome) { int yMin = Math.min(pos1.getY(), pos2.getY()); int yMax = Math.min(255, Math.max(pos1.getY(), pos2.getY())); diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java index 412883f0b..d1ee80029 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java @@ -44,5 +44,8 @@ public abstract class QueueProvider { }; } + /** + * Get a queue for the given world + */ public abstract QueueCoordinator getNewQueue(@Nonnull World world); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java index 396119763..b4fbc5e40 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ScopedQueueCoordinator.java @@ -35,6 +35,9 @@ import com.sk89q.worldedit.world.block.BlockState; import javax.annotation.Nonnull; import javax.annotation.Nullable; +/** + * Queue that only sets blocks with a designated area + */ public class ScopedQueueCoordinator extends DelegateQueueCoordinator { private final int minX; private final int minY; From 221d299052adeeb7d5d7107bbd525e13eb59593a Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 24 Jul 2020 17:52:05 +0100 Subject: [PATCH 43/49] Fix a few remaining merge issues (+1 squashed commits) Squashed commits: [8c6b55dd4] Fix a few remaining merge issues --- Bukkit/build.gradle | 1 + .../bukkit/listener/BlockEventListener.java | 359 +++++------ .../bukkit/listener/EntityEventListener.java | 80 +-- .../bukkit/listener/EntitySpawnListener.java | 17 +- .../bukkit/listener/PlayerEventListener.java | 599 ++++++++---------- .../listener/ProjectileEventListener.java | 43 +- .../bukkit/placeholder/MVdWPlaceholders.java | 26 +- .../bukkit/placeholder/PAPIPlaceholders.java | 2 +- .../bukkit/util/BukkitEntityUtil.java | 8 +- .../java/com/plotsquared/core/plot/Plot.java | 2 +- .../core/util/EventDispatcher.java | 3 + .../placeholders/PlaceholderRegistry.java | 5 +- 12 files changed, 504 insertions(+), 641 deletions(-) diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index 59b215bc8..36151ca3d 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -42,6 +42,7 @@ dependencies { implementation("net.alpenblock:BungeePerms:4.0-dev-106") compile("se.hyperver.hyperverse:Core:0.6.0-SNAPSHOT"){ transitive = false } compile('com.sk89q:squirrelid:1.0.0-SNAPSHOT'){ transitive = false } + compile('be.maximvdw:MVdWPlaceholderAPI:2.1.1-SNAPSHOT'){ transitive = false } // logging implementation('org.apache.logging.log4j:log4j-slf4j-impl:2.8.1') compile('be.maximvdw:MVdWPlaceholderAPI:3.1.1-SNAPSHOT'){ transitive = false } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java index 32408f41e..82a01d765 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java @@ -56,9 +56,12 @@ import com.plotsquared.core.plot.flag.implementations.SnowMeltFlag; import com.plotsquared.core.plot.flag.implementations.SoilDryFlag; import com.plotsquared.core.plot.flag.implementations.VineGrowFlag; import com.plotsquared.core.plot.flag.types.BlockTypeWrapper; +import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.Permissions; import com.plotsquared.core.util.task.TaskManager; +import com.plotsquared.core.util.task.TaskTime; +import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.world.block.BlockType; import org.bukkit.Bukkit; @@ -96,6 +99,8 @@ import org.bukkit.material.Directional; import org.bukkit.projectiles.BlockProjectileSource; import org.bukkit.util.Vector; +import javax.annotation.Nonnull; +import javax.inject.Inject; import java.util.Iterator; import java.util.List; import java.util.Objects; @@ -104,6 +109,14 @@ import java.util.UUID; @SuppressWarnings("unused") public class BlockEventListener implements Listener { + private final PlotAreaManager plotAreaManager; + private final WorldEdit worldEdit; + + @Inject public BlockEventListener(@Nonnull final PlotAreaManager plotAreaManager, @Nonnull final WorldEdit worldEdit) { + this.plotAreaManager = plotAreaManager; + this.worldEdit = worldEdit; + } + public static void sendBlockChange(final org.bukkit.Location bloc, final BlockData data) { TaskManager.runTaskLater(() -> { String world = bloc.getWorld().getName(); @@ -111,22 +124,21 @@ public class BlockEventListener implements Listener { int z = bloc.getBlockZ(); int distance = Bukkit.getViewDistance() * 16; - for (final PlotPlayer player : PlotSquared.imp().getPlayerManager().getPlayers()) { + for (final PlotPlayer player : PlotSquared.platform().getPlayerManager().getPlayers()) { Location location = player.getLocation(); - if (location.getWorld().equals(world)) { - if (16 * Math.abs(location.getX() - x) / 16 > distance - || 16 * Math.abs(location.getZ() - z) / 16 > distance) { + if (location.getWorldName().equals(world)) { + if (16 * Math.abs(location.getX() - x) / 16 > distance || 16 * Math.abs(location.getZ() - z) / 16 > distance) { continue; } ((BukkitPlayer) player).player.sendBlockChange(bloc, data); } } - }, 3); + }, TaskTime.ticks(3L)); } @EventHandler public void onRedstoneEvent(BlockRedstoneEvent event) { Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -149,34 +161,31 @@ public class BlockEventListener implements Listener { if (plot.isMerged()) { disable = true; for (UUID owner : plot.getOwners()) { - if (PlotSquared.imp().getPlayerManager().getPlayerIfExists(owner) != null) { + if (PlotSquared.platform().getPlayerManager().getPlayerIfExists(owner) != null) { disable = false; break; } } } else { - disable = - PlotSquared.imp().getPlayerManager().getPlayerIfExists(plot.getOwnerAbs()) - == null; + disable = PlotSquared.platform().getPlayerManager().getPlayerIfExists(plot.getOwnerAbs()) == null; } } if (disable) { for (UUID trusted : plot.getTrusted()) { - if (PlotSquared.imp().getPlayerManager().getPlayerIfExists(trusted) != null) { + if (PlotSquared.platform().getPlayerManager().getPlayerIfExists(trusted) != null) { disable = false; break; } } if (disable) { event.setNewCurrent(0); - plot.debug( - "Redstone event was cancelled because no trusted player was in the plot"); + plot.debug("Redstone event was cancelled because no trusted player was in the plot"); return; } } } if (Settings.Redstone.DISABLE_UNOCCUPIED) { - for (final PlotPlayer player : PlotSquared.imp().getPlayerManager().getPlayers()) { + for (final PlotPlayer player : PlotSquared.platform().getPlayerManager().getPlayers()) { if (plot.equals(player.getCurrentPlot())) { return; } @@ -185,12 +194,11 @@ public class BlockEventListener implements Listener { } } - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void onPhysicsEvent(BlockPhysicsEvent event) { + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onPhysicsEvent(BlockPhysicsEvent event) { switch (event.getChangedType()) { case COMPARATOR: { Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); if (location.isPlotArea()) { return; } @@ -212,7 +220,7 @@ public class BlockEventListener implements Listener { case TURTLE_HELMET: case TURTLE_SPAWN_EGG: { Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -233,9 +241,8 @@ public class BlockEventListener implements Listener { switch (block.getType()) { case PISTON: case STICKY_PISTON: - org.bukkit.block.data.Directional piston = - (org.bukkit.block.data.Directional) block.getBlockData(); - Location location = BukkitUtil.getLocation(block.getLocation()); + org.bukkit.block.data.Directional piston = (org.bukkit.block.data.Directional) block.getBlockData(); + Location location = BukkitUtil.adapt(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -246,23 +253,22 @@ public class BlockEventListener implements Listener { } switch (piston.getFacing()) { case EAST: - location.setX(location.getX() + 1); + location = location.add(1, 0, 0); break; case SOUTH: - location.setX(location.getX() - 1); + location = location.add(-1, 0, 0); break; case WEST: - location.setZ(location.getZ() + 1); + location = location.add(0, 0, 1); break; case NORTH: - location.setZ(location.getZ() - 1); + location = location.add(0, 0, -1); break; } Plot newPlot = area.getOwnedPlotAbs(location); if (!plot.equals(newPlot)) { event.setCancelled(true); - plot.debug( - "Prevented piston update because of invalid edge piston detection"); + plot.debug("Prevented piston update because of invalid edge piston detection"); return; } } @@ -271,28 +277,24 @@ public class BlockEventListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void blockCreate(BlockPlaceEvent event) { - Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void blockCreate(BlockPlaceEvent event) { + Location location = BukkitUtil.adapt(event.getBlock().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; } Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); + BukkitPlayer pp = BukkitUtil.adapt(player); Plot plot = area.getPlot(location); if (plot != null) { - if ((location.getY() > area.getMaxBuildHeight() || location.getY() < area - .getMinBuildHeight()) && !Permissions + if ((location.getY() > area.getMaxBuildHeight() || location.getY() < area.getMinBuildHeight()) && !Permissions .hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_HEIGHT_LIMIT)) { event.setCancelled(true); - MainUtil.sendMessage(pp, Captions.HEIGHT_LIMIT.getTranslated() - .replace("{limit}", String.valueOf(area.getMaxBuildHeight()))); + MainUtil.sendMessage(pp, Captions.HEIGHT_LIMIT.getTranslated().replace("{limit}", String.valueOf(area.getMaxBuildHeight()))); } if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); return; } @@ -300,23 +302,19 @@ public class BlockEventListener implements Listener { List place = plot.getFlag(PlaceFlag.class); if (place != null) { Block block = event.getBlock(); - if (place.contains( - BlockTypeWrapper.get(BukkitAdapter.asBlockType(block.getType())))) { + if (place.contains(BlockTypeWrapper.get(BukkitAdapter.asBlockType(block.getType())))) { return; } } if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); - plot.debug(player.getName() + " could not place " + event.getBlock().getType() - + " because of the place flag"); + plot.debug(player.getName() + " could not place " + event.getBlock().getType() + " because of the place flag"); return; } } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); return; } @@ -325,45 +323,38 @@ public class BlockEventListener implements Listener { Block block = event.getBlockPlaced(); if (block.getType().hasGravity()) { sendBlockChange(block.getLocation(), block.getBlockData()); - plot.debug(event.getBlock().getType() - + " did not fall because of disable-physics = true"); + plot.debug(event.getBlock().getType() + " did not fall because of disable-physics = true"); } } } else if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_ROAD); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_ROAD); event.setCancelled(true); } } @EventHandler(priority = EventPriority.LOWEST) public void blockDestroy(BlockBreakEvent event) { Player player = event.getPlayer(); - Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); + Location location = BukkitUtil.adapt(event.getBlock().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; } Plot plot = area.getPlot(location); if (plot != null) { - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + BukkitPlayer plotPlayer = BukkitUtil.adapt(player); if (event.getBlock().getY() == 0) { - if (!Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL); + if (!Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL); event.setCancelled(true); return; } - } else if ((location.getY() > area.getMaxBuildHeight() || location.getY() < area - .getMinBuildHeight()) && !Permissions + } else if ((location.getY() > area.getMaxBuildHeight() || location.getY() < area.getMinBuildHeight()) && !Permissions .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_HEIGHT_LIMIT)) { event.setCancelled(true); - MainUtil.sendMessage(plotPlayer, Captions.HEIGHT_LIMIT.getTranslated() - .replace("{limit}", String.valueOf(area.getMaxBuildHeight()))); + MainUtil.sendMessage(plotPlayer, Captions.HEIGHT_LIMIT.getTranslated().replace("{limit}", String.valueOf(area.getMaxBuildHeight()))); } if (!plot.hasOwner()) { - if (!Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED, true)) { + if (!Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED, true)) { event.setCancelled(true); } return; @@ -377,42 +368,36 @@ public class BlockEventListener implements Listener { return; } } - if (Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { + if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { return; } - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_OTHER); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_OTHER); event.setCancelled(true); } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { if (!Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); return; } } return; } - BukkitPlayer pp = BukkitUtil.getPlayer(player); + BukkitPlayer pp = BukkitUtil.adapt(player); if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { return; } - if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) { - if (player.getInventory().getItemInMainHand().getType() == Material - .getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) { + if (this.worldEdit != null && pp.getAttribute("worldedit")) { + if (player.getInventory().getItemInMainHand().getType() == Material.getMaterial(this.worldEdit.getConfiguration().wandItem)) { return; } } - MainUtil - .sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_ROAD); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_ROAD); event.setCancelled(true); } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockSpread(BlockSpreadEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockSpread(BlockSpreadEvent event) { Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); if (location.isPlotRoad()) { event.setCancelled(true); return; @@ -453,10 +438,9 @@ public class BlockEventListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockForm(BlockFormEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockForm(BlockFormEvent event) { Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); if (location.isPlotRoad()) { event.setCancelled(true); return; @@ -487,13 +471,12 @@ public class BlockEventListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityBlockForm(EntityBlockFormEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityBlockForm(EntityBlockFormEvent event) { String world = event.getBlock().getWorld().getName(); - if (!PlotSquared.get().hasPlotArea(world)) { + if (!this.plotAreaManager.hasPlotArea(world)) { return; } - Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); + Location location = BukkitUtil.adapt(event.getBlock().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -507,7 +490,7 @@ public class BlockEventListener implements Listener { if (entity instanceof Player) { Player player = (Player) entity; if (!plot.hasOwner()) { - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + BukkitPlayer plotPlayer = BukkitUtil.adapt(player); if (plot.getFlag(IceFormFlag.class)) { plot.debug("Ice could not be formed because ice-form = false"); return; @@ -515,7 +498,7 @@ public class BlockEventListener implements Listener { event.setCancelled(true); return; } - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + BukkitPlayer plotPlayer = BukkitUtil.adapt(player); if (!plot.isAdded(plotPlayer.getUUID())) { if (plot.getFlag(IceFormFlag.class)) { plot.debug("Ice could not be formed because ice-form = false"); @@ -531,10 +514,9 @@ public class BlockEventListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockDamage(BlockDamageEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockDamage(BlockDamageEvent event) { Player player = event.getPlayer(); - Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); + Location location = BukkitUtil.adapt(event.getBlock().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -557,42 +539,37 @@ public class BlockEventListener implements Listener { return; } if (!plot.hasOwner()) { - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); - if (Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + BukkitPlayer plotPlayer = BukkitUtil.adapt(player); + if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { return; } event.setCancelled(true); return; } - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + BukkitPlayer plotPlayer = BukkitUtil.adapt(player); if (!plot.isAdded(plotPlayer.getUUID())) { List destroy = plot.getFlag(BreakFlag.class); Block block = event.getBlock(); - if (destroy - .contains(BlockTypeWrapper.get(BukkitAdapter.asBlockType(block.getType()))) - || Permissions + if (destroy.contains(BlockTypeWrapper.get(BukkitAdapter.asBlockType(block.getType()))) || Permissions .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { return; } - plot.debug(player.getName() + " could not break " + block.getType() - + " because it was not in the break flag"); + plot.debug(player.getName() + " could not break " + block.getType() + " because it was not in the break flag"); event.setCancelled(true); return; } return; } - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + BukkitPlayer plotPlayer = BukkitUtil.adapt(player); if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { return; } event.setCancelled(true); } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onFade(BlockFadeEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onFade(BlockFadeEvent event) { Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -649,54 +626,46 @@ public class BlockEventListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onChange(BlockFromToEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onChange(BlockFromToEvent event) { Block from = event.getBlock(); // Check liquid flow flag inside of origin plot too - final Location fLocation = BukkitUtil.getLocation(from.getLocation()); + final Location fLocation = BukkitUtil.adapt(from.getLocation()); final PlotArea fromArea = fLocation.getPlotArea(); if (fromArea != null) { final Plot plot = fromArea.getOwnedPlot(fLocation); - if (plot != null - && plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.DISABLED && event - .getBlock().isLiquid()) { - plot.debug("Liquid could not flow because liquid-flow = disabled"); + if (plot != null && plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.DISABLED && event.getBlock().isLiquid()) { + plot.debug("Liquid could now flow because liquid-flow = disabled"); event.setCancelled(true); return; } } Block to = event.getToBlock(); - Location tLocation = BukkitUtil.getLocation(to.getLocation()); + Location tLocation = BukkitUtil.adapt(to.getLocation()); PlotArea area = tLocation.getPlotArea(); if (area == null) { return; } Plot plot = area.getOwnedPlot(tLocation); if (plot != null) { - if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects - .equals(plot, area.getOwnedPlot(fLocation))) { + if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects.equals(plot, area.getOwnedPlot(fLocation))) { event.setCancelled(true); return; } - if (plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.ENABLED && event - .getBlock().isLiquid()) { + if (plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.ENABLED && event.getBlock().isLiquid()) { return; } if (plot.getFlag(DisablePhysicsFlag.class)) { - plot.debug(event.getBlock().getType() - + " could not update because disable-physics = true"); + plot.debug(event.getBlock().getType() + " could not update because disable-physics = true"); event.setCancelled(true); return; } - if (plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.DISABLED && event - .getBlock().isLiquid()) { + if (plot.getFlag(LiquidFlowFlag.class) == LiquidFlowFlag.FlowStatus.DISABLED && event.getBlock().isLiquid()) { plot.debug("Liquid could not flow because liquid-flow = disabled"); event.setCancelled(true); } - } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects - .equals(null, area.getOwnedPlot(fLocation))) { + } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects.equals(null, area.getOwnedPlot(fLocation))) { event.setCancelled(true); } else if (event.getBlock().isLiquid()) { final org.bukkit.Location location = event.getBlock().getLocation(); @@ -704,7 +673,6 @@ public class BlockEventListener implements Listener { /* X = block location A-H = potential plot locations - Z ^ | A B C @@ -713,50 +681,46 @@ public class BlockEventListener implements Listener { v <-----O-----> x */ - if (BukkitUtil.getPlot(location.clone().add(-1, 0, 1) /* A */) != null - || BukkitUtil.getPlot(location.clone().add(1, 0, 0) /* B */) != null - || BukkitUtil.getPlot(location.clone().add(1, 0, 1) /* C */) != null - || BukkitUtil.getPlot(location.clone().add(-1, 0, 0) /* D */) != null - || BukkitUtil.getPlot(location.clone().add(1, 0, 0) /* E */) != null - || BukkitUtil.getPlot(location.clone().add(-1, 0, -1) /* F */) != null - || BukkitUtil.getPlot(location.clone().add(0, 0, -1) /* G */) != null - || BukkitUtil.getPlot(location.clone().add(1, 0, 1) /* H */) != null) { + if (BukkitUtil.adapt(location.clone().add(-1, 0, 1) /* A */).getPlot() != null + || BukkitUtil.adapt(location.clone().add(1, 0, 0) /* B */).getPlot() != null + || BukkitUtil.adapt(location.clone().add(1, 0, 1) /* C */).getPlot() != null + || BukkitUtil.adapt(location.clone().add(-1, 0, 0) /* D */).getPlot() != null + || BukkitUtil.adapt(location.clone().add(1, 0, 0) /* E */).getPlot() != null + || BukkitUtil.adapt(location.clone().add(-1, 0, -1) /* F */).getPlot() != null + || BukkitUtil.adapt(location.clone().add(0, 0, -1) /* G */).getPlot() != null + || BukkitUtil.adapt(location.clone().add(1, 0, 1) /* H */).getPlot() != null) { event.setCancelled(true); } } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onGrow(BlockGrowEvent event) { + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onGrow(BlockGrowEvent event) { Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); if (location.isUnownedPlotArea()) { event.setCancelled(true); } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonExtend(BlockPistonExtendEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockPistonExtend(BlockPistonExtendEvent event) { Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); BlockFace face = event.getDirection(); Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ()); PlotArea area = location.getPlotArea(); if (area == null) { - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) { return; } for (Block block1 : event.getBlocks()) { - Location bloc = BukkitUtil.getLocation(block1.getLocation()); - if (bloc.isPlotArea() || bloc - .add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()) - .isPlotArea()) { + Location bloc = BukkitUtil.adapt(block1.getLocation()); + if (bloc.isPlotArea() || bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()).isPlotArea()) { event.setCancelled(true); return; } } - if (location.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()) - .isPlotArea()) { + if (location.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()).isPlotArea()) { // Prevent pistons from extending if they are: bordering a plot // area, facing inside plot area, and not pushing any blocks event.setCancelled(true); @@ -769,20 +733,18 @@ public class BlockEventListener implements Listener { return; } for (Block block1 : event.getBlocks()) { - Location bloc = BukkitUtil.getLocation(block1.getLocation()); - if (!area.contains(bloc.getX(), bloc.getZ()) || !area - .contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { + Location bloc = BukkitUtil.adapt(block1.getLocation()); + if (!area.contains(bloc.getX(), bloc.getZ()) || !area.contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { event.setCancelled(true); return; } - if (!plot.equals(area.getOwnedPlot(bloc)) || !plot.equals(area.getOwnedPlot( - bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { + if (!plot.equals(area.getOwnedPlot(bloc)) || !plot + .equals(area.getOwnedPlot(bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { event.setCancelled(true); return; } } - if (!plot.equals(area.getOwnedPlot( - location.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { + if (!plot.equals(area.getOwnedPlot(location.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { // This branch is only necessary to prevent pistons from extending // if they are: on a plot edge, facing outside the plot, and not // pushing any blocks @@ -790,22 +752,19 @@ public class BlockEventListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonRetract(BlockPistonRetractEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockPistonRetract(BlockPistonRetractEvent event) { Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); BlockFace face = event.getDirection(); Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ()); PlotArea area = location.getPlotArea(); if (area == null) { - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) { return; } for (Block block1 : event.getBlocks()) { - Location bloc = BukkitUtil.getLocation(block1.getLocation()); - if (bloc.isPlotArea() || bloc - .add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()) - .isPlotArea()) { + Location bloc = BukkitUtil.adapt(block1.getLocation()); + if (bloc.isPlotArea() || bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ()).isPlotArea()) { event.setCancelled(true); return; } @@ -818,22 +777,20 @@ public class BlockEventListener implements Listener { return; } for (Block block1 : event.getBlocks()) { - Location bloc = BukkitUtil.getLocation(block1.getLocation()); - if (!area.contains(bloc.getX(), bloc.getZ()) || !area - .contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { + Location bloc = BukkitUtil.adapt(block1.getLocation()); + if (!area.contains(bloc.getX(), bloc.getZ()) || !area.contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { event.setCancelled(true); return; } - if (!plot.equals(area.getOwnedPlot(bloc)) || !plot.equals(area.getOwnedPlot( - bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { + if (!plot.equals(area.getOwnedPlot(bloc)) || !plot + .equals(area.getOwnedPlot(bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { event.setCancelled(true); return; } } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockDispense(BlockDispenseEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockDispense(BlockDispenseEvent event) { Material type = event.getItem().getType(); switch (type) { case SHULKER_BOX: @@ -870,10 +827,8 @@ public class BlockEventListener implements Listener { if (event.getBlock().getType() == Material.DROPPER) { return; } - BlockFace targetFace = - ((Directional) event.getBlock().getState().getData()).getFacing(); - Location location = - BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation()); + BlockFace targetFace = ((Directional) event.getBlock().getState().getData()).getFacing(); + Location location = BukkitUtil.adapt(event.getBlock().getRelative(targetFace).getLocation()); if (location.isPlotRoad()) { event.setCancelled(true); } @@ -881,20 +836,19 @@ public class BlockEventListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onStructureGrow(StructureGrowEvent event) { - if (!PlotSquared.get().hasPlotArea(event.getWorld().getName())) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onStructureGrow(StructureGrowEvent event) { + if (!this.plotAreaManager.hasPlotArea(event.getWorld().getName())) { return; } List blocks = event.getBlocks(); if (blocks.isEmpty()) { return; } - Location location = BukkitUtil.getLocation(blocks.get(0).getLocation()); + Location location = BukkitUtil.adapt(blocks.get(0).getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { for (int i = blocks.size() - 1; i >= 0; i--) { - location = BukkitUtil.getLocation(blocks.get(i).getLocation()); + location = BukkitUtil.adapt(blocks.get(i).getLocation()); if (location.isPlotArea()) { blocks.remove(i); } @@ -907,7 +861,7 @@ public class BlockEventListener implements Listener { return; } for (int i = blocks.size() - 1; i >= 0; i--) { - location = BukkitUtil.getLocation(blocks.get(i).getLocation()); + location = BukkitUtil.adapt(blocks.get(i).getLocation()); if (!area.contains(location.getX(), location.getZ())) { blocks.remove(i); continue; @@ -924,7 +878,7 @@ public class BlockEventListener implements Listener { return; } for (int i = blocks.size() - 1; i >= 0; i--) { - location = BukkitUtil.getLocation(blocks.get(i).getLocation()); + location = BukkitUtil.adapt(blocks.get(i).getLocation()); Plot plot = area.getOwnedPlot(location); /* * plot → the base plot of the merged area @@ -932,26 +886,24 @@ public class BlockEventListener implements Listener { */ // Are plot and origin different AND are both plots merged - if (plot != null && !Objects.equals(plot, origin) && (!plot.isMerged() && !origin - .isMerged())) { + if (!Objects.equals(plot, origin) && (!plot.isMerged() && !origin.isMerged())) { event.getBlocks().remove(i); } } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBigBoom(BlockExplodeEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBigBoom(BlockExplodeEvent event) { Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - String world = location.getWorld(); - if (!PlotSquared.get().hasPlotArea(world)) { + Location location = BukkitUtil.adapt(block.getLocation()); + String world = location.getWorldName(); + if (!this.plotAreaManager.hasPlotArea(world)) { return; } PlotArea area = location.getPlotArea(); if (area == null) { Iterator iterator = event.blockList().iterator(); while (iterator.hasNext()) { - location = BukkitUtil.getLocation(iterator.next().getLocation()); + location = BukkitUtil.adapt(iterator.next().getLocation()); if (location.isPlotArea()) { iterator.remove(); } @@ -965,14 +917,12 @@ public class BlockEventListener implements Listener { plot.debug("Explosion was cancelled because explosion = false"); } } - event.blockList().removeIf(blox -> plot != null && !plot - .equals(area.getOwnedPlot(BukkitUtil.getLocation(blox.getLocation())))); + event.blockList().removeIf(blox -> !plot.equals(area.getOwnedPlot(BukkitUtil.adapt(blox.getLocation())))); } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBurn(BlockBurnEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockBurn(BlockBurnEvent event) { Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { @@ -989,13 +939,12 @@ public class BlockEventListener implements Listener { } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockIgnite(BlockIgniteEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockIgnite(BlockIgniteEvent event) { Player player = event.getPlayer(); Entity ignitingEntity = event.getIgnitingEntity(); Block block = event.getBlock(); BlockIgniteEvent.IgniteCause igniteCause = event.getCause(); - Location location1 = BukkitUtil.getLocation(block.getLocation()); + Location location1 = BukkitUtil.adapt(block.getLocation()); PlotArea area = location1.getPlotArea(); if (area == null) { return; @@ -1007,23 +956,20 @@ public class BlockEventListener implements Listener { Plot plot = area.getOwnedPlot(location1); if (player != null) { - BukkitPlayer pp = BukkitUtil.getPlayer(player); + BukkitPlayer pp = BukkitUtil.adapt(player); if (plot == null) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_ROAD); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_ROAD); event.setCancelled(true); } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(pp.getUUID())) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } } else if (!plot.getFlag(BlockIgnitionFlag.class)) { @@ -1046,11 +992,10 @@ public class BlockEventListener implements Listener { Location location = null; if (fireball.getShooter() instanceof Entity) { Entity shooter = (Entity) fireball.getShooter(); - location = BukkitUtil.getLocation(shooter.getLocation()); + location = BukkitUtil.adapt(shooter.getLocation()); } else if (fireball.getShooter() instanceof BlockProjectileSource) { - Block shooter = - ((BlockProjectileSource) fireball.getShooter()).getBlock(); - location = BukkitUtil.getLocation(shooter.getLocation()); + Block shooter = ((BlockProjectileSource) fireball.getShooter()).getBlock(); + location = BukkitUtil.adapt(shooter.getLocation()); } if (location != null && !plot.equals(location.getPlot())) { event.setCancelled(true); @@ -1060,13 +1005,11 @@ public class BlockEventListener implements Listener { } else if (event.getIgnitingBlock() != null) { Block ignitingBlock = event.getIgnitingBlock(); - Plot plotIgnited = BukkitUtil.getLocation(ignitingBlock.getLocation()).getPlot(); - if (igniteCause == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL && ( - !plot.getFlag(BlockIgnitionFlag.class) || plotIgnited == null || !plotIgnited - .equals(plot)) || (igniteCause == BlockIgniteEvent.IgniteCause.SPREAD - || igniteCause == BlockIgniteEvent.IgniteCause.LAVA) && ( - !plot.getFlag(BlockIgnitionFlag.class) || plotIgnited == null || !plotIgnited - .equals(plot))) { + Plot plotIgnited = BukkitUtil.adapt(ignitingBlock.getLocation()).getPlot(); + if (igniteCause == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL && (!plot.getFlag(BlockIgnitionFlag.class) || plotIgnited == null + || !plotIgnited.equals(plot)) + || (igniteCause == BlockIgniteEvent.IgniteCause.SPREAD || igniteCause == BlockIgniteEvent.IgniteCause.LAVA) && ( + !plot.getFlag(BlockIgnitionFlag.class) || plotIgnited == null || !plotIgnited.equals(plot))) { event.setCancelled(true); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java index 5bfb26a56..2d4162881 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java @@ -36,6 +36,7 @@ import com.plotsquared.core.plot.flag.implementations.DisablePhysicsFlag; import com.plotsquared.core.plot.flag.implementations.ExplosionFlag; import com.plotsquared.core.plot.flag.implementations.InvincibleFlag; import com.plotsquared.core.plot.flag.implementations.MobPlaceFlag; +import com.plotsquared.core.plot.world.PlotAreaManager; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; @@ -60,30 +61,34 @@ import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; +import javax.annotation.Nonnull; +import javax.inject.Inject; import java.util.Iterator; import java.util.List; @SuppressWarnings("unused") public class EntityEventListener implements Listener { + private final PlotAreaManager plotAreaManager; private float lastRadius; - @EventHandler(priority = EventPriority.HIGHEST) - public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { + @Inject public EntityEventListener(@Nonnull final PlotAreaManager plotAreaManager) { + this.plotAreaManager = plotAreaManager; + } + + @EventHandler(priority = EventPriority.HIGHEST) public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { EntityDamageByEntityEvent eventChange = - new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), - EntityDamageEvent.DamageCause.FIRE_TICK, event.getDuration()); + new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), EntityDamageEvent.DamageCause.FIRE_TICK, event.getDuration()); onEntityDamageByEntityEvent(eventChange); if (eventChange.isCancelled()) { event.setCancelled(true); } } - @EventHandler(priority = EventPriority.HIGHEST) - public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { + @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { Entity damager = event.getDamager(); - Location location = BukkitUtil.getLocation(damager); - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + Location location = BukkitUtil.adapt(damager.getLocation()); + if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) { return; } Entity victim = event.getEntity(); @@ -110,10 +115,9 @@ public class EntityEventListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void creatureSpawnEvent(CreatureSpawnEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void creatureSpawnEvent(CreatureSpawnEvent event) { Entity entity = event.getEntity(); - Location location = BukkitUtil.getLocation(entity.getLocation()); + Location location = BukkitUtil.adapt(entity.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -180,18 +184,17 @@ public class EntityEventListener implements Listener { } } - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void onEntityFall(EntityChangeBlockEvent event) { + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onEntityFall(EntityChangeBlockEvent event) { if (event.getEntityType() != EntityType.FALLING_BLOCK) { return; } Block block = event.getBlock(); World world = block.getWorld(); String worldName = world.getName(); - if (!PlotSquared.get().hasPlotArea(worldName)) { + if (!this.plotAreaManager.hasPlotArea(worldName)) { return; } - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -199,9 +202,7 @@ public class EntityEventListener implements Listener { Plot plot = area.getOwnedPlotAbs(location); if (plot == null || plot.getFlag(DisablePhysicsFlag.class)) { event.setCancelled(true); - if (plot != null) { - plot.debug("Falling block event was cancelled because disable-physics = true"); - } + plot.debug("Falling block event was cancelled because disable-physics = true"); return; } if (event.getTo().hasGravity()) { @@ -216,8 +217,7 @@ public class EntityEventListener implements Listener { entity.remove(); } } else if (event.getTo() == Material.AIR) { - event.getEntity() - .setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); + event.getEntity().setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.platform(), plot)); } } @@ -225,7 +225,7 @@ public class EntityEventListener implements Listener { if (event.getEntityType() != EntityType.PLAYER) { return; } - Location location = BukkitUtil.getLocation(event.getEntity()); + Location location = BukkitUtil.adapt(event.getEntity().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -238,19 +238,17 @@ public class EntityEventListener implements Listener { return; } if (plot.getFlag(InvincibleFlag.class)) { - plot.debug( - event.getEntity().getName() + " could not take damage because invincible = true"); + plot.debug(event.getEntity().getName() + " could not take damage because invincible = true"); event.setCancelled(true); } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBigBoom(EntityExplodeEvent event) { - Location location = BukkitUtil.getLocation(event.getLocation()); + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBigBoom(EntityExplodeEvent event) { + Location location = BukkitUtil.adapt(event.getLocation()); PlotArea area = location.getPlotArea(); boolean plotArea = location.isPlotArea(); if (!plotArea) { - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) { return; } return; @@ -266,14 +264,11 @@ public class EntityEventListener implements Listener { origin = (Plot) meta.get(0).value(); } if (this.lastRadius != 0) { - List nearby = event.getEntity() - .getNearbyEntities(this.lastRadius, this.lastRadius, this.lastRadius); + List nearby = event.getEntity().getNearbyEntities(this.lastRadius, this.lastRadius, this.lastRadius); for (Entity near : nearby) { - if (near instanceof TNTPrimed || near.getType() - .equals(EntityType.MINECART_TNT)) { + if (near instanceof TNTPrimed || near.getType().equals(EntityType.MINECART_TNT)) { if (!near.hasMetadata("plot")) { - near.setMetadata("plot", - new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); + near.setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.platform(), plot)); } } } @@ -282,9 +277,8 @@ public class EntityEventListener implements Listener { Iterator iterator = event.blockList().iterator(); while (iterator.hasNext()) { Block block = iterator.next(); - location = BukkitUtil.getLocation(block.getLocation()); - if (!area.contains(location.getX(), location.getZ()) || (origin != null - && !origin.equals(area.getOwnedPlot(location)))) { + location = BukkitUtil.adapt(block.getLocation()); + if (!area.contains(location.getX(), location.getZ()) || !origin.equals(area.getOwnedPlot(location))) { iterator.remove(); } } @@ -300,15 +294,13 @@ public class EntityEventListener implements Listener { public void onPeskyMobsChangeTheWorldLikeWTFEvent(EntityChangeBlockEvent event) { Entity e = event.getEntity(); if (!(e instanceof FallingBlock)) { - Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); + Location location = BukkitUtil.adapt(event.getBlock().getLocation()); PlotArea area = location.getPlotArea(); if (area != null) { Plot plot = area.getOwnedPlot(location); if (plot != null && plot.getFlag(MobPlaceFlag.class)) { - return; - } - if (plot != null) { plot.debug(e.getType() + " could not change block because mob-place = false"); + return; } event.setCancelled(true); } @@ -319,10 +311,9 @@ public class EntityEventListener implements Listener { this.lastRadius = event.getRadius() + 1; } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onVehicleCreate(VehicleCreateEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onVehicleCreate(VehicleCreateEvent event) { Vehicle entity = event.getVehicle(); - Location location = BukkitUtil.getLocation(entity); + Location location = BukkitUtil.adapt(entity.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -333,8 +324,7 @@ public class EntityEventListener implements Listener { return; } if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { - entity - .setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); + entity.setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.platform(), plot)); } } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java index df6ca0ec3..24d22e6a0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntitySpawnListener.java @@ -54,8 +54,8 @@ import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; import java.util.List; public class EntitySpawnListener implements Listener { @@ -67,8 +67,7 @@ public class EntitySpawnListener implements Listener { public static void testNether(final Entity entity) { @Nonnull World world = entity.getWorld(); - if (world.getEnvironment() != World.Environment.NETHER - && world.getEnvironment() != World.Environment.THE_END) { + if (world.getEnvironment() != World.Environment.NETHER && world.getEnvironment() != World.Environment.THE_END) { return; } test(entity); @@ -92,8 +91,7 @@ public class EntitySpawnListener implements Listener { List meta = entity.getMetadata(KEY); if (meta.isEmpty()) { if (PlotSquared.get().getPlotAreaManager().hasPlotArea(world.getName())) { - entity.setMetadata(KEY, - new FixedMetadataValue((Plugin) PlotSquared.platform(), entity.getLocation())); + entity.setMetadata(KEY, new FixedMetadataValue((Plugin) PlotSquared.platform(), entity.getLocation())); } } else { org.bukkit.Location origin = (org.bukkit.Location) meta.get(0).value(); @@ -124,8 +122,7 @@ public class EntitySpawnListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void creatureSpawnEvent(EntitySpawnEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void creatureSpawnEvent(EntitySpawnEvent event) { Entity entity = event.getEntity(); Location location = BukkitUtil.adapt(entity.getLocation()); PlotArea area = location.getPlotArea(); @@ -161,8 +158,7 @@ public class EntitySpawnListener implements Listener { } case SHULKER: if (!entity.hasMetadata("shulkerPlot")) { - entity.setMetadata("shulkerPlot", - new FixedMetadataValue((Plugin) PlotSquared.platform(), plot.getId())); + entity.setMetadata("shulkerPlot", new FixedMetadataValue((Plugin) PlotSquared.platform(), plot.getId())); } } } @@ -193,8 +189,7 @@ public class EntitySpawnListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void vehicleMove(VehicleMoveEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void vehicleMove(VehicleMoveEvent event) { testNether(event.getVehicle()); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java index c4d7c6d90..0311638c3 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java @@ -37,6 +37,8 @@ import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.listener.PlayerBlockEventType; import com.plotsquared.core.listener.PlotListener; import com.plotsquared.core.location.Location; +import com.plotsquared.core.player.MetaDataAccess; +import com.plotsquared.core.player.PlayerMetaDataKeys; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; @@ -65,6 +67,8 @@ import com.plotsquared.core.plot.flag.implementations.VehicleUseFlag; import com.plotsquared.core.plot.flag.implementations.VillagerInteractFlag; import com.plotsquared.core.plot.flag.types.BlockTypeWrapper; import com.plotsquared.core.plot.message.PlotMessage; +import com.plotsquared.core.plot.world.PlotAreaManager; +import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.MainUtil; import com.plotsquared.core.util.MathMan; import com.plotsquared.core.util.Permissions; @@ -72,6 +76,8 @@ import com.plotsquared.core.util.PremiumVerification; import com.plotsquared.core.util.RegExUtil; import com.plotsquared.core.util.entity.EntityCategories; import com.plotsquared.core.util.task.TaskManager; +import com.plotsquared.core.util.task.TaskTime; +import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.world.block.BlockType; import io.papermc.lib.PaperLib; @@ -133,6 +139,8 @@ import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; +import javax.annotation.Nonnull; +import javax.inject.Inject; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashSet; @@ -147,6 +155,9 @@ import java.util.regex.Pattern; @SuppressWarnings("unused") public class PlayerEventListener extends PlotListener implements Listener { + private final EventDispatcher eventDispatcher; + private final WorldEdit worldEdit; + private final PlotAreaManager plotAreaManager; // To prevent recursion private boolean tmpTeleport = true; private Field fieldPlayer; @@ -162,12 +173,21 @@ public class PlayerEventListener extends PlotListener implements Listener { } } + @Inject public PlayerEventListener(@Nonnull final PlotAreaManager plotAreaManager, + @Nonnull final EventDispatcher eventDispatcher, + @Nonnull final WorldEdit worldEdit) { + super(eventDispatcher); + this.eventDispatcher = eventDispatcher; + this.worldEdit = worldEdit; + this.plotAreaManager = plotAreaManager; + } + @EventHandler public void onVehicleEntityCollision(VehicleEntityCollisionEvent e) { if (e.getVehicle().getType() == EntityType.BOAT) { - Location location = BukkitUtil.getLocation(e.getEntity()); + Location location = BukkitUtil.adapt(e.getEntity().getLocation()); if (location.isPlotArea()) { if (e.getEntity() instanceof Player) { - PlotPlayer player = BukkitUtil.getPlayer((Player) e.getEntity()); + PlotPlayer player = BukkitUtil.adapt((Player) e.getEntity()); Plot plot = player.getCurrentPlot(); if (plot != null) { if (!plot.isAdded(player.getUUID())) { @@ -187,14 +207,13 @@ public class PlayerEventListener extends PlotListener implements Listener { } } - @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) - public void playerCommand(PlayerCommandPreprocessEvent event) { + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void playerCommand(PlayerCommandPreprocessEvent event) { String msg = event.getMessage().toLowerCase().replaceAll("/", "").trim(); if (msg.isEmpty()) { return; } Player player = event.getPlayer(); - PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); + PlotPlayer plotPlayer = BukkitUtil.adapt(player); Location location = plotPlayer.getLocation(); PlotArea area = location.getPlotArea(); if (area == null) { @@ -218,11 +237,8 @@ public class PlayerEventListener extends PlotListener implements Listener { return; } - List blockedCommands = plot != null ? - plot.getFlag(BlockedCmdsFlag.class) : - area.getFlag(BlockedCmdsFlag.class); - if (!blockedCommands.isEmpty() && !Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { + List blockedCommands = plot != null ? plot.getFlag(BlockedCmdsFlag.class) : area.getFlag(BlockedCmdsFlag.class); + if (!blockedCommands.isEmpty() && !Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { String part = parts[0]; if (parts[0].contains(":")) { part = parts[0].split(":")[1]; @@ -280,16 +296,13 @@ public class PlayerEventListener extends PlotListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPreLoin(final AsyncPlayerPreLoginEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPreLogin(final AsyncPlayerPreLoginEvent event) { final UUID uuid; if (Settings.UUID.OFFLINE) { if (Settings.UUID.FORCE_LOWERCASE) { - uuid = UUID.nameUUIDFromBytes( - ("OfflinePlayer:" + event.getName().toLowerCase()).getBytes(Charsets.UTF_8)); + uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + event.getName().toLowerCase()).getBytes(Charsets.UTF_8)); } else { - uuid = UUID.nameUUIDFromBytes( - ("OfflinePlayer:" + event.getName()).getBytes(Charsets.UTF_8)); + uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + event.getName()).getBytes(Charsets.UTF_8)); } } else { uuid = event.getUniqueId(); @@ -297,11 +310,10 @@ public class PlayerEventListener extends PlotListener implements Listener { PlotSquared.get().getImpromptuUUIDPipeline().storeImmediately(event.getName(), uuid); } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onConnect(PlayerJoinEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onConnect(PlayerJoinEvent event) { final Player player = event.getPlayer(); - BukkitUtil.removePlayer(player.getUniqueId()); - final PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotSquared.platform().getPlayerManager().removePlayer(player.getUniqueId()); + final PlotPlayer pp = BukkitUtil.adapt(player); Location location = pp.getLocation(); PlotArea area = location.getPlotArea(); @@ -318,76 +330,72 @@ public class PlayerEventListener extends PlotListener implements Listener { if (!player.hasPlayedBefore() && player.isOnline()) { player.saveData(); } - PlotSquared.get().getEventDispatcher().doJoinTask(pp); - }, 20); + this.eventDispatcher.doJoinTask(pp); + }, TaskTime.seconds(1L)); - if (pp.hasPermission(Captions.PERMISSION_ADMIN_UPDATE_NOTIFICATION.getTranslated()) - && Settings.Enabled_Components.UPDATE_NOTIFICATIONS && PremiumVerification.isPremium() - && UpdateUtility.hasUpdate) { + if (pp.hasPermission(Captions.PERMISSION_ADMIN_UPDATE_NOTIFICATION.getTranslated()) && Settings.Enabled_Components.UPDATE_NOTIFICATIONS + && PremiumVerification.isPremium() && UpdateUtility.hasUpdate) { new PlotMessage("-----------------------------------").send(pp); - new PlotMessage(Captions.PREFIX + "There appears to be a PlotSquared update available!") - .color("$1").send(pp); - new PlotMessage( - Captions.PREFIX + "&6You are running version " + UpdateUtility.internalVersion - .versionString() + ", &6latest version is " + UpdateUtility.spigotVersion) - .color("$1").send(pp); + new PlotMessage(Captions.PREFIX + "There appears to be a PlotSquared update available!").color("$1").send(pp); + new PlotMessage(Captions.PREFIX + "&6You are running version " + UpdateUtility.internalVersion.versionString() + ", &6latest version is " + + UpdateUtility.spigotVersion).color("$1").send(pp); new PlotMessage(Captions.PREFIX + "Download at:").color("$1").send(pp); player.sendMessage(" https://www.spigotmc.org/resources/77506/updates"); new PlotMessage("-----------------------------------").send(pp); } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void playerRespawn(PlayerRespawnEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void playerRespawn(PlayerRespawnEvent event) { Player player = event.getPlayer(); - PlotPlayer pp = BukkitUtil.getPlayer(player); - PlotSquared.get().getEventDispatcher().doRespawnTask(pp); + PlotPlayer pp = BukkitUtil.adapt(player); + this.eventDispatcher.doRespawnTask(pp); } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onTeleport(PlayerTeleportEvent event) { Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); - Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); - org.bukkit.Location to = event.getTo(); - //noinspection ConstantConditions - if (to != null) { - Location location = BukkitUtil.getLocation(to); - PlotArea area = location.getPlotArea(); - if (area == null) { - if (lastPlot != null) { - plotExit(pp, lastPlot); - pp.deleteMeta(PlotPlayer.META_LAST_PLOT); + BukkitPlayer pp = BukkitUtil.adapt(player); + try (final MetaDataAccess lastPlotAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + Plot lastPlot = lastPlotAccess.get().orElse(null); + org.bukkit.Location to = event.getTo(); + //noinspection ConstantConditions + if (to != null) { + Location location = BukkitUtil.adapt(to); + PlotArea area = location.getPlotArea(); + if (area == null) { + if (lastPlot != null) { + plotExit(pp, lastPlot); + lastPlotAccess.remove(); + } + try (final MetaDataAccess lastLocationAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LOCATION)) { + lastLocationAccess.remove(); + } + return; } - pp.deleteMeta(PlotPlayer.META_LOCATION); - return; - } - Plot plot = area.getPlot(location); - if (plot != null) { - final boolean result = DenyTeleportFlag.allowsTeleport(pp, plot); - // there is one possibility to still allow teleportation: - // to is identical to the plot's home location, and untrusted-visit is true - // i.e. untrusted-visit can override deny-teleport - // this is acceptable, because otherwise it wouldn't make sense to have both flags set - if (!result && !(plot.getFlag(UntrustedVisitFlag.class) && plot.getHomeSynchronous() - .equals(BukkitUtil.getLocationFull(to)))) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_ENTRY_DENIED); - event.setCancelled(true); + Plot plot = area.getPlot(location); + if (plot != null) { + final boolean result = DenyTeleportFlag.allowsTeleport(pp, plot); + // there is one possibility to still allow teleportation: + // to is identical to the plot's home location, and untrusted-visit is true + // i.e. untrusted-visit can override deny-teleport + // this is acceptable, because otherwise it wouldn't make sense to have both flags set + if (!result && !(plot.getFlag(UntrustedVisitFlag.class) && plot.getHomeSynchronous().equals(BukkitUtil.adaptComplete(to)))) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_ENTRY_DENIED); + event.setCancelled(true); + } } } } playerMove(event); } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void vehicleMove(VehicleMoveEvent event) + throws IllegalAccessException { final org.bukkit.Location from = event.getFrom(); final org.bukkit.Location to = event.getTo(); int toX, toZ; - if ((toX = MathMan.roundInt(to.getX())) != MathMan.roundInt(from.getX()) - | (toZ = MathMan.roundInt(to.getZ())) != MathMan.roundInt(from.getZ())) { + if ((toX = MathMan.roundInt(to.getX())) != MathMan.roundInt(from.getX()) | (toZ = MathMan.roundInt(to.getZ())) != MathMan + .roundInt(from.getZ())) { Vehicle vehicle = event.getVehicle(); // Check allowed @@ -411,8 +419,7 @@ public class PlayerEventListener extends PlotListener implements Listener { org.bukkit.Location dest; if (moveTmp.isCancelled()) { dest = from; - } else if (MathMan.roundInt(moveTmp.getTo().getX()) != toX - || MathMan.roundInt(moveTmp.getTo().getZ()) != toZ) { + } else if (MathMan.roundInt(moveTmp.getTo().getX()) != toX || MathMan.roundInt(moveTmp.getTo().getZ()) != toZ) { dest = to; } else { dest = null; @@ -426,22 +433,19 @@ public class PlayerEventListener extends PlotListener implements Listener { } } if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { - final com.sk89q.worldedit.world.entity.EntityType entityType = - BukkitAdapter.adapt(vehicle.getType()); + final com.sk89q.worldedit.world.entity.EntityType entityType = BukkitAdapter.adapt(vehicle.getType()); // Horses etc are vehicles, but they're also animals // so this filters out all living entities - if (EntityCategories.VEHICLE.contains(entityType) && !EntityCategories.ANIMAL - .contains(entityType)) { + if (EntityCategories.VEHICLE.contains(entityType) && !EntityCategories.ANIMAL.contains(entityType)) { List meta = vehicle.getMetadata("plot"); - Plot toPlot = BukkitUtil.getLocation(to).getPlot(); + Plot toPlot = BukkitUtil.adapt(to).getPlot(); if (!meta.isEmpty()) { Plot origin = (Plot) meta.get(0).value(); if (origin != null && !origin.getBasePlot(false).equals(toPlot)) { vehicle.remove(); } } else if (toPlot != null) { - vehicle.setMetadata("plot", - new FixedMetadataValue((Plugin) PlotSquared.get().IMP, toPlot)); + vehicle.setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.platform(), toPlot)); } } } @@ -450,48 +454,53 @@ public class PlayerEventListener extends PlotListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void playerMove(PlayerMoveEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void playerMove(PlayerMoveEvent event) { org.bukkit.Location from = event.getFrom(); org.bukkit.Location to = event.getTo(); int x2; if (MathMan.roundInt(from.getX()) != (x2 = MathMan.roundInt(to.getX()))) { Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); + BukkitPlayer pp = BukkitUtil.adapt(player); // Cancel teleport - if (TaskManager.TELEPORT_QUEUE.remove(pp.getName())) { + if (TaskManager.removeFromTeleportQueue(pp.getName())) { MainUtil.sendMessage(pp, Captions.TELEPORT_FAILED); } // Set last location - Location location = BukkitUtil.getLocation(to); - pp.setMeta(PlotPlayer.META_LOCATION, location); + Location location = BukkitUtil.adapt(to); + try (final MetaDataAccess lastLocationAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LOCATION)) { + lastLocationAccess.remove(); + } PlotArea area = location.getPlotArea(); if (area == null) { - pp.deleteMeta(PlotPlayer.META_LAST_PLOT); + try (final MetaDataAccess lastPlotAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + lastPlotAccess.remove(); + } return; } Plot now = area.getPlot(location); - Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); + Plot lastPlot; + try (final MetaDataAccess lastPlotAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + lastPlot = lastPlotAccess.get().orElse(null); + } if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp - .getMeta("kick", false)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_EXIT_DENIED); - this.tmpTeleport = false; - if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { - player.teleport(from); - } else { - player.teleport(player.getWorld().getSpawnLocation()); + try (final MetaDataAccess kickAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_KICK)) { + if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !kickAccess.get().orElse(false)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_EXIT_DENIED); + this.tmpTeleport = false; + if (lastPlot.equals(BukkitUtil.adapt(from).getPlot())) { + player.teleport(from); + } else { + player.teleport(player.getWorld().getSpawnLocation()); + } + this.tmpTeleport = true; + event.setCancelled(true); + return; } - this.tmpTeleport = true; - event.setCancelled(true); - return; } } else if (now.equals(lastPlot)) { ForceFieldListener.handleForcefield(player, pp, now); } else if (!plotEntry(pp, now) && this.tmpTeleport) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_ENTRY_DENIED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_ENTRY_DENIED); this.tmpTeleport = false; to.setX(from.getBlockX()); to.setY(from.getBlockY()); @@ -519,41 +528,47 @@ public class PlayerEventListener extends PlotListener implements Listener { int z2; if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) { Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); + BukkitPlayer pp = BukkitUtil.adapt(player); // Cancel teleport - if (TaskManager.TELEPORT_QUEUE.remove(pp.getName())) { + if (TaskManager.removeFromTeleportQueue(pp.getName())) { MainUtil.sendMessage(pp, Captions.TELEPORT_FAILED); } // Set last location - Location location = BukkitUtil.getLocation(to); - pp.setMeta(PlotPlayer.META_LOCATION, location); + Location location = BukkitUtil.adapt(to); + try (final MetaDataAccess lastLocationAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LOCATION)) { + lastLocationAccess.set(location); + } PlotArea area = location.getPlotArea(); if (area == null) { - pp.deleteMeta(PlotPlayer.META_LAST_PLOT); + try (final MetaDataAccess lastPlotAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + lastPlotAccess.remove(); + } return; } Plot now = area.getPlot(location); - Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); + Plot lastPlot; + try (final MetaDataAccess lastPlotAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + lastPlot = lastPlotAccess.get().orElse(null); + } if (now == null) { - if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp - .getMeta("kick", false)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_EXIT_DENIED); - this.tmpTeleport = false; - if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { - player.teleport(from); - } else { - player.teleport(player.getWorld().getSpawnLocation()); + try (final MetaDataAccess kickAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_KICK)) { + if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !kickAccess.get().orElse(false)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_EXIT_DENIED); + this.tmpTeleport = false; + if (lastPlot.equals(BukkitUtil.adapt(from).getPlot())) { + player.teleport(from); + } else { + player.teleport(player.getWorld().getSpawnLocation()); + } + this.tmpTeleport = true; + event.setCancelled(true); + return; } - this.tmpTeleport = true; - event.setCancelled(true); - return; } } else if (now.equals(lastPlot)) { ForceFieldListener.handleForcefield(player, pp, now); } else if (!plotEntry(pp, now) && this.tmpTeleport) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_ENTRY_DENIED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_ENTRY_DENIED); this.tmpTeleport = false; player.teleport(from); to.setX(from.getBlockX()); @@ -585,7 +600,7 @@ public class PlayerEventListener extends PlotListener implements Listener { return; } - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(event.getPlayer()); + BukkitPlayer plotPlayer = BukkitUtil.adapt(event.getPlayer()); Location location = plotPlayer.getLocation(); PlotArea area = location.getPlotArea(); if (area == null) { @@ -595,12 +610,10 @@ public class PlayerEventListener extends PlotListener implements Listener { if (plot == null) { return; } - if (!((plot.getFlag(ChatFlag.class) && area.isPlotChat() && plotPlayer.getAttribute("chat")) - || area.isForcingPlotChat())) { + if (!((plot.getFlag(ChatFlag.class) && area.isPlotChat() && plotPlayer.getAttribute("chat")) || area.isForcingPlotChat())) { return; } - if (plot.isDenied(plotPlayer.getUUID()) && !Permissions - .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_CHAT_BYPASS)) { + if (plot.isDenied(plotPlayer.getUUID()) && !Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_CHAT_BYPASS)) { return; } event.setCancelled(true); @@ -611,7 +624,7 @@ public class PlayerEventListener extends PlotListener implements Listener { Set recipients = event.getRecipients(); recipients.clear(); Set spies = new HashSet<>(); - for (final PlotPlayer pp : PlotSquared.imp().getPlayerManager().getPlayers()) { + for (final PlotPlayer pp : PlotSquared.platform().getPlayerManager().getPlayers()) { if (pp.getAttribute("chatspy")) { spies.add(((BukkitPlayer) pp).player); } else { @@ -621,8 +634,8 @@ public class PlayerEventListener extends PlotListener implements Listener { } } } - String partial = ChatColor.translateAlternateColorCodes('&', - format.replace("%plot_id%", id.getX() + ";" + id.getY()).replace("%sender%", sender)); + String partial = + ChatColor.translateAlternateColorCodes('&', format.replace("%plot_id%", id.getX() + ";" + id.getY()).replace("%sender%", sender)); if (plotPlayer.hasPermission("plots.chat.color")) { message = Captions.color(message); } @@ -631,36 +644,38 @@ public class PlayerEventListener extends PlotListener implements Listener { receiver.sendMessage(full); } if (!spies.isEmpty()) { - String spyMessage = Captions.PLOT_CHAT_SPY_FORMAT.getTranslated() - .replace("%plot_id%", id.getX() + ";" + id.getY()).replace("%sender%", sender) - .replace("%msg%", message); + String spyMessage = + Captions.PLOT_CHAT_SPY_FORMAT.getTranslated().replace("%plot_id%", id.getX() + ";" + id.getY()).replace("%sender%", sender) + .replace("%msg%", message); for (Player player : spies) { player.sendMessage(spyMessage); } } - PlotSquared.debug(full); + // TODO: Re-implement + // PlotSquared.debug(full); } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onWorldChanged(PlayerChangedWorldEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onWorldChanged(PlayerChangedWorldEvent event) { Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); + BukkitPlayer pp = BukkitUtil.adapt(player); // Delete last location - Plot plot = (Plot) pp.deleteMeta(PlotPlayer.META_LAST_PLOT); - pp.deleteMeta(PlotPlayer.META_LOCATION); + Plot plot; + try (final MetaDataAccess lastPlotAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LAST_PLOT)) { + plot = lastPlotAccess.remove(); + } + try (final MetaDataAccess lastLocationAccess = pp.accessTemporaryMetaData(PlayerMetaDataKeys.TEMPORARY_LOCATION)) { + lastLocationAccess.remove(); + } if (plot != null) { plotExit(pp, plot); } - if (PlotSquared.get().worldedit != null) { + if (this.worldEdit != null) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_WORLDEDIT_BYPASS)) { if (pp.getAttribute("worldedit")) { pp.removeAttribute("worldedit"); } } } - if (Settings.Enabled_Components.PERMISSION_CACHE) { - pp.deleteMeta("perm"); - } Location location = pp.getLocation(); PlotArea area = location.getPlotArea(); if (location.isPlotArea()) { @@ -671,16 +686,14 @@ public class PlayerEventListener extends PlotListener implements Listener { } } - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + @SuppressWarnings("deprecation") @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) || !PlotSquared.get() - .hasPlotArea(entity.getWorld().getName())) { + if (!(entity instanceof Player) || !this.plotAreaManager.hasPlotArea(entity.getWorld().getName())) { return; } @@ -689,7 +702,7 @@ public class PlayerEventListener extends PlotListener implements Listener { return; } Player player = (Player) clicker; - BukkitPlayer pp = BukkitUtil.getPlayer(player); + BukkitPlayer pp = BukkitUtil.adapt(player); final PlotInventory inventory = PlotInventory.getOpenPlotInventory(pp); if (inventory != null && event.getRawSlot() == event.getSlot()) { if (!inventory.onClick(event.getSlot())) { @@ -705,30 +718,22 @@ public class PlayerEventListener extends PlotListener implements Listener { } ItemStack current = inv.getItemInHand(); ItemStack newItem = event.getCursor(); - if (newItem == null) { - return; - } ItemMeta newMeta = newItem.getItemMeta(); ItemMeta oldMeta = newItem.getItemMeta(); if (event.getClick() == ClickType.CREATIVE) { final Plot plot = pp.getCurrentPlot(); if (plot != null) { - if (plot.getFlag(PreventCreativeCopyFlag.class) && !plot - .isAdded(player.getUniqueId()) && !Permissions + if (plot.getFlag(PreventCreativeCopyFlag.class) && !plot.isAdded(player.getUniqueId()) && !Permissions .hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_OTHER)) { - final ItemStack newStack = - new ItemStack(newItem.getType(), newItem.getAmount()); + final ItemStack newStack = new ItemStack(newItem.getType(), newItem.getAmount()); event.setCursor(newStack); - plot.debug(player.getName() - + " could not creative-copy an item because prevent-creative-copy = true"); + plot.debug(player.getName() + " could not creative-copy an item because prevent-creative-copy = true"); } } else { PlotArea area = pp.getPlotAreaAbs(); - if (area != null && area.isRoadFlags() && area - .getRoadFlag(PreventCreativeCopyFlag.class)) { - final ItemStack newStack = - new ItemStack(newItem.getType(), newItem.getAmount()); + if (area != null && area.isRoadFlags() && area.getRoadFlag(PreventCreativeCopyFlag.class)) { + final ItemStack newStack = new ItemStack(newItem.getType(), newItem.getAmount()); event.setCursor(newStack); } } @@ -779,7 +784,7 @@ public class PlayerEventListener extends PlotListener implements Listener { return; } } - Location location = BukkitUtil.getLocation(state.getLocation()); + Location location = BukkitUtil.adapt(state.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -793,66 +798,57 @@ public class PlayerEventListener extends PlotListener implements Listener { } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { - MainUtil - .sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); cancelled = true; } } else { UUID uuid = pp.getUUID(); if (!plot.isAdded(uuid)) { if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.interact.other"); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.other"); cancelled = true; } } } if (cancelled) { - if ((current.getType() == newItem.getType()) && (current.getDurability() == newItem - .getDurability())) { - event.setCursor( - new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); + if ((current.getType() == newItem.getType()) && (current.getDurability() == newItem.getDurability())) { + event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); event.setCancelled(true); return; } - event.setCursor( - new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); + event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onInteract(PlayerInteractAtEntityEvent e) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onInteract(PlayerInteractAtEntityEvent e) { Entity entity = e.getRightClicked(); if (!(entity instanceof ArmorStand) && !(entity instanceof ItemFrame)) { return; } - Location location = BukkitUtil.getLocation(e.getRightClicked().getLocation()); + Location location = BukkitUtil.adapt(e.getRightClicked().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; } EntitySpawnListener.testNether(entity); Plot plot = location.getPlotAbs(); - BukkitPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); + BukkitPlayer pp = BukkitUtil.adapt(e.getPlayer()); if (plot == null) { - if (!area.isRoadFlags() && !area.getRoadFlag(MiscInteractFlag.class) && !Permissions - .hasPermission(pp, "plots.admin.interact.road")) { + if (!area.isRoadFlags() && !area.getRoadFlag(MiscInteractFlag.class) && !Permissions.hasPermission(pp, "plots.admin.interact.road")) { MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.road"); e.setCancelled(true); } } else { if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); e.setCancelled(true); return; } } if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.interact.unowned"); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); e.setCancelled(true); } } else { @@ -864,21 +860,18 @@ public class PlayerEventListener extends PlotListener implements Listener { return; } if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.interact.other"); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.other"); e.setCancelled(true); - plot.debug(pp.getName() + " could not interact with " + entity.getType() - + " bcause misc-interact = false"); + plot.debug(pp.getName() + " could not interact with " + entity.getType() + " bcause misc-interact = false"); } } } } - @EventHandler(priority = EventPriority.LOW) - public void onCancelledInteract(PlayerInteractEvent event) { + @EventHandler(priority = EventPriority.LOW) public void onCancelledInteract(PlayerInteractEvent event) { if (event.isCancelled() && event.getAction() == Action.RIGHT_CLICK_AIR) { Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); + BukkitPlayer pp = BukkitUtil.adapt(player); PlotArea area = pp.getPlotAreaAbs(); if (area == null) { return; @@ -900,10 +893,8 @@ public class PlayerEventListener extends PlotListener implements Listener { if (type.toString().toLowerCase().endsWith("_egg")) { Block block = player.getTargetBlockExact(5, FluidCollisionMode.SOURCE_ONLY); if (block != null && block.getType() != Material.AIR) { - Location location = BukkitUtil.getLocation(block.getLocation()); - if (!PlotSquared.get().getEventDispatcher() - .checkPlayerBlockEvent(pp, PlayerBlockEventType.SPAWN_MOB, location, null, - true)) { + Location location = BukkitUtil.adapt(block.getLocation()); + if (!this.eventDispatcher.checkPlayerBlockEvent(pp, PlayerBlockEventType.SPAWN_MOB, location, null, true)) { event.setCancelled(true); event.setUseItemInHand(Event.Result.DENY); } @@ -912,10 +903,9 @@ public class PlayerEventListener extends PlotListener implements Listener { } } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onInteract(PlayerInteractEvent event) { + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); + BukkitPlayer pp = BukkitUtil.adapt(player); PlotArea area = pp.getPlotAreaAbs(); if (area == null) { return; @@ -923,10 +913,7 @@ public class PlayerEventListener extends PlotListener implements Listener { PlayerBlockEventType eventType = null; BlockType blocktype1; Block block = event.getClickedBlock(); - if (block == null) { - return; - } - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); Action action = event.getAction(); outer: switch (action) { @@ -976,12 +963,12 @@ public class PlayerEventListener extends PlotListener implements Listener { if (PaperLib.isPaper()) { if (MaterialTags.SPAWN_EGGS.isTagged(type) || Material.EGG.equals(type)) { eventType = PlayerBlockEventType.SPAWN_MOB; - break; + break outer; } } else { if (type.toString().toLowerCase().endsWith("egg")) { eventType = PlayerBlockEventType.SPAWN_MOB; - break; + break outer; } } if (type.isEdible()) { @@ -1014,15 +1001,14 @@ public class PlayerEventListener extends PlotListener implements Listener { eventType = PlayerBlockEventType.READ; break outer; case ARMOR_STAND: - location = BukkitUtil - .getLocation(block.getRelative(event.getBlockFace()).getLocation()); + location = BukkitUtil.adapt(block.getRelative(event.getBlockFace()).getLocation()); eventType = PlayerBlockEventType.PLACE_MISC; break outer; } break; } case LEFT_CLICK_BLOCK: { - location = BukkitUtil.getLocation(block.getLocation()); + location = BukkitUtil.adapt(block.getLocation()); //eventType = PlayerBlockEventType.BREAK_BLOCK; blocktype1 = BukkitAdapter.asBlockType(block.getType()); if (block.getType() == Material.DRAGON_EGG) { @@ -1035,45 +1021,38 @@ public class PlayerEventListener extends PlotListener implements Listener { default: return; } - if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) { - if (event.getMaterial() == Material - .getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) { + if (this.worldEdit != null && pp.getAttribute("worldedit")) { + if (event.getMaterial() == Material.getMaterial(this.worldEdit.getConfiguration().wandItem)) { return; } } - if (!PlotSquared.get().getEventDispatcher() - .checkPlayerBlockEvent(pp, eventType, location, blocktype1, true)) { + if (!this.eventDispatcher.checkPlayerBlockEvent(pp, eventType, location, blocktype1, true)) { event.setCancelled(true); event.setUseInteractedBlock(Event.Result.DENY); } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBucketEmpty(PlayerBucketEmptyEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBucketEmpty(PlayerBucketEmptyEvent event) { BlockFace bf = event.getBlockFace(); - Block block = - event.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()) - .getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); + Block block = event.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); + Location location = BukkitUtil.adapt(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; } - BukkitPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); + BukkitPlayer pp = BukkitUtil.adapt(event.getPlayer()); Plot plot = area.getPlot(location); if (plot == null) { if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { return; } - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_ROAD); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_ROAD); event.setCancelled(true); } else if (!plot.hasOwner()) { if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { return; } - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } else if (!plot.isAdded(pp.getUUID())) { List use = plot.getFlag(UseFlag.class); @@ -1086,59 +1065,53 @@ public class PlayerEventListener extends PlotListener implements Listener { if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { return; } - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } } } - @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClose(InventoryCloseEvent event) { + @EventHandler(priority = EventPriority.HIGHEST) public void onInventoryClose(InventoryCloseEvent event) { HumanEntity closer = event.getPlayer(); if (!(closer instanceof Player)) { return; } Player player = (Player) closer; - PlotInventory.removePlotInventoryOpen(BukkitUtil.getPlayer(player)); + PlotInventory.removePlotInventoryOpen(BukkitUtil.adapt(player)); } @EventHandler(priority = EventPriority.MONITOR) public void onLeave(PlayerQuitEvent event) { - TaskManager.TELEPORT_QUEUE.remove(event.getPlayer().getName()); - BukkitPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); + TaskManager.removeFromTeleportQueue(event.getPlayer().getName()); + BukkitPlayer pp = BukkitUtil.adapt(event.getPlayer()); pp.unregister(); - PlotListener.logout(pp.getUUID()); + this.logout(pp.getUUID()); } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBucketFill(PlayerBucketFillEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBucketFill(PlayerBucketFillEvent event) { Block blockClicked = event.getBlockClicked(); - Location location = BukkitUtil.getLocation(blockClicked.getLocation()); + Location location = BukkitUtil.adapt(blockClicked.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; } Player player = event.getPlayer(); - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + BukkitPlayer plotPlayer = BukkitUtil.adapt(player); Plot plot = area.getPlot(location); if (plot == null) { if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { return; } - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_ROAD); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_ROAD); event.setCancelled(true); } else if (!plot.hasOwner()) { if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { return; } - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } else if (!plot.isAdded(plotPlayer.getUUID())) { List use = plot.getFlag(UseFlag.class); @@ -1152,45 +1125,39 @@ public class PlayerEventListener extends PlotListener implements Listener { if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { return; } - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } else if (Settings.Done.RESTRICT_BUILDING && DoneFlag.isDone(plot)) { if (!Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onHangingPlace(HangingPlaceEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onHangingPlace(HangingPlaceEvent event) { Block block = event.getBlock().getRelative(event.getBlockFace()); - Location location = BukkitUtil.getLocation(block.getLocation()); + Location location = BukkitUtil.adapt(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; } Player p = event.getPlayer(); if (p == null) { - PlotSquared.debug("PlotSquared does not support HangingPlaceEvent for non-players."); event.setCancelled(true); return; } - BukkitPlayer pp = BukkitUtil.getPlayer(p); + BukkitPlayer pp = BukkitUtil.adapt(p); Plot plot = area.getPlot(location); if (plot == null) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_ROAD); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_ROAD); event.setCancelled(true); } } else { if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } return; @@ -1198,8 +1165,7 @@ public class PlayerEventListener extends PlotListener implements Listener { if (!plot.isAdded(pp.getUUID())) { if (!plot.getFlag(HangingPlaceFlag.class)) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } return; @@ -1212,28 +1178,25 @@ public class PlayerEventListener extends PlotListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onHangingBreakByEntity(HangingBreakByEntityEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onHangingBreakByEntity(HangingBreakByEntityEvent event) { Entity remover = event.getRemover(); if (remover instanceof Player) { Player p = (Player) remover; - Location location = BukkitUtil.getLocation(event.getEntity()); + Location location = BukkitUtil.adapt(event.getEntity().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; } - BukkitPlayer pp = BukkitUtil.getPlayer(p); + BukkitPlayer pp = BukkitUtil.adapt(p); Plot plot = area.getPlot(location); if (plot == null) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_ROAD); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_ROAD); event.setCancelled(true); } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_UNOWNED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(pp.getUUID())) { @@ -1241,41 +1204,34 @@ public class PlayerEventListener extends PlotListener implements Listener { return; } if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_OTHER); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_OTHER); event.setCancelled(true); - plot.debug(p.getName() - + " could not break hanging entity because hanging-break = false"); + plot.debug(p.getName() + " could not break hanging entity because hanging-break = false"); } } } else if (remover instanceof Projectile) { Projectile p = (Projectile) remover; if (p.getShooter() instanceof Player) { Player shooter = (Player) p.getShooter(); - Location location = BukkitUtil.getLocation(event.getEntity()); + Location location = BukkitUtil.adapt(event.getEntity().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; } - BukkitPlayer player = BukkitUtil.getPlayer(shooter); - Plot plot = area.getPlot(BukkitUtil.getLocation(event.getEntity())); + BukkitPlayer player = BukkitUtil.adapt(shooter); + Plot plot = area.getPlot(BukkitUtil.adapt(event.getEntity().getLocation())); if (plot != null) { if (!plot.hasOwner()) { - if (!Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_UNOWNED); + if (!Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(player.getUUID())) { if (!plot.getFlag(HangingBreakFlag.class)) { - if (!Permissions - .hasPermission(player, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_DESTROY_OTHER); + if (!Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_OTHER); event.setCancelled(true); - plot.debug(player.getName() - + " could not break hanging entity because hanging-break = false"); + plot.debug(player.getName() + " could not break hanging entity because hanging-break = false"); } } } @@ -1286,33 +1242,28 @@ public class PlayerEventListener extends PlotListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { - Location location = BukkitUtil.getLocation(event.getRightClicked().getLocation()); + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { + Location location = BukkitUtil.adapt(event.getRightClicked().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; } Player p = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(p); + BukkitPlayer pp = BukkitUtil.adapt(p); Plot plot = area.getPlot(location); if (plot == null && !area.isRoadFlags()) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_ROAD)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_INTERACT_ROAD); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_INTERACT_ROAD); event.setCancelled(true); } } else if (plot != null && !plot.hasOwner()) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_INTERACT_UNOWNED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED); event.setCancelled(true); } - } else if ((plot != null && !plot.isAdded(pp.getUUID())) || (plot == null && area - .isRoadFlags())) { + } else if ((plot != null && !plot.isAdded(pp.getUUID())) || (plot == null && area.isRoadFlags())) { final Entity entity = event.getRightClicked(); - final com.sk89q.worldedit.world.entity.EntityType entityType = - BukkitAdapter.adapt(entity.getType()); + final com.sk89q.worldedit.world.entity.EntityType entityType = BukkitAdapter.adapt(entity.getType()); FlagContainer flagContainer; if (plot == null) { @@ -1321,55 +1272,46 @@ public class PlayerEventListener extends PlotListener implements Listener { flagContainer = plot.getFlagContainer(); } - if (EntityCategories.HOSTILE.contains(entityType) && flagContainer - .getFlag(HostileInteractFlag.class).getValue()) { + if (EntityCategories.HOSTILE.contains(entityType) && flagContainer.getFlag(HostileInteractFlag.class).getValue()) { return; } - if (EntityCategories.ANIMAL.contains(entityType) && flagContainer - .getFlag(AnimalInteractFlag.class).getValue()) { + if (EntityCategories.ANIMAL.contains(entityType) && flagContainer.getFlag(AnimalInteractFlag.class).getValue()) { return; } // This actually makes use of the interface, so we don't use the // category - if (entity instanceof Tameable && ((Tameable) entity).isTamed() && flagContainer - .getFlag(TamedInteractFlag.class).getValue()) { + if (entity instanceof Tameable && ((Tameable) entity).isTamed() && flagContainer.getFlag(TamedInteractFlag.class).getValue()) { return; } - if (EntityCategories.VEHICLE.contains(entityType) && flagContainer - .getFlag(VehicleUseFlag.class).getValue()) { + if (EntityCategories.VEHICLE.contains(entityType) && flagContainer.getFlag(VehicleUseFlag.class).getValue()) { return; } - if (EntityCategories.PLAYER.contains(entityType) && flagContainer - .getFlag(PlayerInteractFlag.class).getValue()) { + if (EntityCategories.PLAYER.contains(entityType) && flagContainer.getFlag(PlayerInteractFlag.class).getValue()) { return; } - if (EntityCategories.VILLAGER.contains(entityType) && flagContainer - .getFlag(VillagerInteractFlag.class).getValue()) { + if (EntityCategories.VILLAGER.contains(entityType) && flagContainer.getFlag(VillagerInteractFlag.class).getValue()) { return; } - if ((EntityCategories.HANGING.contains(entityType) || EntityCategories.OTHER - .contains(entityType)) && flagContainer.getFlag(MiscInteractFlag.class) - .getValue()) { + if ((EntityCategories.HANGING.contains(entityType) || EntityCategories.OTHER.contains(entityType)) && flagContainer + .getFlag(MiscInteractFlag.class).getValue()) { return; } if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_OTHER)) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - Captions.PERMISSION_ADMIN_INTERACT_OTHER); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_INTERACT_OTHER); event.setCancelled(true); } } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onVehicleDestroy(VehicleDestroyEvent event) { - Location location = BukkitUtil.getLocation(event.getVehicle()); + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onVehicleDestroy(VehicleDestroyEvent event) { + Location location = BukkitUtil.adapt(event.getVehicle().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -1377,19 +1319,17 @@ public class PlayerEventListener extends PlotListener implements Listener { Entity attacker = event.getAttacker(); if (attacker instanceof Player) { Player p = (Player) attacker; - BukkitPlayer pp = BukkitUtil.getPlayer(p); + BukkitPlayer pp = BukkitUtil.adapt(p); Plot plot = area.getPlot(location); if (plot == null) { if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.road")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.vehicle.break.road"); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.road"); event.setCancelled(true); } } else { if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.unowned")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.vehicle.break.unowned"); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.unowned"); event.setCancelled(true); return; } @@ -1400,43 +1340,37 @@ public class PlayerEventListener extends PlotListener implements Listener { return; } if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.other")) { - MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, - "plots.admin.vehicle.break.other"); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.other"); event.setCancelled(true); - plot.debug(pp.getName() - + " could not break vehicle because vehicle-break = false"); + plot.debug(pp.getName() + " could not break vehicle because vehicle-break = false"); } } } } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerEggThrow(PlayerEggThrowEvent event) { - Location location = BukkitUtil.getLocation(event.getEgg().getLocation()); + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerEggThrow(PlayerEggThrowEvent event) { + Location location = BukkitUtil.adapt(event.getEgg().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; } Player player = event.getPlayer(); - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + BukkitPlayer plotPlayer = BukkitUtil.adapt(player); Plot plot = area.getPlot(location); if (plot == null) { if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.road")) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.projectile.road"); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, "plots.admin.projectile.road"); event.setHatching(false); } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.unowned")) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.projectile.unowned"); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, "plots.admin.projectile.unowned"); event.setHatching(false); } } else if (!plot.isAdded(plotPlayer.getUUID())) { if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.other")) { - MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, - "plots.admin.projectile.other"); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, "plots.admin.projectile.other"); event.setHatching(false); } } @@ -1444,7 +1378,7 @@ public class PlayerEventListener extends PlotListener implements Listener { @EventHandler public void onItemDrop(PlayerDropItemEvent event) { Player player = event.getPlayer(); - BukkitPlayer pp = BukkitUtil.getPlayer(player); + BukkitPlayer pp = BukkitUtil.adapt(player); Location location = pp.getLocation(); PlotArea area = location.getPlotArea(); if (area == null) { @@ -1470,7 +1404,7 @@ public class PlayerEventListener extends PlotListener implements Listener { LivingEntity ent = event.getEntity(); if (ent instanceof Player) { Player player = (Player) ent; - BukkitPlayer pp = BukkitUtil.getPlayer(player); + BukkitPlayer pp = BukkitUtil.adapt(player); Location location = pp.getLocation(); PlotArea area = location.getPlotArea(); if (area == null) { @@ -1485,15 +1419,14 @@ public class PlayerEventListener extends PlotListener implements Listener { } UUID uuid = pp.getUUID(); if (!plot.isAdded(uuid) && plot.getFlag(DropProtectionFlag.class)) { - plot.debug( - player.getName() + " could not pick up item because of drop-protection = true"); + plot.debug(player.getName() + " could not pick up item because of drop-protection = true"); event.setCancelled(true); } } } @EventHandler public void onDeath(final PlayerDeathEvent event) { - Location location = BukkitUtil.getLocation(event.getEntity()); + Location location = BukkitUtil.adapt(event.getEntity().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -1507,9 +1440,7 @@ public class PlayerEventListener extends PlotListener implements Listener { } if (plot.getFlag(KeepInventoryFlag.class)) { if (plot.getFlag(KeepInventoryFlag.class)) { - plot.debug(event.getEntity().getName() - + " kept their inventory because of keep-inventory = true"); - event.getDrops().clear(); + plot.debug(event.getEntity().getName() + " kept their inventory because of keep-inventory = true"); event.setKeepInventory(true); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ProjectileEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ProjectileEventListener.java index a4cfd6171..4a5f78bc3 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ProjectileEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ProjectileEventListener.java @@ -27,13 +27,13 @@ package com.plotsquared.bukkit.listener; import com.plotsquared.bukkit.util.BukkitEntityUtil; import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.core.PlotSquared; import com.plotsquared.core.configuration.Captions; import com.plotsquared.core.location.Location; import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotHandler; +import com.plotsquared.core.plot.world.PlotAreaManager; import com.plotsquared.core.util.Permissions; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -50,14 +50,22 @@ import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.projectiles.BlockProjectileSource; import org.bukkit.projectiles.ProjectileSource; +import javax.annotation.Nonnull; +import javax.inject.Inject; + @SuppressWarnings("unused") public class ProjectileEventListener implements Listener { - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPotionSplash(LingeringPotionSplashEvent event) { + private final PlotAreaManager plotAreaManager; + + @Inject public ProjectileEventListener(@Nonnull final PlotAreaManager plotAreaManager) { + this.plotAreaManager = plotAreaManager; + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPotionSplash(LingeringPotionSplashEvent event) { Projectile entity = event.getEntity(); - Location location = BukkitUtil.getLocation(entity); - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + Location location = BukkitUtil.adapt(entity.getLocation()); + if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) { return; } if (!this.onProjectileHit(event)) { @@ -65,11 +73,10 @@ public class ProjectileEventListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPotionSplash(PotionSplashEvent event) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPotionSplash(PotionSplashEvent event) { ThrownPotion damager = event.getPotion(); - Location location = BukkitUtil.getLocation(damager); - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + Location location = BukkitUtil.adapt(damager.getLocation()); + if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) { return; } int count = 0; @@ -93,11 +100,11 @@ public class ProjectileEventListener implements Listener { if (!(shooter instanceof Player)) { return; } - Location location = BukkitUtil.getLocation(entity); - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + Location location = BukkitUtil.adapt(entity.getLocation()); + if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) { return; } - PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); + PlotPlayer pp = BukkitUtil.adapt((Player) shooter); Plot plot = location.getOwnedPlot(); if (plot != null && !plot.isAdded(pp.getUUID())) { entity.remove(); @@ -108,8 +115,8 @@ public class ProjectileEventListener implements Listener { @SuppressWarnings({"BooleanMethodIsAlwaysInverted", "cos it's not... dum IntelliJ"}) @EventHandler public boolean onProjectileHit(ProjectileHitEvent event) { Projectile entity = event.getEntity(); - Location location = BukkitUtil.getLocation(entity); - if (!PlotSquared.get().hasPlotArea(location.getWorld())) { + Location location = BukkitUtil.adapt(entity.getLocation()); + if (!this.plotAreaManager.hasPlotArea(location.getWorldName())) { return true; } PlotArea area = location.getPlotArea(); @@ -119,7 +126,7 @@ public class ProjectileEventListener implements Listener { Plot plot = area.getPlot(location); ProjectileSource shooter = entity.getShooter(); if (shooter instanceof Player) { - PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); + PlotPlayer pp = BukkitUtil.adapt((Player) shooter); if (plot == null) { if (!Permissions.hasPermission(pp, Captions.PERMISSION_PROJECTILE_UNOWNED)) { entity.remove(); @@ -127,8 +134,7 @@ public class ProjectileEventListener implements Listener { } return true; } - if (plot.isAdded(pp.getUUID()) || Permissions - .hasPermission(pp, Captions.PERMISSION_PROJECTILE_OTHER)) { + if (plot.isAdded(pp.getUUID()) || Permissions.hasPermission(pp, Captions.PERMISSION_PROJECTILE_OTHER)) { return true; } entity.remove(); @@ -139,8 +145,7 @@ public class ProjectileEventListener implements Listener { entity.remove(); return false; } - Location sLoc = - BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); + Location sLoc = BukkitUtil.adapt(((BlockProjectileSource) shooter).getBlock().getLocation()); if (!area.contains(sLoc.getX(), sLoc.getZ())) { entity.remove(); return false; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java index 599a1122b..0549d1529 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/MVdWPlaceholders.java @@ -45,8 +45,7 @@ public class MVdWPlaceholders { private final Plugin plugin; private final PlaceholderRegistry registry; - public MVdWPlaceholders(@NotNull final Plugin plugin, - @NotNull final PlaceholderRegistry registry) { + public MVdWPlaceholders(@NotNull final Plugin plugin, @NotNull final PlaceholderRegistry registry) { this.plugin = plugin; this.registry = registry; for (final Placeholder placeholder : registry.getPlaceholders()) { @@ -55,24 +54,19 @@ public class MVdWPlaceholders { PlotSquared.get().getEventDispatcher().registerListener(this); } - @Subscribe public void onNewPlaceholder(@NotNull final - PlaceholderRegistry.PlaceholderAddedEvent event) { + @Subscribe public void onNewPlaceholder(@NotNull final PlaceholderRegistry.PlaceholderAddedEvent event) { this.addPlaceholder(event.getPlaceholder()); } private void addPlaceholder(@NotNull final Placeholder placeholder) { - PlaceholderAPI.registerPlaceholder(plugin, PREFIX + String.format("%s", placeholder.getKey()), - placeholderReplaceEvent -> { - if (!placeholderReplaceEvent.isOnline() || placeholderReplaceEvent.getPlayer() == null) { - return ""; - } - final PlotPlayer player = BukkitUtil.getPlayer(placeholderReplaceEvent.getPlayer()); - if (player == null) { - return ""; - } - String key = placeholderReplaceEvent.getPlaceholder().substring(PREFIX.length()); - return registry.getPlaceholderValue(key, player); - }); + PlaceholderAPI.registerPlaceholder(plugin, PREFIX + String.format("%s", placeholder.getKey()), placeholderReplaceEvent -> { + if (!placeholderReplaceEvent.isOnline() || placeholderReplaceEvent.getPlayer() == null) { + return ""; + } + final PlotPlayer player = BukkitUtil.adapt(placeholderReplaceEvent.getPlayer()); + String key = placeholderReplaceEvent.getPlaceholder().substring(PREFIX.length()); + return registry.getPlaceholderValue(key, player); + }); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/PAPIPlaceholders.java b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/PAPIPlaceholders.java index 52d30d5ed..9a5ebdb82 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/PAPIPlaceholders.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/placeholder/PAPIPlaceholders.java @@ -57,7 +57,7 @@ public class PAPIPlaceholders extends PlaceholderExpansion { } @Override public String onPlaceholderRequest(Player p, String identifier) { - final PlotPlayer pl = PlotSquared.imp().getPlayerManager().getPlayerIfExists(p.getUniqueId()); + final PlotPlayer pl = PlotSquared.platform().getPlayerManager().getPlayerIfExists(p.getUniqueId()); if (pl == null) { return ""; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java index d5ef32ba3..17291eec9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java @@ -73,8 +73,8 @@ public class BukkitEntityUtil { public static boolean entityDamage(Entity damager, Entity victim, EntityDamageEvent.DamageCause cause) { - Location dloc = BukkitUtil.getLocation(damager); - Location vloc = BukkitUtil.getLocation(victim); + Location dloc = BukkitUtil.adapt(damager.getLocation()); + Location vloc = BukkitUtil.adapt(victim.getLocation()); PlotArea dArea = dloc.getPlotArea(); PlotArea vArea; if (dArea != null && dArea.contains(vloc.getX(), vloc.getZ())) { @@ -152,7 +152,7 @@ public class BukkitEntityUtil { } else { // shooter is not player if (shooter instanceof BlockProjectileSource) { Location sLoc = BukkitUtil - .getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); + .adapt(((BlockProjectileSource) shooter).getBlock().getLocation()); dplot = dArea.getPlot(sLoc); } player = null; @@ -161,7 +161,7 @@ public class BukkitEntityUtil { player = null; } if (player != null) { - BukkitPlayer plotPlayer = BukkitUtil.getPlayer(player); + BukkitPlayer plotPlayer = BukkitUtil.adapt(player); final com.sk89q.worldedit.world.entity.EntityType entityType; diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index ed483be9d..b0c345adc 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -2351,7 +2351,7 @@ public class Plot { * * @return The plot alias */ - @NotNull public String getAlias() { + @Nonnull public String getAlias() { if (this.settings == null) { return ""; } diff --git a/Core/src/main/java/com/plotsquared/core/util/EventDispatcher.java b/Core/src/main/java/com/plotsquared/core/util/EventDispatcher.java index 47ae83d29..eefaec5c4 100644 --- a/Core/src/main/java/com/plotsquared/core/util/EventDispatcher.java +++ b/Core/src/main/java/com/plotsquared/core/util/EventDispatcher.java @@ -104,6 +104,9 @@ public class EventDispatcher { eventBus.unregister(listener); } } + public void callGenericEvent(@Nonnull final Object event) { + eventBus.post(event); + } public void callEvent(@Nonnull final PlotEvent event) { eventBus.post(event); diff --git a/Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java index d18859b2e..11afc948d 100644 --- a/Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java +++ b/Core/src/main/java/com/plotsquared/core/util/placeholders/PlaceholderRegistry.java @@ -34,6 +34,7 @@ import com.plotsquared.core.plot.flag.GlobalFlagContainer; import com.plotsquared.core.plot.flag.PlotFlag; import com.plotsquared.core.util.EventDispatcher; import com.plotsquared.core.util.MainUtil; +import com.plotsquared.core.util.PlayerManager; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.jetbrains.annotations.NotNull; @@ -70,7 +71,7 @@ public final class PlaceholderRegistry { this.registerPlaceholder(new PlotFlagPlaceholder(flag, true)); this.registerPlaceholder(new PlotFlagPlaceholder(flag, false)); }); - this.createPlaceholder("currentplot_world", player -> player.getLocation().getWorld()); + this.createPlaceholder("currentplot_world", player -> player.getLocation().getWorldName()); this.createPlaceholder("has_plot", player -> player.getPlotCount() > 0 ? "true" : "false"); this.createPlaceholder("allowed_plot_count", player -> Integer.toString(player.getAllowedPlots())); this.createPlaceholder("plot_count", player -> Integer.toString(player.getPlotCount())); @@ -82,7 +83,7 @@ public final class PlaceholderRegistry { } try { - return MainUtil.getName(plotOwner, false); + return PlayerManager.getName(plotOwner, false); } catch (final Exception ignored) {} return "unknown"; From 615a5212bf3231bfb008ebc09e202bfe1485a422 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 24 Jul 2020 17:57:00 +0100 Subject: [PATCH 44/49] update bukkit pom --- Bukkit/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Bukkit/pom.xml b/Bukkit/pom.xml index 509145806..f0c4c0b70 100644 --- a/Bukkit/pom.xml +++ b/Bukkit/pom.xml @@ -27,7 +27,7 @@ com.plotsquared PlotSquared-Core - 5.13.1 + 6.0.0-SUPER-SNAPSHOT compile From b3ddabda29a5b21d9f4ea529f4a597442f3d6833 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Fri, 24 Jul 2020 18:20:26 +0100 Subject: [PATCH 45/49] Fix DelegateQueueCoordinator --- .../plotsquared/core/queue/DelegateQueueCoordinator.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index 7a97f4c39..6520a64fc 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -176,6 +176,13 @@ public class DelegateQueueCoordinator extends QueueCoordinator { } } + @Override public Runnable getCompleteTask() { + if (parent != null) { + return parent.getCompleteTask(); + } + return null; + } + @Override public void setCompleteTask(Runnable whenDone) { if (parent != null) { parent.setCompleteTask(whenDone); From 32887212590cbb51897c93fc19c79d45631c1461 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Tue, 28 Jul 2020 08:34:14 +0100 Subject: [PATCH 46/49] Better constructor error handling in QueueProvider. Add back default constructor requiring world to QueueCoordinator to indicate extents require this constructor --- .../plotsquared/core/queue/BasicQueueCoordinator.java | 1 + .../core/queue/DelegateQueueCoordinator.java | 1 + .../com/plotsquared/core/queue/QueueCoordinator.java | 5 ++++- .../com/plotsquared/core/queue/QueueProvider.java | 11 +++++++++++ 4 files changed, 17 insertions(+), 1 deletion(-) diff --git a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java index 684eea7f6..cca1899fe 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/BasicQueueCoordinator.java @@ -69,6 +69,7 @@ public abstract class BasicQueueCoordinator extends QueueCoordinator { private Runnable whenDone; public BasicQueueCoordinator(@Nonnull World world) { + super(world); this.world = world; this.modified = System.currentTimeMillis(); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java index 6520a64fc..b3dea64e9 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/DelegateQueueCoordinator.java @@ -50,6 +50,7 @@ public class DelegateQueueCoordinator extends QueueCoordinator { private final QueueCoordinator parent; public DelegateQueueCoordinator(QueueCoordinator parent) { + super(parent == null ? null : parent.getWorld()); this.parent = parent; if (parent != null) { diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java index 91738bd40..b6a838990 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueCoordinator.java @@ -52,7 +52,10 @@ public abstract class QueueCoordinator { @Inject private GlobalBlockQueue blockQueue; - public QueueCoordinator() { + /** + * Default constructor requires world to indicate any extents given to {@link QueueCoordinator} also need this constructor. + */ + public QueueCoordinator(@Nullable World world) { PlotSquared.platform().getInjector().injectMembers(this); } diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java index d1ee80029..5fbe4289e 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java @@ -25,11 +25,17 @@ */ package com.plotsquared.core.queue; +import com.plotsquared.core.PlotSquared; import com.sk89q.worldedit.world.World; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; public abstract class QueueProvider { + + private static final Logger logger = LoggerFactory.getLogger("P2/" + PlotSquared.class.getSimpleName()); + public static QueueProvider of(@Nonnull final Class primary) { return new QueueProvider() { @@ -37,6 +43,11 @@ public abstract class QueueProvider { try { return (QueueCoordinator) primary.getConstructors()[0].newInstance(world); } catch (Throwable e) { + logger.info("Error creating Queue: " + primary.getName() + " - Does it have the correct constructor(s)?"); + if (!primary.getName().contains("com.plotsquared")) { + logger.info("It looks like " + primary.getSimpleName() + + " is a custom queue. Please look for a plugin in its classpath and report to themm"); + } e.printStackTrace(); } return null; From 97b1a60ae8ab6326a47b1e4f1d07b95f0f44ae2d Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Tue, 28 Jul 2020 08:44:16 +0100 Subject: [PATCH 47/49] Move comments to ChunkCoordinator, remove Range annotations --- .../bukkit/generator/DelegatePlotGenerator.java | 4 +--- .../bukkit/queue/BukkitChunkCoordinator.java | 13 ------------- .../plotsquared/core/queue/ChunkCoordinator.java | 15 +++++++++++++++ .../java/com/plotsquared/core/util/ChunkUtil.java | 10 ++++------ 4 files changed, 20 insertions(+), 22 deletions(-) diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java index e155f03bd..6a0a3ce7d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/generator/DelegatePlotGenerator.java @@ -38,7 +38,6 @@ import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; -import org.jetbrains.annotations.Range; import javax.annotation.Nonnull; import java.util.Random; @@ -72,8 +71,7 @@ final class DelegatePlotGenerator extends IndependentPlotGenerator { Random random = new Random(MathMan.pair((short) chunkX, (short) chunkZ)); try { ChunkGenerator.BiomeGrid grid = new ChunkGenerator.BiomeGrid() { - @Override public void setBiome(@Range(from = 0, to = 15) int x, - @Range(from = 0, to = 15) int z, @Nonnull Biome biome) { + @Override public void setBiome(int x, int z, @Nonnull Biome biome) { result.setBiome(x, z, BukkitAdapter.adapt(biome)); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java index 3f15fc6f3..3ab6e31c0 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/queue/BukkitChunkCoordinator.java @@ -97,9 +97,6 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { this.bukkitWorld = Bukkit.getWorld(world.getName()); } - /** - * Start the coordinator instance - */ @Override public void start() { // Request initial batch this.requestBatch(); @@ -195,20 +192,10 @@ public final class BukkitChunkCoordinator extends ChunkCoordinator { chunk.removePluginChunkTicket(this.plugin); } - /** - * Get the amount of remaining chunks (at the time of the method call) - * - * @return Snapshot view of remaining chunk count - */ @Override public int getRemainingChunks() { return this.expectedSize.get(); } - /** - * Get the amount of requested chunks - * - * @return Requested chunk count - */ @Override public int getTotalChunks() { return this.totalSize; } diff --git a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java index ca89c5579..28ed3dc74 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java +++ b/Core/src/main/java/com/plotsquared/core/queue/ChunkCoordinator.java @@ -39,9 +39,24 @@ public abstract class ChunkCoordinator implements PlotSquaredTask { // Do nothing } + /** + * Starts the chunk coordinator. This will usually (implementation-specific-permitting) mark chunks to be loaded in batches, + * then add them to a queue and apply tickets once loaded to prevent unloading. A repeating task will then iterate over loaded + * chunks, access them with a Consumer(BlockVector2) and remove the ticket once work has been completed on it. + */ public abstract void start(); + /** + * Get the amount of remaining chunks (at the time of the method call) + * + * @return Snapshot view of remaining chunk count + */ public abstract int getRemainingChunks(); + /** + * Get the amount of requested chunks + * + * @return Requested chunk count + */ public abstract int getTotalChunks(); } diff --git a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java index c602b1691..31535d9fe 100644 --- a/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/ChunkUtil.java @@ -28,7 +28,6 @@ package com.plotsquared.core.util; import com.plotsquared.core.location.Location; import com.sk89q.worldedit.math.BlockVector2; import lombok.experimental.UtilityClass; -import org.jetbrains.annotations.Range; import javax.annotation.Nonnull; @@ -84,8 +83,7 @@ public class ChunkUtil { * @param z Relative z coordinate * @return J value for xyz position in Array[4096]. */ - public static int getJ(@Range(from = 0, to = 15) int x, @Range(from = 0, to = 255) int y, - @Range(from = 0, to = 15) int z) { + public static int getJ(int x, int y, int z) { return CACHE_J[y][x][z]; } @@ -95,7 +93,7 @@ public class ChunkUtil { * @param j Position in the xyz Array[4096]. * @return x coordinate within the chunk */ - public static int getX(@Range(from = 0, to = 4095) int j) { + public static int getX(int j) { return x_loc[j]; } @@ -106,7 +104,7 @@ public class ChunkUtil { * @param j Position in the xyz Array[4096]. * @return x coordinate within the chunk */ - public static int getY(@Range(from = 0, to = 15) int i, @Range(from = 0, to = 4095) int j) { + public static int getY(int i, int j) { return y_loc[i][j]; } @@ -116,7 +114,7 @@ public class ChunkUtil { * @param j Position in the xyz Array[4096]. * @return z coordinate within the chunk */ - public static int getZ(@Range(from = 0, to = 4095) int j) { + public static int getZ(int j) { return z_loc[j]; } From 704e92c3d0cb6283f5ed56fcf99bed4de549d2c5 Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Tue, 28 Jul 2020 09:35:44 +0100 Subject: [PATCH 48/49] Use placeholder --- .../main/java/com/plotsquared/core/queue/QueueProvider.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java index 5fbe4289e..b31a7da45 100644 --- a/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java +++ b/Core/src/main/java/com/plotsquared/core/queue/QueueProvider.java @@ -43,10 +43,10 @@ public abstract class QueueProvider { try { return (QueueCoordinator) primary.getConstructors()[0].newInstance(world); } catch (Throwable e) { - logger.info("Error creating Queue: " + primary.getName() + " - Does it have the correct constructor(s)?"); + logger.error("Error creating Queue: {} - Does it have the correct constructor(s)?", primary.getName()); if (!primary.getName().contains("com.plotsquared")) { - logger.info("It looks like " + primary.getSimpleName() - + " is a custom queue. Please look for a plugin in its classpath and report to themm"); + logger.error("It looks like {} is a custom queue. Please look for a plugin in its classpath and report to them.", + primary.getSimpleName()); } e.printStackTrace(); } From 38988b48191767e24991b6220ab6129e77f529af Mon Sep 17 00:00:00 2001 From: dordsor21 Date: Tue, 28 Jul 2020 10:17:15 +0100 Subject: [PATCH 49/49] A little spring cleaning - Add Javadoc comments for where QueueCoordinator can be given or nulled - Add some more Javadoc comments in general - Squash methods into one where QueueCoordinator can be given - Only use one queue in some places where it makes sense --- .../core/command/DebugRoadRegen.java | 18 ++- .../core/generator/ClassicPlotManager.java | 67 +++++++-- .../core/generator/HybridPlotManager.java | 52 ++++--- .../core/generator/HybridUtils.java | 2 +- .../java/com/plotsquared/core/plot/Plot.java | 84 +++++++---- .../com/plotsquared/core/plot/PlotArea.java | 12 +- .../plotsquared/core/plot/PlotManager.java | 131 +++++++++--------- .../plotsquared/core/util/RegionManager.java | 7 + 8 files changed, 232 insertions(+), 141 deletions(-) diff --git a/Core/src/main/java/com/plotsquared/core/command/DebugRoadRegen.java b/Core/src/main/java/com/plotsquared/core/command/DebugRoadRegen.java index b656522c7..4ff80045f 100644 --- a/Core/src/main/java/com/plotsquared/core/command/DebugRoadRegen.java +++ b/Core/src/main/java/com/plotsquared/core/command/DebugRoadRegen.java @@ -34,9 +34,10 @@ import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.plotsquared.core.plot.PlotManager; +import com.plotsquared.core.queue.QueueCoordinator; import com.plotsquared.core.util.MainUtil; -import javax.annotation.Nonnull; +import javax.annotation.Nonnull; import java.util.Arrays; @CommandDeclaration(command = "debugroadregen", @@ -85,12 +86,15 @@ public class DebugRoadRegen extends SubCommand { Captions.REQUIRES_UNMERGED.send(player); } else { PlotManager manager = area.getPlotManager(); - manager.createRoadEast(plot); - manager.createRoadSouth(plot); - manager.createRoadSouthEast(plot); - MainUtil.sendMessage(player, "&6Regenerating plot south/east roads: " + plot.getId() - + "\n&6 - Result: &aSuccess"); - MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads"); + QueueCoordinator queue = area.getQueue(); + manager.createRoadEast(plot, queue); + manager.createRoadSouth(plot, queue); + manager.createRoadSouthEast(plot, queue); + queue.setCompleteTask(() -> { + MainUtil.sendMessage(player, "&6Regenerating plot south/east roads: " + plot.getId() + "\n&6 - Result: &aSuccess"); + MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads"); + }); + queue.enqueue(); } return true; } diff --git a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java index 2361c6814..f4849dd4e 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java @@ -60,8 +60,10 @@ public class ClassicPlotManager extends SquarePlotManager { this.regionManager = regionManager; } - @Override - public boolean setComponent(@Nonnull PlotId plotId, @Nonnull String component, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { + @Override public boolean setComponent(@Nonnull PlotId plotId, + @Nonnull String component, + @Nonnull Pattern blocks, + @Nullable QueueCoordinator queue) { final Optional componentOptional = ClassicPlotManagerComponent.fromString(component); if (componentOptional.isPresent()) { switch (componentOptional.get()) { @@ -96,6 +98,12 @@ public class ClassicPlotManager extends SquarePlotManager { return true; } + /** + * Set the plot floor + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public boolean setFloor(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); if (plot != null && plot.isBasePlot()) { @@ -105,6 +113,12 @@ public class ClassicPlotManager extends SquarePlotManager { return false; } + /** + * Sets the plot main, floor and air areas. + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public boolean setAll(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); if (plot != null && plot.isBasePlot()) { @@ -113,6 +127,12 @@ public class ClassicPlotManager extends SquarePlotManager { return false; } + /** + * Sets the plot air region. + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public boolean setAir(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); if (plot != null && plot.isBasePlot()) { @@ -122,6 +142,12 @@ public class ClassicPlotManager extends SquarePlotManager { return false; } + /** + * Sets the plot main blocks. + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public boolean setMain(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); if (plot == null || plot.isBasePlot()) { @@ -130,6 +156,12 @@ public class ClassicPlotManager extends SquarePlotManager { return false; } + /** + * Set the middle plot block to a Pattern + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public boolean setMiddle(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { Plot plot = classicPlotWorld.getPlotAbs(plotId); if (plot == null || !plot.isBasePlot()) { @@ -149,6 +181,12 @@ public class ClassicPlotManager extends SquarePlotManager { return !enqueue || queue.enqueue(); } + /** + * Set a plot's outline + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public boolean setOutline(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { if (classicPlotWorld.ROAD_WIDTH == 0) { return false; @@ -216,6 +254,12 @@ public class ClassicPlotManager extends SquarePlotManager { return !enqueue || queue.enqueue(); } + /** + * Set the wall filling for a plot + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public boolean setWallFilling(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { if (classicPlotWorld.ROAD_WIDTH == 0) { return false; @@ -274,6 +318,12 @@ public class ClassicPlotManager extends SquarePlotManager { return !enqueue || queue.enqueue(); } + /** + * Set a plot's wall top block only + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public boolean setWall(@Nonnull PlotId plotId, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue) { if (classicPlotWorld.ROAD_WIDTH == 0) { return false; @@ -325,9 +375,6 @@ public class ClassicPlotManager extends SquarePlotManager { return !enqueue || queue.enqueue(); } - /** - * PLOT MERGING. - */ @Override public boolean createRoadEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue) { Location pos1 = getPlotBottomLocAbs(plot.getId()); Location pos2 = getPlotTopLocAbs(plot.getId()); @@ -363,7 +410,7 @@ public class ClassicPlotManager extends SquarePlotManager { } queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); - return queue.enqueue(); + return !enqueue || queue.enqueue(); } @Override public boolean createRoadSouth(@Nonnull Plot plot, @Nullable QueueCoordinator queue) { @@ -401,9 +448,10 @@ public class ClassicPlotManager extends SquarePlotManager { } queue.setCuboid(Location.at(classicPlotWorld.getWorldName(), sx + 1, 1, sz + 1), Location.at(classicPlotWorld.getWorldName(), ex - 1, classicPlotWorld.ROAD_HEIGHT, ez - 1), classicPlotWorld.ROAD_BLOCK.toPattern()); - return queue.enqueue(); + return !enqueue || queue.enqueue(); } + @Override public boolean createRoadSouthEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue) { Location pos2 = getPlotTopLocAbs(plot.getId()); int sx = pos2.getX() + 1; @@ -504,11 +552,6 @@ public class ClassicPlotManager extends SquarePlotManager { return !enqueue || queue.enqueue(); } - /** - * Finishing off plot merging by adding in the walls surrounding the plot (OPTIONAL)(UNFINISHED). - * - * @return false if part of the merge failed, otherwise true if successful. - */ @Override public boolean finishPlotMerge(@Nonnull List plotIds, @Nullable QueueCoordinator queue) { final BlockBucket claim = classicPlotWorld.CLAIMED_WALL_BLOCK; if (classicPlotWorld.PLACE_TOP_BLOCK && (!claim.isAir() || !claim.equals(classicPlotWorld.WALL_BLOCK))) { diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java index 64acf40ad..42efb5e0f 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridPlotManager.java @@ -93,8 +93,8 @@ public class HybridPlotManager extends ClassicPlotManager { Template.zipAll(hybridPlotWorld.getWorldName(), files); } - @Override public boolean createRoadEast(@Nonnull final Plot plot) { - super.createRoadEast(plot); + @Override public boolean createRoadEast(@Nonnull final Plot plot, @Nullable QueueCoordinator queue) { + super.createRoadEast(plot, queue); PlotId id = plot.getId(); PlotId id2 = PlotId.of(id.getX() + 1, id.getY()); Location bot = getPlotBottomLocAbs(id2); @@ -105,10 +105,13 @@ public class HybridPlotManager extends ClassicPlotManager { if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; } - QueueCoordinator queue = hybridPlotWorld.getQueue(); + boolean enqueue = false; + if (queue == null) { + queue = hybridPlotWorld.getQueue(); + enqueue = true; + } createSchemAbs(queue, pos1, pos2, true); - queue.enqueue(); - return true; + return !enqueue || queue.enqueue(); } private void resetBiome(@Nonnull final HybridPlotWorld hybridPlotWorld, @Nonnull final Location pos1, @Nonnull final Location pos2) { @@ -159,8 +162,8 @@ public class HybridPlotManager extends ClassicPlotManager { } } - @Override public boolean createRoadSouth(@Nonnull final Plot plot) { - super.createRoadSouth(plot); + @Override public boolean createRoadSouth(@Nonnull final Plot plot, @Nullable QueueCoordinator queue) { + super.createRoadSouth(plot, queue); PlotId id = plot.getId(); PlotId id2 = PlotId.of(id.getX(), id.getY() + 1); Location bot = getPlotBottomLocAbs(id2); @@ -171,24 +174,31 @@ public class HybridPlotManager extends ClassicPlotManager { if (!hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { return true; } - QueueCoordinator queue = hybridPlotWorld.getQueue(); + boolean enqueue = false; + if (queue == null) { + enqueue = true; + queue = hybridPlotWorld.getQueue(); + } createSchemAbs(queue, pos1, pos2, true); - queue.enqueue(); - return true; + return !enqueue || queue.enqueue(); } - @Override public boolean createRoadSouthEast(@Nonnull final Plot plot) { - super.createRoadSouthEast(plot); + @Override public boolean createRoadSouthEast(@Nonnull final Plot plot, @Nullable QueueCoordinator queue) { + super.createRoadSouthEast(plot, queue); PlotId id = plot.getId(); PlotId id2 = PlotId.of(id.getX() + 1, id.getY() + 1); Location pos1 = getPlotTopLocAbs(id).add(1, 0, 1).withY(0); Location pos2 = getPlotBottomLocAbs(id2).withY(Math.min(getWorldHeight(), 255)); - QueueCoordinator queue = hybridPlotWorld.getQueue(); + boolean enqueue = false; + if (queue == null) { + enqueue = true; + queue = hybridPlotWorld.getQueue(); + } createSchemAbs(queue, pos1, pos2, true); if (hybridPlotWorld.ROAD_SCHEMATIC_ENABLED) { createSchemAbs(queue, pos1, pos2, true); } - return queue.enqueue(); + return !enqueue || queue.enqueue(); } /** @@ -198,7 +208,7 @@ public class HybridPlotManager extends ClassicPlotManager { * don't need to do something quite as complex unless you happen to have 512x512 sized plots. *

*/ - @Override public boolean clearPlot(@Nonnull final Plot plot, @Nullable final Runnable whenDone) { + @Override public boolean clearPlot(@Nonnull final Plot plot, @Nullable final Runnable whenDone, @Nullable QueueCoordinator queue) { if (this.regionManager.notifyClear(this)) { //If this returns false, the clear didn't work if (this.regionManager.handleClear(plot, whenDone, this)) { @@ -224,7 +234,11 @@ public class HybridPlotManager extends ClassicPlotManager { } final BiomeType biome = hybridPlotWorld.getPlotBiome(); - final QueueCoordinator queue = hybridPlotWorld.getQueue(); + boolean enqueue = false; + if (queue == null) { + enqueue = true; + queue = hybridPlotWorld.getQueue(); + } if (!canRegen) { queue.setCuboid(pos1.withY(0), pos2.withY(0), bedrock); // Each component has a different layer @@ -236,8 +250,10 @@ public class HybridPlotManager extends ClassicPlotManager { queue.setRegenRegion(new CuboidRegion(pos1.getBlockVector3(), pos2.getBlockVector3())); } pastePlotSchematic(queue, pos1, pos2); - queue.setCompleteTask(whenDone); - return queue.enqueue(); + if (whenDone != null) { + queue.setCompleteTask(whenDone); + } + return !enqueue || queue.enqueue(); } public void pastePlotSchematic(@Nonnull final QueueCoordinator queue, @Nonnull final Location bottom, @Nonnull final Location top) { diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index 384eecdcd..2a1215074 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -109,7 +109,7 @@ public class HybridUtils { public void regeneratePlotWalls(final PlotArea area) { PlotManager plotManager = area.getPlotManager(); - plotManager.regenerateAllPlotWalls(); + plotManager.regenerateAllPlotWalls(null); } public void analyzeRegion(final String world, final CuboidRegion region, final RunnableVal whenDone) { diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index b12a7a5d5..236f01a27 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -1061,13 +1061,17 @@ public class Plot { } TaskManager.runTask(whenDone); }; + QueueCoordinator queue = getArea().getQueue(); for (Plot current : plots) { if (isDelete || !current.hasOwner()) { - manager.unClaimPlot(current, null); + manager.unClaimPlot(current, null, queue); } else { - manager.claimPlot(current); + manager.claimPlot(current, queue); } } + if (queue.size() > 0) { + queue.enqueue(); + } TaskManager.runTask(run); return; } @@ -1082,7 +1086,7 @@ public class Plot { } return; } - manager.clearPlot(current, this); + manager.clearPlot(current, this, null); } }; run.run(); @@ -1861,7 +1865,7 @@ public class Plot { } }); } - plotworld.getPlotManager().claimPlot(this); + plotworld.getPlotManager().claimPlot(this, null); return true; } @@ -2074,8 +2078,11 @@ public class Plot { /** * Remove the east road section of a plot
* - Used when a plot is merged
+ * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. */ - public void removeRoadEast() { + public void removeRoadEast(@Nullable QueueCoordinator queue) { if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { Plot other = this.getRelative(Direction.EAST); Location bot = other.getBottomAbs(); @@ -2084,7 +2091,7 @@ public class Plot { Location pos2 = Location.at(this.getWorldName(), bot.getX(), MAX_HEIGHT, top.getZ()); this.regionManager.regenerateRegion(pos1, pos2, true, null); } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove - this.area.getPlotManager().removeRoadEast(this); + this.area.getPlotManager().removeRoadEast(this, queue); } } @@ -2440,8 +2447,11 @@ public class Plot { /** * Remove the south road section of a plot
* - Used when a plot is merged
+ * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. */ - public void removeRoadSouth() { + public void removeRoadSouth(@Nullable QueueCoordinator queue) { if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { Plot other = this.getRelative(Direction.SOUTH); Location bot = other.getBottomAbs(); @@ -2450,7 +2460,7 @@ public class Plot { Location pos2 = Location.at(this.getWorldName(), top.getX(), MAX_HEIGHT, bot.getZ()); this.regionManager.regenerateRegion(pos1, pos2, true, null); } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove - this.getManager().removeRoadSouth(this); + this.getManager().removeRoadSouth(this, queue); } } @@ -2474,6 +2484,7 @@ public class Plot { Plot current; boolean toReturn = false; HashSet visited = new HashSet<>(); + QueueCoordinator queue = getArea().getQueue(); while ((current = frontier.poll()) != null && max >= 0) { if (visited.contains(current)) { continue; @@ -2484,7 +2495,7 @@ public class Plot { Plot other = current.getRelative(Direction.NORTH); if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { - current.mergePlot(other, removeRoads); + current.mergePlot(other, removeRoads, queue); merged.add(current.getId()); merged.add(other.getId()); toReturn = true; @@ -2493,7 +2504,7 @@ public class Plot { ArrayList ids = new ArrayList<>(); ids.add(current.getId()); ids.add(other.getId()); - this.getManager().finishPlotMerge(ids); + this.getManager().finishPlotMerge(ids, queue); } } } @@ -2501,7 +2512,7 @@ public class Plot { Plot other = current.getRelative(Direction.EAST); if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { - current.mergePlot(other, removeRoads); + current.mergePlot(other, removeRoads, queue); merged.add(current.getId()); merged.add(other.getId()); toReturn = true; @@ -2510,7 +2521,7 @@ public class Plot { ArrayList ids = new ArrayList<>(); ids.add(current.getId()); ids.add(other.getId()); - this.getManager().finishPlotMerge(ids); + this.getManager().finishPlotMerge(ids, queue); } } } @@ -2518,7 +2529,7 @@ public class Plot { Plot other = current.getRelative(Direction.SOUTH); if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { - current.mergePlot(other, removeRoads); + current.mergePlot(other, removeRoads, queue); merged.add(current.getId()); merged.add(other.getId()); toReturn = true; @@ -2527,7 +2538,7 @@ public class Plot { ArrayList ids = new ArrayList<>(); ids.add(current.getId()); ids.add(other.getId()); - this.getManager().finishPlotMerge(ids); + this.getManager().finishPlotMerge(ids, queue); } } } @@ -2535,7 +2546,7 @@ public class Plot { Plot other = current.getRelative(Direction.WEST); if (other != null && other.isOwner(uuid) && (other.getBasePlot(false).equals(current.getBasePlot(false)) || (plots = other.getConnectedPlots()).size() <= max && frontier.addAll(plots) && (max -= plots.size()) != -1)) { - current.mergePlot(other, removeRoads); + current.mergePlot(other, removeRoads, queue); merged.add(current.getId()); merged.add(other.getId()); toReturn = true; @@ -2544,10 +2555,13 @@ public class Plot { ArrayList ids = new ArrayList<>(); ids.add(current.getId()); ids.add(other.getId()); - this.getManager().finishPlotMerge(ids); + this.getManager().finishPlotMerge(ids, queue); } } } + if (queue.size() > 0) { + queue.enqueue(); + } } return toReturn; } @@ -2603,15 +2617,18 @@ public class Plot { /** * Remove the SE road (only effects terrain) + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. */ - public void removeRoadSouthEast() { + public void removeRoadSouthEast(@Nullable QueueCoordinator queue) { if (this.area.getType() != PlotAreaType.NORMAL && this.area.getTerrain() == PlotAreaTerrainType.ROAD) { Plot other = this.getRelative(1, 1); Location pos1 = this.getTopAbs().add(1, 0, 1).withY(0); Location pos2 = other.getBottomAbs().subtract(1, 0, 1).withY(MAX_HEIGHT); this.regionManager.regenerateRegion(pos1, pos2, true, null); } else if (this.area.getTerrain() != PlotAreaTerrainType.ALL) { // no road generated => no road to remove - this.area.getPlotManager().removeRoadSouthEast(this); + this.area.getPlotManager().removeRoadSouthEast(this, queue); } } @@ -3088,10 +3105,10 @@ public class Plot { /** * Merges two plots.
- Assumes plots are directly next to each other
- saves to DB * - * @param lesserPlot - * @param removeRoads + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. */ - public void mergePlot(Plot lesserPlot, boolean removeRoads) { + public void mergePlot(Plot lesserPlot, boolean removeRoads, @Nullable QueueCoordinator queue) { Plot greaterPlot = this; lesserPlot.removeSign(); if (lesserPlot.getId().getX() == greaterPlot.getId().getX()) { @@ -3108,14 +3125,14 @@ public class Plot { lesserPlot.mergeData(greaterPlot); if (removeRoads) { //lesserPlot.removeSign(); - lesserPlot.removeRoadSouth(); + lesserPlot.removeRoadSouth(queue); Plot diagonal = greaterPlot.getRelative(Direction.EAST); if (diagonal.getMerged(Direction.NORTHWEST)) { - lesserPlot.removeRoadSouthEast(); + lesserPlot.removeRoadSouthEast(queue); } Plot below = greaterPlot.getRelative(Direction.WEST); if (below.getMerged(Direction.NORTHEAST)) { - below.getRelative(Direction.NORTH).removeRoadSouthEast(); + below.getRelative(Direction.NORTH).removeRoadSouthEast(queue); } } } @@ -3135,17 +3152,16 @@ public class Plot { //lesserPlot.removeSign(); Plot diagonal = greaterPlot.getRelative(Direction.SOUTH); if (diagonal.getMerged(Direction.NORTHWEST)) { - lesserPlot.removeRoadSouthEast(); + lesserPlot.removeRoadSouthEast(queue); } - lesserPlot.removeRoadEast(); + lesserPlot.removeRoadEast(queue); } Plot below = greaterPlot.getRelative(Direction.NORTH); if (below.getMerged(Direction.SOUTHWEST)) { - below.getRelative(Direction.WEST).removeRoadSouthEast(); + below.getRelative(Direction.WEST).removeRoadSouthEast(queue); } } } - } /** @@ -3235,8 +3251,12 @@ public class Plot { Plot plot = destination.getRelative(0, 0); Plot originPlot = originArea.getPlotAbs(PlotId.of(plot.id.getX() - offset.getX(), plot.id.getY() - offset.getY())); final Runnable clearDone = () -> { + QueueCoordinator queue = getArea().getQueue(); for (final Plot current : plot.getConnectedPlots()) { - getManager().claimPlot(current); + getManager().claimPlot(current, queue); + } + if (queue.size() > 0) { + queue.enqueue(); } plot.setSign(); TaskManager.runTask(whenDone); @@ -3334,8 +3354,12 @@ public class Plot { Runnable run = new Runnable() { @Override public void run() { if (regions.isEmpty()) { + QueueCoordinator queue = getArea().getQueue(); for (Plot current : getConnectedPlots()) { - destination.getManager().claimPlot(current); + destination.getManager().claimPlot(current, queue); + } + if (queue.size() > 0) { + queue.enqueue(); } destination.setSign(); TaskManager.runTask(whenDone); diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java index 31e637cf9..e12e773eb 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java @@ -934,7 +934,8 @@ public abstract class PlotArea { final PlotId pos2 = plotIds.get(plotIds.size() - 1); final PlotManager manager = getPlotManager(); - manager.startPlotMerge(plotIds); + QueueCoordinator queue = getQueue(); + manager.startPlotMerge(plotIds, queue); final Set trusted = new HashSet<>(); final Set members = new HashSet<>(); final Set denied = new HashSet<>(); @@ -969,24 +970,25 @@ public abstract class PlotArea { if (ly) { if (!plot.getMerged(Direction.EAST) || !plot.getMerged(Direction.SOUTH)) { if (removeRoads) { - plot.removeRoadSouthEast(); + plot.removeRoadSouthEast(queue); } } } if (!plot.getMerged(Direction.EAST)) { plot2 = plot.getRelative(1, 0); - plot.mergePlot(plot2, removeRoads); + plot.mergePlot(plot2, removeRoads, queue); } } if (ly) { if (!plot.getMerged(Direction.SOUTH)) { plot2 = plot.getRelative(0, 1); - plot.mergePlot(plot2, removeRoads); + plot.mergePlot(plot2, removeRoads, queue); } } } } - manager.finishPlotMerge(plotIds); + manager.finishPlotMerge(plotIds, queue); + queue.enqueue(); return true; } diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java b/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java index 8a1413a35..187e29ffd 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotManager.java @@ -61,27 +61,16 @@ public abstract class PlotManager { // the same applies here public abstract Location getPlotTopLocAbs(@Nonnull PlotId plotId); - /* - * Plot clearing (return false if you do not support some method) - */ - public boolean clearPlot(@Nonnull Plot plot, @Nullable Runnable whenDone) { - return clearPlot(plot, whenDone, null); - } - - public boolean claimPlot(@Nonnull Plot plot) { - return claimPlot(plot, null); - - } - - public boolean unClaimPlot(@Nonnull Plot plot, @Nullable Runnable whenDone) { - return unClaimPlot(plot, whenDone, null); - - } - public abstract boolean clearPlot(@Nonnull Plot plot, @Nullable Runnable whenDone, @Nullable QueueCoordinator queue); public abstract boolean claimPlot(@Nonnull Plot plot, @Nullable QueueCoordinator queue); + /** + * Completes block changes associated with plot unclaim. + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public abstract boolean unClaimPlot(@Nonnull Plot plot, @Nullable Runnable whenDone, @Nullable QueueCoordinator queue); /** @@ -98,77 +87,85 @@ public abstract class PlotManager { */ public abstract String[] getPlotComponents(@Nonnull PlotId plotId); - public boolean setComponent(@Nonnull PlotId plotId, @Nonnull String component, @Nonnull Pattern blocks) { - return setComponent(plotId, component, blocks, null); - } - + /** + * Set the specified components to the specified Pattern on the specified plot. + * + * @param component FLOOR, WALL, AIR, MAIN, MIDDLE, OUTLINE, BORDER, ALL (floor, air and main). + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public abstract boolean setComponent(@Nonnull PlotId plotId, @Nonnull String component, @Nonnull Pattern blocks, @Nullable QueueCoordinator queue); - /* - * PLOT MERGING (return false if your generator does not support plot - * merging). + /** + * Create the road east of the plot (not schematic-based) + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. */ - public boolean createRoadEast(@Nonnull Plot plot) { - return createRoadEast(plot, null); - } - - public boolean createRoadSouth(@Nonnull Plot plot) { - return createRoadSouth(plot, null); - } - - public boolean createRoadSouthEast(@Nonnull Plot plot) { - return createRoadSouthEast(plot, null); - } - - public boolean removeRoadEast(@Nonnull Plot plot) { - return removeRoadEast(plot, null); - } - - public boolean removeRoadSouth(@Nonnull Plot plot) { - return removeRoadSouth(plot, null); - } - - public boolean removeRoadSouthEast(@Nonnull Plot plot) { - return removeRoadSouthEast(plot, null); - } - - public boolean startPlotMerge(@Nonnull List plotIds) { - return startPlotMerge(plotIds, null); - } - - public boolean startPlotUnlink(@Nonnull List plotIds) { - return startPlotUnlink(plotIds, null); - } - - public boolean finishPlotMerge(@Nonnull List plotIds) { - return finishPlotMerge(plotIds, null); - } - - public boolean finishPlotUnlink(@Nonnull List plotIds) { - return finishPlotUnlink(plotIds, null); - } - public abstract boolean createRoadEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue); + /** + * Create the road south of the plot (not schematic-based) + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public abstract boolean createRoadSouth(@Nonnull Plot plot, @Nullable QueueCoordinator queue); + /** + * Create the south-east corner of the road (intersection, not schematic-based) + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public abstract boolean createRoadSouthEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue); + /** + * Replace the road to the east of the plot with standard plot blocks (for when merging plots) + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public abstract boolean removeRoadEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue); + /** + * Replace the road to the south of the plot with standard plot blocks (for when merging plots) + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public abstract boolean removeRoadSouth(@Nonnull Plot plot, @Nullable QueueCoordinator queue); + /** + * Replace the road to the south east of the plot (intersection) with standard plot blocks (for when merging plots) + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public abstract boolean removeRoadSouthEast(@Nonnull Plot plot, @Nullable QueueCoordinator queue); public abstract boolean startPlotMerge(@Nonnull List plotIds, @Nullable QueueCoordinator queue); public abstract boolean startPlotUnlink(@Nonnull List plotIds, @Nullable QueueCoordinator queue); + /** + * Finishing off plot merging by adding in the walls surrounding the plot (OPTIONAL)(UNFINISHED). + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + * @return false if part if the merge failed, otherwise true if successful. + */ public abstract boolean finishPlotMerge(@Nonnull List plotIds, @Nullable QueueCoordinator queue); + /** + * Finished off an unlink by resetting the top wall block for unlinked plots + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + */ public abstract boolean finishPlotUnlink(@Nonnull List plotIds, @Nullable QueueCoordinator queue); public void exportTemplate() throws IOException { @@ -184,12 +181,10 @@ public abstract class PlotManager { /** * Sets all the blocks along all the plot walls to their correct state (claimed or unclaimed). * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. * @return true if the wall blocks were successfully set */ - public boolean regenerateAllPlotWalls() { - return regenerateAllPlotWalls(null); - } - public boolean regenerateAllPlotWalls(@Nullable QueueCoordinator queue) { boolean success = true; for (Plot plot : plotArea.getPlots()) { diff --git a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java index e2d6255d8..f3e745c86 100644 --- a/Core/src/main/java/com/plotsquared/core/util/RegionManager.java +++ b/Core/src/main/java/com/plotsquared/core/util/RegionManager.java @@ -95,6 +95,13 @@ public abstract class RegionManager { }); } + /** + * Set a number of cuboids to a certain block between two y values. + * + * @param queue Nullable {@link QueueCoordinator}. If null, creates own queue and enqueues, + * otherwise writes to the queue but does not enqueue. + * @return true if not enqueued, otherwise whether the created queue enqueued. + */ public boolean setCuboids(final PlotArea area, final Set regions, final Pattern blocks,