From 7f3c4c4828d0f76b1d8e4b36e4610d5ad66963ca Mon Sep 17 00:00:00 2001 From: MattBDev <4009945+MattBDev@users.noreply.github.com> Date: Fri, 7 Jun 2019 20:58:48 -0400 Subject: [PATCH] A lot of removals, upstream merges, and maybe more. --- .../com/boydti/fawe/bukkit/FaweBukkit.java | 9 +- .../fawe/bukkit/util/cui/CUIListener.java | 31 - .../fawe/bukkit/util/cui/StructureCUI.java | 201 --- .../main/java/com/boydti/fawe/FaweAPI.java | 10 - .../main/java/com/boydti/fawe/config/BBC.java | 3 +- .../jnbt/anvil/HeightMapMCAGenerator.java | 12 +- .../fawe/jnbt/anvil/generator/CavesGen.java | 1 - .../fawe/jnbt/anvil/generator/GenBase.java | 7 - .../fawe/jnbt/anvil/generator/Resource.java | 2 - .../fawe/jnbt/anvil/generator/SchemGen.java | 6 +- .../com/boydti/fawe/object/FawePlayer.java | 6 +- .../com/boydti/fawe/object/Metadatable.java | 14 +- .../com/boydti/fawe/object/PseudoRandom.java | 23 - .../boydti/fawe/object/brush/ErodeBrush.java | 7 - .../fawe/object/brush/ShatterBrush.java | 7 +- .../fawe/object/brush/SplatterBrush.java | 31 +- .../fawe/object/brush/StencilBrush.java | 12 +- .../object/brush/heightmap/HeightMap.java | 7 +- .../object/brush/scroll/ScrollClipboard.java | 2 +- .../brush/visualization/VisualQueue.java | 3 +- .../fawe/object/mask/FaweBlockMatcher.java | 4 +- .../pattern/RandomFullClipboardPattern.java | 9 +- .../object/schematic/visualizer/SchemVis.java | 1267 ++++++++--------- .../java/com/boydti/fawe/util/BrushCache.java | 2 +- .../com/boydti/fawe/util/ImgurUtility.java | 18 +- .../main/java/com/boydti/fawe/util/Jars.java | 7 +- .../java/com/boydti/fawe/util/MainUtil.java | 197 +-- .../java/com/boydti/fawe/util/cui/CUI.java | 18 - .../com/boydti/fawe/util/image/ImageUtil.java | 4 +- .../java/com/sk89q/worldedit/EditSession.java | 2 +- .../com/sk89q/worldedit/LocalSession.java | 46 +- .../worldedit/command/SchematicCommands.java | 107 +- .../worldedit/command/UtilityCommands.java | 10 +- .../command/composition/SelectionCommand.java | 1 - .../com/sk89q/worldedit/extent/Extent.java | 2 - .../clipboard/io/BuiltInClipboardFormat.java | 94 +- .../internal/command/WorldEditBinding.java | 7 +- .../sk89q/worldedit/world/SimpleWorld.java | 3 +- 38 files changed, 871 insertions(+), 1321 deletions(-) delete mode 100644 worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/CUIListener.java delete mode 100644 worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/StructureCUI.java delete mode 100644 worldedit-core/src/main/java/com/boydti/fawe/object/PseudoRandom.java delete mode 100644 worldedit-core/src/main/java/com/boydti/fawe/util/cui/CUI.java diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java index d9634733d..e020b3f71 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java @@ -24,7 +24,6 @@ import com.boydti.fawe.bukkit.util.BukkitReflectionUtils; import com.boydti.fawe.bukkit.util.BukkitTaskMan; import com.boydti.fawe.bukkit.util.ItemUtil; import com.boydti.fawe.bukkit.util.VaultUtil; -import com.boydti.fawe.bukkit.util.cui.CUIListener; import com.boydti.fawe.bukkit.util.image.BukkitImageViewer; import com.boydti.fawe.bukkit.v0.BukkitQueue_0; import com.boydti.fawe.bukkit.v0.BukkitQueue_All; @@ -73,10 +72,10 @@ public class FaweBukkit implements IFawe, Listener { private boolean listeningImages; private BukkitImageListener imageListener; - private CFIPacketListener packetListener; + //private CFIPacketListener packetListener; - private boolean listeningCui; - private CUIListener cuiListener; + //private boolean listeningCui; + //private CUIListener cuiListener; public VaultUtil getVault() { return this.vault; @@ -151,7 +150,7 @@ public class FaweBukkit implements IFawe, Listener { if (listeningImages && imageListener == null) return null; try { listeningImages = true; - registerPacketListener(); + //registerPacketListener(); PluginManager manager = Bukkit.getPluginManager(); if (manager.getPlugin("PacketListenerApi") == null) { diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/CUIListener.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/CUIListener.java deleted file mode 100644 index 2101d64b8..000000000 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/CUIListener.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.boydti.fawe.bukkit.util.cui; - -import com.boydti.fawe.object.FawePlayer; -import com.boydti.fawe.util.cui.CUI; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.plugin.Plugin; - -public class CUIListener implements Listener { - - public CUIListener(Plugin plugin) { - Bukkit.getPluginManager().registerEvents(this, plugin); - } - - @EventHandler - public void onPlayerMove(PlayerMoveEvent event) { - Location from = event.getFrom(); - Location to = event.getTo(); - if ((int) from.getX() >> 2 != (int) to.getX() >> 2 || (int) from.getZ() >> 2 != (int) to.getZ() >> 2 || (int) from.getY() >> 2 != (int) to.getY() >> 2) { - FawePlayer player = FawePlayer.wrap(event.getPlayer()); - CUI cui = player.getMeta("CUI"); - if (cui instanceof StructureCUI) { - StructureCUI sCui = (StructureCUI) cui; - sCui.update(); - } - } - } -} \ No newline at end of file diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/StructureCUI.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/StructureCUI.java deleted file mode 100644 index 5040670d5..000000000 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/StructureCUI.java +++ /dev/null @@ -1,201 +0,0 @@ -package com.boydti.fawe.bukkit.util.cui; - -import com.boydti.fawe.FaweCache; -import com.boydti.fawe.bukkit.v0.BukkitQueue_0; -import com.boydti.fawe.object.FawePlayer; -import com.boydti.fawe.util.cui.CUI; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.ProtocolManager; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.injector.PacketConstructor; -import com.comphenix.protocol.wrappers.BlockPosition; -import com.comphenix.protocol.wrappers.nbt.NbtBase; -import com.comphenix.protocol.wrappers.nbt.NbtCompound; -import com.comphenix.protocol.wrappers.nbt.NbtFactory; -import com.sk89q.worldedit.bukkit.BukkitAdapter; -import com.sk89q.worldedit.internal.cui.CUIEvent; -import com.sk89q.worldedit.internal.cui.SelectionPointEvent; -import com.sk89q.worldedit.internal.cui.SelectionShapeEvent; -import com.sk89q.worldedit.math.BlockVector3; - -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import com.sk89q.worldedit.world.block.BlockState; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -public class StructureCUI extends CUI { - private boolean cuboid = true; - - private BlockVector3 pos1; - private BlockVector3 pos2; - - private BlockVector3 remove; - private NbtCompound removeTag; - private BlockState state; - - public StructureCUI(FawePlayer player) { - super(player); - } - - @Override - public void dispatchCUIEvent(CUIEvent event) { - if (event instanceof SelectionShapeEvent) { - clear(); - this.cuboid = event.getParameters()[0].equalsIgnoreCase("cuboid"); - } else if (cuboid && event instanceof SelectionPointEvent) { - SelectionPointEvent spe = (SelectionPointEvent) event; - String[] param = spe.getParameters(); - int id = Integer.parseInt(param[0]); - int x = Integer.parseInt(param[1]); - int y = Integer.parseInt(param[2]); - int z = Integer.parseInt(param[3]); - BlockVector3 pos = BlockVector3.at(x, y, z); - if (id == 0) { - pos1 = pos; - } else { - pos2 = pos; - } - update(); - } - } - - private int viewDistance() { - Player player = this.getPlayer().parent; - //todo replace with PaperLib.isPaper() - if (Bukkit.getVersion().contains("paper")) { - return player.getViewDistance(); - } else { - return Bukkit.getViewDistance(); - } - } - - public void clear() { - pos1 = null; - pos2 = null; - update(); - } - - private NbtCompound constructStructureNbt(int x, int y, int z, int posX, int posY, int posZ, int sizeX, int sizeY, int sizeZ) { - HashMap tag = new HashMap<>(); - tag.put("name", UUID.randomUUID().toString()); - tag.put("author", "Empire92"); // :D - tag.put("metadata", ""); - tag.put("x", x); - tag.put("y", y); - tag.put("z", z); - tag.put("posX", posX); - tag.put("posY", posY); - tag.put("posZ", posZ); - tag.put("sizeX", sizeX); - tag.put("sizeY", sizeY); - tag.put("sizeZ", sizeZ); - tag.put("rotation", "NONE"); - tag.put("mirror", "NONE"); - tag.put("mode", "SAVE"); - tag.put("ignoreEntities", true); - tag.put("powered", false); - tag.put("showair", false); - tag.put("showboundingbox", true); - tag.put("integrity", 1.0f); - tag.put("seed", 0); - tag.put("id", "minecraft:structure_block"); - Object nmsTag = BukkitQueue_0.fromNative(FaweCache.asTag(tag)); - return NbtFactory.fromNMSCompound(nmsTag); - } - - private void sendOp() { - Player player = this.getPlayer().parent; - ProtocolManager manager = ProtocolLibrary.getProtocolManager(); - - PacketConstructor statusCtr = manager.createPacketConstructor(PacketType.Play.Server.ENTITY_STATUS, player, (byte) 28); - PacketContainer status = statusCtr.createPacket(player, (byte) 28); - - try { - manager.sendServerPacket(player, status); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - - private void sendNbt(BlockVector3 pos, NbtCompound compound) { - Player player = this.getPlayer().parent; - ProtocolManager manager = ProtocolLibrary.getProtocolManager(); - - PacketContainer blockNbt = new PacketContainer(PacketType.Play.Server.TILE_ENTITY_DATA); - blockNbt.getBlockPositionModifier().write(0, new BlockPosition(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ())); - blockNbt.getIntegers().write(0, 7); - blockNbt.getNbtModifier().write(0, compound); - - - try { - manager.sendServerPacket(player, blockNbt); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - - public synchronized void update() { - Player player = this.getPlayer().parent; - Location playerLoc = player.getLocation(); - boolean setOp = remove == null && !player.isOp(); - if (remove != null) { - int cx = playerLoc.getBlockX() >> 4; - int cz = playerLoc.getBlockZ() >> 4; - int viewDistance = viewDistance(); - if (Math.abs(cx - (remove.getBlockX() >> 4)) <= viewDistance && Math.abs(cz - (remove.getBlockZ() >> 4)) <= viewDistance) { - Map> map = removeTag.getValue(); - map.put("sizeX", NbtFactory.of("sizeX", 0)); - sendNbt(remove, removeTag); - Location removeLoc = new Location(player.getWorld(), remove.getX(), remove.getY(), remove.getZ()); - player.sendBlockChange(removeLoc, BukkitAdapter.adapt(state)); - } - remove = null; - } - if (pos1 == null || pos2 == null) return; - BlockVector3 min = pos1.getMinimum(pos2); - BlockVector3 max = pos1.getMaximum(pos2); - - // Position - double rotX = playerLoc.getYaw(); - double rotY = playerLoc.getPitch(); - double xz = Math.cos(Math.toRadians(rotY)); - int x = (int) (playerLoc.getX() - (-xz * Math.sin(Math.toRadians(rotX))) * 12); - int z = (int) (playerLoc.getZ() - (xz * Math.cos(Math.toRadians(rotX))) * 12); - int y = Math.max(0, Math.min(Math.min(255, max.getBlockY() + 32), playerLoc.getBlockY() + 3)); - int minX = Math.max(Math.min(32, min.getBlockX() - x), -32); - int maxX = Math.max(Math.min(32, max.getBlockX() - x + 1), -32); - int minY = Math.max(Math.min(32, min.getBlockY() - y), -32); - int maxY = Math.max(Math.min(32, max.getBlockY() - y + 1), -32); - int minZ = Math.max(Math.min(32, min.getBlockZ() - z), -32); - int maxZ = Math.max(Math.min(32, max.getBlockZ() - z + 1), -32); - int sizeX = Math.min(32, maxX - minX); - int sizeY = Math.min(32, maxY - minY); - int sizeZ = Math.min(32, maxZ - minZ); - if (sizeX == 0 || sizeY == 0 || sizeZ == 0) return; - // maxX - 32; - int posX = Math.max(minX, Math.min(16, maxX) - 32); - int posY = Math.max(minY, Math.min(16, maxY) - 32); - int posZ = Math.max(minZ, Math.min(16, maxZ) - 32); - - // NBT - NbtCompound compound = constructStructureNbt(x, y, z, posX, posY, posZ, sizeX, sizeY, sizeZ); - - Block block = player.getWorld().getBlockAt(x, y, z); - remove = BlockVector3.at(x, y, z); - state = BukkitAdapter.adapt(block.getBlockData()); - removeTag = compound; - - Location blockLoc = new Location(player.getWorld(), x, y, z); - player.sendBlockChange(blockLoc, Material.STRUCTURE_BLOCK, (byte) 0); - if (setOp) sendOp(); - sendNbt(remove, compound); - } -} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/FaweAPI.java b/worldedit-core/src/main/java/com/boydti/fawe/FaweAPI.java index 6690bbdf6..513a44301 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/FaweAPI.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/FaweAPI.java @@ -7,7 +7,6 @@ import com.boydti.fawe.example.NMSRelighter; import com.boydti.fawe.object.FaweLocation; import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FaweQueue; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.RegionWrapper; import com.boydti.fawe.object.changeset.DiskStorageHistory; import com.boydti.fawe.object.schematic.Schematic; @@ -245,15 +244,6 @@ public class FaweAPI { return MemUtil.isMemoryLimited(); } - /** - * Use ThreadLocalRandom instead - * - */ - @Deprecated - public static PseudoRandom getFastRandom() { - throw new UnsupportedOperationException("Please Use ThreadLocalRandom instead."); - } - /** * Get a player's allowed WorldEdit region * diff --git a/worldedit-core/src/main/java/com/boydti/fawe/config/BBC.java b/worldedit-core/src/main/java/com/boydti/fawe/config/BBC.java index b47350b6c..0b733b015 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/config/BBC.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/config/BBC.java @@ -4,13 +4,14 @@ import com.boydti.fawe.Fawe; import com.boydti.fawe.configuration.MemorySection; import com.boydti.fawe.configuration.file.YamlConfiguration; import com.boydti.fawe.object.FawePlayer; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.RunnableVal3; import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.StringMan; import com.boydti.fawe.util.chat.Message; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; +import com.sk89q.worldedit.entity.Player; + import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java index 2c7adbf36..1ccdcb03f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java @@ -595,11 +595,11 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr continue; } placed.add(x, z); - ClipboardHolder holder = clipboards.get(PseudoRandom.random.random(clipboards.size())); + ClipboardHolder holder = clipboards.get(ThreadLocalRandom.current().nextInt(clipboards.size())); if (randomRotate) { - int rotate = PseudoRandom.random.random(4) * 90; + int rotate = ThreadLocalRandom.current().nextInt(4) * 90; if (rotate != 0) { - holder.setTransform(new AffineTransform().rotateY(PseudoRandom.random.random(4) * 90)); + holder.setTransform(new AffineTransform().rotateY(ThreadLocalRandom.current().nextInt(4) * 90)); } else { holder.setTransform(identity); } @@ -644,11 +644,11 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr } mutable.mutY(y + 1); placed.add(x, z); - ClipboardHolder holder = clipboards.get(PseudoRandom.random.random(clipboards.size())); + ClipboardHolder holder = clipboards.get(ThreadLocalRandom.current().nextInt(clipboards.size())); if (randomRotate) { - int rotate = PseudoRandom.random.random(4) * 90; + int rotate = ThreadLocalRandom.current().nextInt(4) * 90; if (rotate != 0) { - holder.setTransform(new AffineTransform().rotateY(PseudoRandom.random.random(4) * 90)); + holder.setTransform(new AffineTransform().rotateY(ThreadLocalRandom.current().nextInt(4) * 90)); } else { holder.setTransform(identity); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java index 76cbdb05f..db2971b0e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java @@ -1,6 +1,5 @@ package com.boydti.fawe.jnbt.anvil.generator; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/GenBase.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/GenBase.java index c3adeb880..9f8c67c24 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/GenBase.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/GenBase.java @@ -1,6 +1,5 @@ package com.boydti.fawe.jnbt.anvil.generator; -import com.boydti.fawe.object.PseudoRandom; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.math.BlockVector2; @@ -10,12 +9,10 @@ import java.util.concurrent.ThreadLocalRandom; public abstract class GenBase { private final int checkAreaSize; - private final PseudoRandom random; private final long seed; private final long worldSeed1, worldSeed2; public GenBase(int area) { - this.random = new PseudoRandom(); this.checkAreaSize = area; this.seed = ThreadLocalRandom.current().nextLong(); this.worldSeed1 = ThreadLocalRandom.current().nextLong(); @@ -26,10 +23,6 @@ public abstract class GenBase { return checkAreaSize; } - public PseudoRandom getRandom() { - return random; - } - public void generate(BlockVector2 chunkPos, Extent chunk) throws WorldEditException { int i = this.checkAreaSize; int chunkX = chunkPos.getBlockX(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/Resource.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/Resource.java index 459596ca8..9ff294afd 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/Resource.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/Resource.java @@ -1,10 +1,8 @@ package com.boydti.fawe.jnbt.anvil.generator; -import com.boydti.fawe.object.PseudoRandom; import com.sk89q.worldedit.WorldEditException; import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; public abstract class Resource { public Resource() {} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/SchemGen.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/SchemGen.java index a404b38e5..3cb58d0af 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/SchemGen.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/SchemGen.java @@ -1,6 +1,5 @@ package com.boydti.fawe.jnbt.anvil.generator; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.schematic.Schematic; import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.WorldEditException; @@ -12,6 +11,7 @@ import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.session.ClipboardHolder; import java.util.List; import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; public class SchemGen extends Resource { @@ -40,9 +40,9 @@ public class SchemGen extends Resource { return false; } mutable.mutY(y + 1); - ClipboardHolder holder = clipboards.get(PseudoRandom.random.random(clipboards.size())); + ClipboardHolder holder = clipboards.get(ThreadLocalRandom.current().nextInt(clipboards.size())); if (randomRotate) { - holder.setTransform(new AffineTransform().rotateY(PseudoRandom.random.random(4) * 90)); + holder.setTransform(new AffineTransform().rotateY(ThreadLocalRandom.current().nextInt(4) * 90)); } Clipboard clipboard = holder.getClipboard(); Schematic schematic = new Schematic(clipboard); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java b/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java index 321c24285..c8b79ea2f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java @@ -506,7 +506,8 @@ public abstract class FawePlayer extends Metadatable { * @return */ public LocalSession getSession() { - return (this.session != null || this.getPlayer() == null || Fawe.get() == null) ? this.session : (session = Fawe.get().getWorldEdit().getSessionManager().get(this.getPlayer())); + if (this.session != null || this.getPlayer() == null || Fawe.get() == null) return this.session; + else return session = Fawe.get().getWorldEdit().getSessionManager().get(this.getPlayer()); } /** @@ -662,7 +663,8 @@ public abstract class FawePlayer extends Metadatable { PlayerProxy proxy = new PlayerProxy(player, permActor, cuiActor, world); if (world instanceof VirtualWorld) { - proxy.setOffset(Vector3.ZERO.subtract(((VirtualWorld) world).getOrigin())); + //todo fix this + //proxy.setOffset(Vector3.ZERO.subtract(((VirtualWorld) world).getOrigin())); } return proxy; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/Metadatable.java b/worldedit-core/src/main/java/com/boydti/fawe/object/Metadatable.java index 83a9f55e9..266cc2232 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/Metadatable.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/Metadatable.java @@ -33,10 +33,7 @@ public class Metadatable { * @return */ public V getMeta(String key) { - if (this.meta != null) { - return (V) this.meta.get(key); - } - return null; + return (V) this.meta.get(key); } /** @@ -48,11 +45,8 @@ public class Metadatable { * @return */ public V getMeta(String key, V def) { - if (this.meta != null) { - V value = (V) this.meta.get(key); - return value == null ? def : value; - } - return def; + V value = (V) this.meta.get(key); + return value == null ? def : value; } /** @@ -63,6 +57,6 @@ public class Metadatable { * @param key */ public V deleteMeta(String key) { - return this.meta == null ? null : (V) this.meta.remove(key); + return (V) this.meta.remove(key); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/PseudoRandom.java b/worldedit-core/src/main/java/com/boydti/fawe/object/PseudoRandom.java deleted file mode 100644 index dabda02d6..000000000 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/PseudoRandom.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.boydti.fawe.object; - -import java.util.concurrent.ThreadLocalRandom; - -@Deprecated -/** - * @Deprecated use ThreadLocalRandom instead - */ -public class PseudoRandom { - public static PseudoRandom random = new PseudoRandom(); - - public PseudoRandom() { - } - - public int random(final int n) { - if (n == 1) { - return 0; - } - final long r = ((ThreadLocalRandom.current().nextLong() >>> 32) * n) >> 32; - return (int) r; - } - -} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ErodeBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ErodeBrush.java index 36f90aeff..2d65de252 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ErodeBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ErodeBrush.java @@ -1,27 +1,20 @@ package com.boydti.fawe.object.brush; -import com.boydti.fawe.FaweCache; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.clipboard.CPUOptimizedClipboard; import com.boydti.fawe.object.clipboard.FaweClipboard; import com.boydti.fawe.object.clipboard.OffsetFaweClipboard; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.blocks.Blocks; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import java.util.Arrays; public class ErodeBrush implements Brush { - private PseudoRandom rand = new PseudoRandom(); - private static final BlockVector3[] FACES_TO_CHECK = {BlockVector3.at(0, 0, 1), BlockVector3.at(0, 0, -1), BlockVector3.at(0, 1, 0), BlockVector3.at(0, -1, 0), BlockVector3.at(1, 0, 0), BlockVector3.at(-1, 0, 0)}; @Override diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ShatterBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ShatterBrush.java index 6b4fb75c9..70360ad15 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ShatterBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ShatterBrush.java @@ -1,6 +1,5 @@ package com.boydti.fawe.object.brush; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.collection.LocalBlockVectorSet; import com.boydti.fawe.object.mask.SurfaceMask; import com.sk89q.worldedit.EditSession; @@ -12,6 +11,8 @@ import com.sk89q.worldedit.function.visitor.BreadthFirstSearch; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.MutableBlockVector3; +import java.util.concurrent.ThreadLocalRandom; + public class ShatterBrush extends ScatterBrush { private final MutableBlockVector3 mutable = new MutableBlockVector3(); @@ -61,7 +62,7 @@ public class ShatterBrush extends ScatterBrush { frontier.forEach(new LocalBlockVectorSet.BlockVectorSetVisitor() { @Override public void run(int x, int y, int z, int index) { - if (PseudoRandom.random.random(2) == 0) { + if (ThreadLocalRandom.current().nextInt(2) == 0) { finalTmp.add(x, y, z); return; } @@ -101,4 +102,4 @@ public class ShatterBrush extends ScatterBrush { } } } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplatterBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplatterBrush.java index 7b2e7f3ce..299d8fdcc 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplatterBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplatterBrush.java @@ -1,21 +1,20 @@ package com.boydti.fawe.object.brush; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.collection.LocalBlockVectorSet; import com.boydti.fawe.object.mask.SurfaceMask; import com.boydti.fawe.object.pattern.BiomePattern; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.SolidBlockMask; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.function.visitor.BreadthFirstSearch; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; import com.sk89q.worldedit.math.BlockVector3; import java.util.Arrays; +import java.util.concurrent.ThreadLocalRandom; public class SplatterBrush extends ScatterBrush { private final boolean solid; @@ -45,25 +44,17 @@ public class SplatterBrush extends ScatterBrush { SurfaceMask surface = new SurfaceMask(editSession); final SolidBlockMask solid = new SolidBlockMask(editSession); - RecursiveVisitor visitor = new RecursiveVisitor(new Mask() { - @Override - public boolean test(BlockVector3 vector) { - double dist = vector.distanceSq(position); - if (dist < size2 && !placed.contains(vector) && (PseudoRandom.random.random(5) < 2) && surface.test(vector)) { - placed.add(vector); - return true; - } - return false; + RecursiveVisitor visitor = new RecursiveVisitor(vector -> { + double dist = vector.distanceSq(position); + if (dist < size2 && !placed.contains(vector) && (ThreadLocalRandom.current().nextInt(5) < 2) && surface.test(vector)) { + placed.add(vector); + return true; } - }, new RegionFunction() { - @Override - public boolean apply(BlockVector3 vector) throws WorldEditException { - return editSession.setBlock(vector, finalPattern); - } - }, recursion, editSession); + return false; + }, vector -> editSession.setBlock(vector, finalPattern), recursion, editSession); visitor.setMaxBranch(2); - visitor.setDirections(Arrays.asList(visitor.DIAGONAL_DIRECTIONS)); + visitor.setDirections(Arrays.asList(BreadthFirstSearch.DIAGONAL_DIRECTIONS)); visitor.visit(position); Operations.completeBlindly(visitor); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/StencilBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/StencilBrush.java index fbd2b5158..15f6316b3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/StencilBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/StencilBrush.java @@ -1,6 +1,5 @@ package com.boydti.fawe.object.brush; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.brush.heightmap.HeightMap; import com.boydti.fawe.object.mask.AdjacentAnyMask; import com.boydti.fawe.util.MathMan; @@ -13,14 +12,17 @@ import com.sk89q.worldedit.function.mask.Masks; import com.sk89q.worldedit.function.mask.SolidBlockMask; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.function.visitor.BreadthFirstSearch; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.MutableVector3; import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.util.Location; + import java.io.InputStream; import java.util.Arrays; +import java.util.concurrent.ThreadLocalRandom; public class StencilBrush extends HeightBrush { private final boolean onlyWhite; @@ -53,7 +55,7 @@ public class StencilBrush extends HeightBrush { Player player = editSession.getPlayer().getPlayer(); -// BlockVector3 pos = player.getLocation(); + // BlockVector3 pos = player.getLocation(); @@ -84,7 +86,7 @@ public class StencilBrush extends HeightBrush { if (val < cutoff) { return true; } - if (val >= 255 || PseudoRandom.random.random(maxY) < val) { + if (val >= 255 || ThreadLocalRandom.current().nextInt(maxY) < val) { editSession.setBlock(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ(), pattern); } return true; @@ -92,7 +94,7 @@ public class StencilBrush extends HeightBrush { return false; } }, vector -> true, Integer.MAX_VALUE, editSession); - visitor.setDirections(Arrays.asList(visitor.DIAGONAL_DIRECTIONS)); + visitor.setDirections(Arrays.asList(BreadthFirstSearch.DIAGONAL_DIRECTIONS)); visitor.visit(position); Operations.completeBlindly(visitor); } @@ -100,4 +102,4 @@ public class StencilBrush extends HeightBrush { private void apply(double val) { } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/HeightMap.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/HeightMap.java index 0e07d6eb6..70f5282dc 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/HeightMap.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/HeightMap.java @@ -1,6 +1,5 @@ package com.boydti.fawe.object.brush.heightmap; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.util.MainUtil; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; @@ -12,6 +11,8 @@ import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; +import java.util.concurrent.ThreadLocalRandom; + public interface HeightMap { public double getHeight(int x, int z); @@ -108,7 +109,7 @@ public interface HeightMap { int diff = targetY - height; double raiseScaled = diff * (raisePow * sizePowInv); double raiseScaledAbs = Math.abs(raiseScaled); - int random = PseudoRandom.random.random(256) < (int) ((Math.ceil(raiseScaledAbs) - Math.floor(raiseScaledAbs)) * 256) ? (diff > 0 ? 1 : -1) : 0; + int random = ThreadLocalRandom.current().nextInt(256) < (int) ((Math.ceil(raiseScaledAbs) - Math.floor(raiseScaledAbs)) * 256) ? (diff > 0 ? 1 : -1) : 0; int raiseScaledInt = (int) raiseScaled + random; newData[index] = height + raiseScaledInt; } @@ -148,7 +149,7 @@ public interface HeightMap { continue; } raise = (yscale * raise); - int random = PseudoRandom.random.random(256) < (int) ((raise - (int) raise) * (256)) ? 1 : 0; + int random = ThreadLocalRandom.current().nextInt(256) < (int) ((raise - (int) raise) * (256)) ? 1 : 0; int newHeight = height + (int) raise + random; newData[index] = newHeight; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/ScrollClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/ScrollClipboard.java index f6275bc72..1c381feeb 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/ScrollClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/ScrollClipboard.java @@ -10,7 +10,7 @@ import java.util.List; public class ScrollClipboard extends ScrollAction { private final List clipboards; private final LocalSession session; - int index = 0; + private int index = 0; public ScrollClipboard(BrushTool tool, LocalSession session, List clipboards) { super(tool); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualQueue.java index a5feb905b..b0e6d2bf3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualQueue.java @@ -20,7 +20,6 @@ public class VisualQueue extends SingleThreadIntervalQueue { LocalSession session = fp.getSession(); Player player = fp.getPlayer(); Tool tool = session.getTool(player); - Brush brush; if (tool instanceof BrushTool) { BrushTool brushTool = (BrushTool) tool; if (brushTool.getVisualMode() != VisualMode.NONE) { @@ -32,4 +31,4 @@ public class VisualQueue extends SingleThreadIntervalQueue { } } } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/FaweBlockMatcher.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/FaweBlockMatcher.java index a2c768b35..b05ad4ef5 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/FaweBlockMatcher.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/FaweBlockMatcher.java @@ -1,9 +1,7 @@ package com.boydti.fawe.object.mask; -import com.boydti.fawe.FaweCache; -import com.boydti.fawe.object.PseudoRandom; import com.sk89q.worldedit.world.block.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; + import java.util.Set; // TODO FIXME diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomFullClipboardPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomFullClipboardPattern.java index 36c3eb08c..d49ca03ab 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomFullClipboardPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomFullClipboardPattern.java @@ -1,10 +1,8 @@ package com.boydti.fawe.object.pattern; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.schematic.Schematic; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.world.block.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.pattern.AbstractPattern; @@ -17,6 +15,7 @@ import com.sk89q.worldedit.session.ClipboardHolder; import java.io.IOException; import java.io.NotSerializableException; import java.util.List; +import java.util.concurrent.ThreadLocalRandom; import static com.google.common.base.Preconditions.checkNotNull; @@ -37,11 +36,11 @@ public class RandomFullClipboardPattern extends AbstractPattern { @Override public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { - ClipboardHolder holder = clipboards.get(PseudoRandom.random.random(clipboards.size())); + ClipboardHolder holder = clipboards.get(ThreadLocalRandom.current().nextInt(clipboards.size())); AffineTransform transform = new AffineTransform(); if (randomRotate) { - transform = transform.rotateY(PseudoRandom.random.random(4) * 90); - holder.setTransform(new AffineTransform().rotateY(PseudoRandom.random.random(4) * 90)); + transform = transform.rotateY(ThreadLocalRandom.current().nextInt(4) * 90); + holder.setTransform(new AffineTransform().rotateY(ThreadLocalRandom.current().nextInt(4) * 90)); } if (randomFlip) { transform = transform.scale(Vector3.at(1, 0, 0).multiply(-2).add(1, 1, 1)); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/visualizer/SchemVis.java b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/visualizer/SchemVis.java index 41dbae0c1..cf393791c 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/visualizer/SchemVis.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/visualizer/SchemVis.java @@ -1,647 +1,622 @@ -package com.boydti.fawe.object.schematic.visualizer; - -import com.boydti.fawe.config.BBC; -import com.boydti.fawe.jnbt.anvil.MCAChunk; -import com.boydti.fawe.jnbt.anvil.MCAQueue; -import com.boydti.fawe.object.*; -import com.boydti.fawe.object.brush.visualization.ImmutableVirtualWorld; -import com.boydti.fawe.object.clipboard.LazyClipboardHolder; -import com.boydti.fawe.object.clipboard.MultiClipboardHolder; -import com.boydti.fawe.object.clipboard.URIClipboardHolder; -import com.boydti.fawe.object.exception.FaweException; -import com.boydti.fawe.object.io.NonCloseableInputStream; -import com.boydti.fawe.object.queue.LazyFaweChunk; -import com.boydti.fawe.object.schematic.Schematic; -import com.boydti.fawe.util.*; -import com.google.common.io.ByteSource; -import com.google.common.io.Files; -import com.sk89q.jnbt.NBTInputStream; -import com.sk89q.jnbt.NBTOutputStream; -import com.sk89q.worldedit.*; -import com.sk89q.worldedit.entity.Player; -import com.sk89q.worldedit.event.platform.InputType; -import com.sk89q.worldedit.event.platform.PlayerInputEvent; -import com.sk89q.worldedit.extent.clipboard.Clipboard; -import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; -import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; -import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; -import com.sk89q.worldedit.math.BlockVector2; -import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldedit.math.MutableBlockVector2; -import com.sk89q.worldedit.math.Vector3; -import com.sk89q.worldedit.session.ClipboardHolder; -import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.util.TargetBlock; -import com.sk89q.worldedit.world.biome.BiomeType; -import com.sk89q.worldedit.world.biome.BiomeTypes; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockTypes; -import it.unimi.dsi.fastutil.longs.Long2ObjectMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectIterator; - -import java.io.*; -import java.net.URI; -import java.nio.file.LinkOption; -import java.nio.file.Path; -import java.util.*; - -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * An Immutable virtual world used to display & select schematics - */ -public class SchemVis extends ImmutableVirtualWorld { - private static final WeakHashMap DIMENSION_CACHE = new WeakHashMap<>(); - - private final Long2ObjectOpenHashMap> files; - private final Long2ObjectOpenHashMap chunks; // TODO use soft references OR clear chunks outside view distance - - private final MutableBlockVector2 lastPos = new MutableBlockVector2(); - private final FawePlayer player; - private final Location origin; - private final BlockVector2 chunkOffset; - private BlockVector2 lastPosition; - - public static SchemVis create(FawePlayer player, Collection files) throws IOException { - checkNotNull(player); - checkNotNull(files); - SchemVis visExtent = new SchemVis(player); - for (File file : files) { - visExtent.add(file); - } - visExtent.bind(); - visExtent.update(); - return visExtent; - } - - public SchemVis(FawePlayer player) { - this.files = new Long2ObjectOpenHashMap<>(); - this.chunks = new Long2ObjectOpenHashMap<>(); - this.player = player; - - // Set the origin to somewhere around where the player currently is - FaweLocation pos = player.getLocation(); - this.origin = player.getPlayer().getLocation(); - this.chunkOffset = BlockVector2.at(pos.x >> 4,pos.z >> 4); - } - - private Set getFiles(BlockVector2 chunkPosA, BlockVector2 chunkPosB) { - BlockVector2 pos1 = BlockVector2.at(Math.min(chunkPosA.getBlockX(), chunkPosB.getBlockX()), Math.min(chunkPosA.getBlockZ(), chunkPosB.getBlockZ())); - BlockVector2 pos2 = BlockVector2.at(Math.max(chunkPosA.getBlockX(), chunkPosB.getBlockX()), Math.max(chunkPosA.getBlockZ(), chunkPosB.getBlockZ())); - Set contained = new HashSet<>(); - for (Long2ObjectMap.Entry> entry : files.long2ObjectEntrySet()) { - long key = entry.getLongKey(); - int chunkX = MathMan.unpairIntX(key); - if (chunkX < pos1.getBlockX() || chunkX > pos2.getBlockX()) continue; - int chunkZ = MathMan.unpairIntY(key); - if (chunkZ < pos1.getBlockZ() || chunkZ > pos2.getBlockZ()) continue; - contained.add(entry.getValue().getKey()); - - } - return contained; - } - - private File getRealFile(File cached) { - String fileName = cached.getName(); - return new File(cached.getParentFile(), fileName.substring(1, fileName.length() - 7)); - } - - @Override - public void handlePlayerInput(Player player, PlayerInputEvent event) { - int range = 240; - Location target = new TargetBlock(player, range, 0.2).getAnyTargetBlock(); - if (target != null) { - int chunkX = target.getBlockX() >> 4; - int chunkZ = target.getBlockZ() >> 4; - long pos = MathMan.pairInt(chunkX, chunkZ); - Map.Entry entry = files.get(pos); - if (entry != null) { - File cachedFile = entry.getKey(); - String filename = cachedFile.getName(); - - LocalSession session = this.player.getSession(); - synchronized (this) { - try { - BlockVector2 tmpLastPosition = lastPosition; - lastPosition = BlockVector2.at(chunkX, chunkZ); - - boolean sneaking = this.player.isSneaking(); - if (event.getInputType() == InputType.PRIMARY && !sneaking) { - - File file = new File(cachedFile.getParentFile(), filename.substring(1, filename.length() - 7)); - URI uri = file.toURI(); - ClipboardFormat format = ClipboardFormats.findByFile(file); - format.hold(player, uri, new FileInputStream(file)); - BBC.SCHEMATIC_LOADED.send(player, filename); - session.setVirtualWorld(null); - return; - } - Set toSelect; - if (sneaking && tmpLastPosition != null) toSelect = getFiles(tmpLastPosition, lastPosition); - else toSelect = Collections.singleton(cachedFile); - - Map select = new HashMap<>(); - for (File clicked : toSelect) { - ClipboardHolder existing = session.getExistingClipboard(); - - File file = new File(clicked.getParentFile(), filename.substring(1, filename.length() - 7)); - URI uri = file.toURI(); - ClipboardFormat format = ClipboardFormats.findByFile(file); - - boolean contains = existing instanceof URIClipboardHolder && ((URIClipboardHolder) existing).contains(uri); - if (contains) { - if (!sneaking) { - // Remove it - if (existing instanceof MultiClipboardHolder) { - MultiClipboardHolder multi = ((MultiClipboardHolder) existing); - multi.remove(uri); - if (multi.getClipboards().isEmpty()) session.setClipboard(null); - } else { - session.setClipboard(null); - } - select.put(clicked, false); - BBC.CLIPBOARD_CLEARED.send(player); - } - } else { - // Add it - ByteSource source = Files.asByteSource(file); - MultiClipboardHolder multi = new MultiClipboardHolder(URI.create(""), new LazyClipboardHolder(uri, source, format, null)); - session.addClipboard(multi); - select.put(clicked, true); - BBC.SCHEMATIC_LOADED.send(player, file.getName()); - } - } - // Resend relevant chunks - FaweQueue packetQueue = SetQueue.IMP.getNewQueue(this.player.getWorld(), true, false); - if (packetQueue.supports(Capability.CHUNK_PACKETS)) { - ArrayDeque toSend = new ArrayDeque<>(); - int OX = chunkOffset.getBlockX(); - int OZ = chunkOffset.getBlockZ(); - ObjectIterator> iter = chunks.long2ObjectEntrySet().fastIterator(); - while (iter.hasNext()) { - Long2ObjectMap.Entry mcaChunkEntry = iter.next(); - long curChunkPos = mcaChunkEntry.getLongKey(); - Map.Entry curFileEntry = files.get(curChunkPos); - if (curFileEntry != null) { - Boolean selected = select.get(curFileEntry.getKey()); - if (selected != null) { - if (!selected) { - iter.remove(); - } else { - select(mcaChunkEntry.getValue()); - } - toSend.add(curChunkPos); - } - } - } - for (long curChunkPos : toSend) send(packetQueue, MathMan.unpairIntX(curChunkPos), MathMan.unpairIntY(curChunkPos)); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - } - } - - /** - * Discard chunks outside FOV - */ - private void clean() { - if (chunks.size() > 225) { - TaskManager.IMP.sync(() -> { - if (chunks.size() > 225) { - synchronized (SchemVis.this) { - FaweLocation pos = player.getLocation(); - int centerX = pos.getX() >> 4; - int centerZ = pos.getZ() >> 4; - ObjectIterator> iter = chunks.long2ObjectEntrySet().fastIterator(); - while (iter.hasNext()) { - Long2ObjectMap.Entry entry = iter.next(); - long pair = entry.getLongKey(); - int chunkX = MathMan.unpairIntX(pair); - int chunkZ = MathMan.unpairIntY(pair); - if (Math.abs(centerX - chunkX) > 15 || Math.abs(centerZ - chunkZ) > 15) { - iter.remove(); - } - } - } - } - return null; - }); - } - } - - /** - * Send a chunk - * @param packetQueue - * @param chunkX - * @param chunkZ - */ - private void send(FaweQueue packetQueue, int chunkX, int chunkZ) { - TaskManager.IMP.getPublicForkJoinPool().submit(() -> { - try { - int OX = chunkOffset.getBlockX(); - int OZ = chunkOffset.getBlockZ(); - FaweChunk toSend = getSnapshot(chunkX, chunkZ); - toSend.setLoc(SchemVis.this, chunkX + OX, chunkZ + OZ); - packetQueue.sendChunkUpdate(toSend, SchemVis.this.player); - } catch (Throwable e) { - e.printStackTrace(); - } - }); - } - - /** - * The offset for this virtual world - * @return offset vector - */ - @Override - public Vector3 getOrigin() { - return Vector3.at(chunkOffset.getBlockX() << 4, 0, chunkOffset.getBlockZ() << 4); - } - - /** - * @param chunkX - * @param chunkZ - * @return The schematic file visualized at a chunk position - */ - private File getFile(int chunkX, int chunkZ) { - long pair = MathMan.pairInt(chunkX, chunkZ); - Map.Entry entry = files.get(pair); - return entry != null ? entry.getKey() : null; - } - - private Map.Entry getEntry(File file, long position) { - return new AbstractMap.SimpleEntry<>(file, position); - } - - /** - * Replace the blocks with glass, to indicate it's been selected - * @param chunk - */ - private void select(MCAChunk chunk) { - for (int layer = 0; layer < 16; layer++) { - int[] ids = chunk.ids[layer]; - if (ids != null) { - for (int i = 0; i < ids.length; i++) { - // TODO FIXME update to 1.13 - if (ids[i] != 0) ids[i] = (byte) BlockTypes.WHITE_STAINED_GLASS.getInternalId(); - } - } - } - } - - /** - * Cache a chunk - * @param file - * @param chunk - */ - private void cacheChunk(File file, MCAChunk chunk, boolean selected) { - long pair = MathMan.pairInt(chunk.getX(), chunk.getZ()); - // Light chunk - for (int layer = 0; layer < 16; layer++) { - if (chunk.skyLight[layer] != null) { - Arrays.fill(chunk.skyLight[layer], (byte) 255); - } - } - if (selected) { - select(chunk); - } - synchronized (this) { - chunks.put(pair, chunk); - } - } - - /** - * Get the next free position for a schematic of the provided dimensions - * @param schemDimensions - * @return - */ - private BlockVector2 registerAndGetChunkOffset(BlockVector2 schemDimensions, File file) { - int chunkX = schemDimensions.getBlockX() >> 4; - int chunkZ = schemDimensions.getBlockZ() >> 4; - MutableBlockVector2 pos2 = new MutableBlockVector2(); - MutableBlockVector2 curPos = lastPos; - // Find next free position - while (!isAreaFree(curPos, pos2.setComponents(curPos.getBlockX() + chunkX, curPos.getBlockZ() + chunkZ))) { -// if (curPos == lastPos && !files.containsKey(MathMan.pairInt(curPos.getBlockX(), curPos.getBlockZ()))) { -// curPos = new MutableBlockVector2(); -// curPos.setComponents(lastPos.getBlockX(), lastPos.getBlockZ()); +//package com.boydti.fawe.object.schematic.visualizer; +// +//import com.boydti.fawe.config.BBC; +//import com.boydti.fawe.jnbt.anvil.MCAChunk; +//import com.boydti.fawe.jnbt.anvil.MCAQueue; +//import com.boydti.fawe.object.*; +//import com.boydti.fawe.object.brush.visualization.ImmutableVirtualWorld; +//import com.boydti.fawe.object.clipboard.LazyClipboardHolder; +//import com.boydti.fawe.object.clipboard.MultiClipboardHolder; +//import com.boydti.fawe.object.clipboard.URIClipboardHolder; +//import com.boydti.fawe.object.exception.FaweException; +//import com.boydti.fawe.object.io.NonCloseableInputStream; +//import com.boydti.fawe.object.queue.LazyFaweChunk; +//import com.boydti.fawe.object.schematic.Schematic; +//import com.boydti.fawe.util.*; +//import com.google.common.io.ByteSource; +//import com.google.common.io.Files; +//import com.sk89q.jnbt.NBTInputStream; +//import com.sk89q.jnbt.NBTOutputStream; +//import com.sk89q.worldedit.*; +//import com.sk89q.worldedit.entity.Player; +//import com.sk89q.worldedit.event.platform.InputType; +//import com.sk89q.worldedit.event.platform.PlayerInputEvent; +//import com.sk89q.worldedit.extent.clipboard.Clipboard; +//import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +//import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; +//import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; +//import com.sk89q.worldedit.math.BlockVector2; +//import com.sk89q.worldedit.math.BlockVector3; +//import com.sk89q.worldedit.math.MutableBlockVector2; +//import com.sk89q.worldedit.math.Vector3; +//import com.sk89q.worldedit.session.ClipboardHolder; +//import com.sk89q.worldedit.util.Location; +//import com.sk89q.worldedit.util.TargetBlock; +//import com.sk89q.worldedit.world.biome.BiomeType; +//import com.sk89q.worldedit.world.biome.BiomeTypes; +//import com.sk89q.worldedit.world.block.BlockState; +//import com.sk89q.worldedit.world.block.BlockTypes; +//import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +//import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +//import it.unimi.dsi.fastutil.objects.ObjectIterator; +// +//import java.io.*; +//import java.net.URI; +//import java.nio.file.LinkOption; +//import java.nio.file.Path; +//import java.util.*; +// +//import static com.google.common.base.Preconditions.checkNotNull; +// +///** +// * An Immutable virtual world used to display & select schematics +// */ +//public class SchemVis extends ImmutableVirtualWorld { +// private static final WeakHashMap DIMENSION_CACHE = new WeakHashMap<>(); +// +// private final Long2ObjectOpenHashMap> files; +// private final Long2ObjectOpenHashMap chunks; // TODO use soft references OR clear chunks outside view distance +// +// private final MutableBlockVector2 lastPos = new MutableBlockVector2(); +// private final FawePlayer player; +// private final Location origin; +// private final BlockVector2 chunkOffset; +// private BlockVector2 lastPosition; +// +// public static SchemVis create(FawePlayer player, Collection files) throws IOException { +// checkNotNull(player); +// checkNotNull(files); +// SchemVis visExtent = new SchemVis(player); +// for (File file : files) { +// visExtent.add(file); +// } +// visExtent.bind(); +// visExtent.update(); +// return visExtent; +// } +// +// public SchemVis(FawePlayer player) { +// this.files = new Long2ObjectOpenHashMap<>(); +// this.chunks = new Long2ObjectOpenHashMap<>(); +// this.player = player; +// +// // Set the origin to somewhere around where the player currently is +// Location pos = player.toWorldEditPlayer().getLocation(); +// this.origin = player.getPlayer().getLocation(); +// this.chunkOffset = BlockVector2.at(pos.getBlockX() >> 4,pos.getBlockZ() >> 4); +// } +// +// private Set getFiles(BlockVector2 chunkPosA, BlockVector2 chunkPosB) { +// BlockVector2 pos1 = BlockVector2.at(Math.min(chunkPosA.getBlockX(), chunkPosB.getBlockX()), Math.min(chunkPosA.getBlockZ(), chunkPosB.getBlockZ())); +// BlockVector2 pos2 = BlockVector2.at(Math.max(chunkPosA.getBlockX(), chunkPosB.getBlockX()), Math.max(chunkPosA.getBlockZ(), chunkPosB.getBlockZ())); +// Set contained = new HashSet<>(); +// for (Long2ObjectMap.Entry> entry : files.long2ObjectEntrySet()) { +// long key = entry.getLongKey(); +// int chunkX = MathMan.unpairIntX(key); +// if (chunkX < pos1.getBlockX() || chunkX > pos2.getBlockX()) continue; +// int chunkZ = MathMan.unpairIntY(key); +// if (chunkZ < pos1.getBlockZ() || chunkZ > pos2.getBlockZ()) continue; +// contained.add(entry.getValue().getKey()); +// +// } +// return contained; +// } +// +// @Override +// public void handlePlayerInput(Player player, PlayerInputEvent event) { +// int range = 240; +// Location target = new TargetBlock(player, range, 0.2).getAnyTargetBlock(); +// if (target != null) { +// int chunkX = target.getBlockX() >> 4; +// int chunkZ = target.getBlockZ() >> 4; +// long pos = MathMan.pairInt(chunkX, chunkZ); +// Map.Entry entry = files.get(pos); +// if (entry != null) { +// File cachedFile = entry.getKey(); +// String filename = cachedFile.getName(); +// +// LocalSession session = this.player.getSession(); +// synchronized (this) { +// try { +// BlockVector2 tmpLastPosition = lastPosition; +// lastPosition = BlockVector2.at(chunkX, chunkZ); +// +// boolean sneaking = this.player.isSneaking(); +// if (event.getInputType() == InputType.PRIMARY && !sneaking) { +// +// File file = new File(cachedFile.getParentFile(), filename.substring(1, filename.length() - 7)); +// URI uri = file.toURI(); +// ClipboardFormat format = ClipboardFormats.findByFile(file); +// format.hold(player, uri, new FileInputStream(file)); +// BBC.SCHEMATIC_LOADED.send(player, filename); +// session.setVirtualWorld(null); +// return; +// } +// Set toSelect; +// if (sneaking && tmpLastPosition != null) toSelect = getFiles(tmpLastPosition, lastPosition); +// else toSelect = Collections.singleton(cachedFile); +// +// Map select = new HashMap<>(); +// for (File clicked : toSelect) { +// ClipboardHolder existing = session.getExistingClipboard(); +// +// File file = new File(clicked.getParentFile(), filename.substring(1, filename.length() - 7)); +// URI uri = file.toURI(); +// ClipboardFormat format = ClipboardFormats.findByFile(file); +// +// boolean contains = existing instanceof URIClipboardHolder && ((URIClipboardHolder) existing).contains(uri); +// if (contains) { +// if (!sneaking) { +// // Remove it +// if (existing instanceof MultiClipboardHolder) { +// MultiClipboardHolder multi = ((MultiClipboardHolder) existing); +// multi.remove(uri); +// if (multi.getClipboards().isEmpty()) session.setClipboard(null); +// } else { +// session.setClipboard(null); +// } +// select.put(clicked, false); +// BBC.CLIPBOARD_CLEARED.send(player); +// } +// } else { +// // Add it +// ByteSource source = Files.asByteSource(file); +// MultiClipboardHolder multi = new MultiClipboardHolder(URI.create(""), new LazyClipboardHolder(uri, source, format, null)); +// session.addClipboard(multi); +// select.put(clicked, true); +// BBC.SCHEMATIC_LOADED.send(player, file.getName()); +// } +// } +// // Resend relevant chunks +// FaweQueue packetQueue = SetQueue.IMP.getNewQueue(this.player.getWorld(), true, false); +// if (packetQueue.supports(Capability.CHUNK_PACKETS)) { +// ArrayDeque toSend = new ArrayDeque<>(); +// ObjectIterator> iter = chunks.long2ObjectEntrySet().fastIterator(); +// while (iter.hasNext()) { +// Long2ObjectMap.Entry mcaChunkEntry = iter.next(); +// long curChunkPos = mcaChunkEntry.getLongKey(); +// Map.Entry curFileEntry = files.get(curChunkPos); +// if (curFileEntry != null) { +// Boolean selected = select.get(curFileEntry.getKey()); +// if (selected != null) { +// if (!selected) { +// iter.remove(); +// } else { +// select(mcaChunkEntry.getValue()); +// } +// toSend.add(curChunkPos); +// } +// } +// } +// for (long curChunkPos : toSend) send(packetQueue, MathMan.unpairIntX(curChunkPos), MathMan.unpairIntY(curChunkPos)); +// } +// } catch (IOException e) { +// throw new RuntimeException(e); +// } +// } // } - curPos.nextPosition(); - } - // Register the chunks - Map.Entry originValue = getEntry(file, MathMan.pairInt(curPos.getBlockX(), curPos.getBlockZ())); - long pairX, pos; - for (int x = 0; x <= chunkX; x++) { - int xx = curPos.getBlockX() + x; - pairX = ((long) xx) << 32; - for (int z = 0; z <= chunkZ; z++) { - int zz = curPos.getBlockZ() + z; - pos = pairX + (zz & 0xffffffffL); - files.put(pos, originValue); - } - } - for (int i = 0; i < Math.min(chunkX, chunkZ); i++) curPos.nextPosition(); - return curPos; - } - - private boolean isAreaFree(BlockVector2 chunkPos1, BlockVector2 chunkPos2 /* inclusive */) { - for (int x = chunkPos1.getBlockX(); x <= chunkPos2.getBlockX(); x++) { - for (int z = chunkPos1.getBlockZ(); z <= chunkPos2.getBlockZ(); z++) { - if (files.containsKey(MathMan.pairInt(x, z)) || (x == 0 && z == 0)) return false; - } - } - return true; - } - - private boolean isSelected(File file) { - ClipboardHolder clipboard = player.getSession().getExistingClipboard(); - if (clipboard != null) { - if (clipboard instanceof URIClipboardHolder) { - return ((URIClipboardHolder) clipboard).contains(file.toURI()); - } - } - return false; - } - - public void add(File file) throws IOException { - File cached = new File(file.getParentFile(), "." + file.getName() + ".cached"); - Integer dimensionPair = DIMENSION_CACHE.get(file); - if (dimensionPair != null) { - int width = (char) MathMan.unpairX(dimensionPair); - int length = (char) MathMan.unpairY(dimensionPair); - BlockVector2 dimensions = BlockVector2.at(width, length); - BlockVector2 offset = registerAndGetChunkOffset(dimensions, cached); - return; - } - if (cached.exists() && file.lastModified() <= cached.lastModified()) { - try (InputStream fis = new BufferedInputStream(new FileInputStream(cached), 4)) { - BlockVector2 dimensions = BlockVector2.at(IOUtil.readVarInt(fis), IOUtil.readVarInt(fis)); - DIMENSION_CACHE.put(file, MathMan.pair((short) dimensions.getBlockX(), (short) dimensions.getBlockZ())); - BlockVector2 offset = registerAndGetChunkOffset(dimensions, cached); - } - } else { - try { - player.sendMessage(BBC.getPrefix() + "Converting: " + file); - cached.createNewFile(); - try (FileInputStream in = new FileInputStream(file)) { - ClipboardFormat format = ClipboardFormats.findByFile(file); - if (format != null) { - ClipboardReader reader = format.getReader(in); - Clipboard clipboard = reader.read(); - clipboard.setOrigin(clipboard.getMinimumPoint()); - try { - MCAQueue queue = new MCAQueue(null, null, false); - BlockVector2 dimensions = clipboard.getDimensions().toBlockVector2(); - BlockVector2 offset = registerAndGetChunkOffset(dimensions, cached); - new Schematic(clipboard).paste(queue, BlockVector3.ZERO, true); - try (FileOutputStream fos = new FileOutputStream(cached)) { - IOUtil.writeVarInt(fos, dimensions.getBlockX()); - IOUtil.writeVarInt(fos, dimensions.getBlockZ()); - - try (FaweOutputStream cos = MainUtil.getCompressedOS(fos, 2)) { - NBTOutputStream nos = new NBTOutputStream((DataOutput) cos); - Collection writeChunks = queue.getFaweChunks(); - cos.writeInt(writeChunks.size()); - - boolean selected = isSelected(file); - - for (FaweChunk chunk : writeChunks) { - MCAChunk mcaChunk = ((MCAChunk) chunk); - mcaChunk.write(nos); - mcaChunk.setLoc(this, mcaChunk.getX() + offset.getBlockX(), mcaChunk.getZ() + offset.getBlockZ()); - if (Math.abs(mcaChunk.getX()) <= 15 && Math.abs(mcaChunk.getZ()) <= 15) { - cacheChunk(cached, mcaChunk, selected); - } - } - } - } - if (System.getProperty("os.name").contains("Windows")) { - Path path = cached.toPath(); - Object hidden = java.nio.file.Files.getAttribute(path, "dos:hidden", LinkOption.NOFOLLOW_LINKS); - if (hidden != null) { - //link file to DosFileAttributes - java.nio.file.Files.setAttribute(path, "dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS); - } - } - - DIMENSION_CACHE.put(file, MathMan.pair((short) dimensions.getBlockX(), (short) dimensions.getBlockZ())); - } finally { - if (clipboard instanceof Closeable) { - ((Closeable) clipboard).close(); - } - } - } - } - } catch (Throwable e) { - e.printStackTrace(); - cached.delete(); - } - } - } - - private synchronized MCAChunk getCachedChunk(int chunkX, int chunkZ) { - return chunks.get(MathMan.pairInt(chunkX, chunkZ)); - } - - private MCAChunk getChunk(int chunkX, int chunkZ) { - long pair = MathMan.pairInt(chunkX, chunkZ); - // Check cached - MCAChunk chunk = getCachedChunk(chunkX, chunkZ); - if (chunk != null) return chunk; - - // We need to cache it - Map.Entry entry = files.get(pair); - if (entry != null) { - File cached = entry.getKey(); - - // Guard caching by other threads - synchronized (cached) { - chunk = getCachedChunk(chunkX, chunkZ); - - // Read chunks from disk - if (chunk == null) { - clean(); - String filename = cached.getName(); - File file = new File(cached.getParentFile(), filename.substring(1, filename.length() - 7)); - boolean selected = isSelected(file); - - long origin = entry.getValue(); - int OCX = MathMan.unpairIntX(origin); - int OCZ = MathMan.unpairIntY(origin); - try { - try (FileInputStream fis = new FileInputStream(cached)) { - BlockVector2 dimensions = BlockVector2.at(IOUtil.readVarInt(fis), IOUtil.readVarInt(fis)); - try (FaweInputStream in = MainUtil.getCompressedIS(fis)) { - NonCloseableInputStream nonCloseable = new NonCloseableInputStream(in); - try (NBTInputStream nis = new NBTInputStream(nonCloseable)) { - - int numChunks = in.readInt(); - for (int i = 0; i < numChunks; i++) { - MCAChunk mcaChunk = new MCAChunk(nis, null, 0, 0, true); - mcaChunk.setLoc(this, mcaChunk.getX() + OCX, mcaChunk.getZ() + OCZ); - cacheChunk(cached, mcaChunk, selected); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } - // Return the cached chunk, or an empty one - chunk = getCachedChunk(chunkX, chunkZ); - if (chunk == null) { - // TODO use shared chunk - // TODO synchronize on sending chunk packet - cacheChunk(cached, chunk = new MCAChunk(this, chunkX, chunkZ), selected); - } - } - } - } else { - chunk = new MCAChunk(this, chunkX, chunkZ); - } - return chunk; - } - - /** - * Return a lazily evaluated chunk - * @param chunkX - * @param chunkZ - * @return lazy chunk - */ - @Override - public FaweChunk getSnapshot(int chunkX, int chunkZ) { - return new LazyFaweChunk(this, chunkX, chunkZ) { - @Override - public MCAChunk getChunk() { - MCAChunk tmp = SchemVis.this.getChunk(chunkX, chunkZ); - tmp.setLoc(SchemVis.this, getX(), getZ()); - return tmp; - } - - @Override - public void addToQueue() { - MCAChunk cached = getCachedChunk(); - if (cached != null) setChunk(cached); - } - }; - } - - @Override - public FawePlayer getPlayer() { - return player; - } - - public void bind() { - player.setVirtualWorld(this); - } - - /** - * Send all chunks to the player - */ - @Override - public void update() { - FaweQueue packetQueue = SetQueue.IMP.getNewQueue(player.getWorld(), true, false); - - if (!packetQueue.supports(Capability.CHUNK_PACKETS)) { - return; - } - - int OX = chunkOffset.getBlockX(); - int OZ = chunkOffset.getBlockZ(); - - FaweLocation position = player.getLocation(); - int pcx = (position.getX() >> 4) - OX; - int pcz = (position.getZ() >> 4) - OZ; - - int scx = pcx - 15; - int scz = pcz - 15; - int ecx = pcx + 15; - int ecz = pcz + 15; - - for (int cz = scz; cz <= ecz; cz++) { - for (int cx = scx; cx <= ecx; cx++) { - send(packetQueue, cx, cz); - } - } - } - - @Override - public void sendChunk(FaweChunk chunk) { /* do nothing - never used */ } - - @Override - public void sendChunk(int x, int z, int bitMask) { /* do nothing - never used*/ } - - @Override - public BiomeType getBiomeType(int x, int z) throws FaweException.FaweChunkLoadException { - // TODO later (currently not used) - return BiomeTypes.FOREST; - } - - @Override - public int getCombinedId4Data(int x, int y, int z) throws FaweException.FaweChunkLoadException { - MCAChunk chunk = getChunk(x >> 4, z >> 4); - if (y < 0 || y > 255) return 0; - return chunk.getBlockCombinedId(x & 15, y, z & 15); - } - - /** - * Closes this virtual world and sends the normal world chunks to the player - * @throws IOException - */ - @Override - public synchronized void close(boolean update) throws IOException { - clear(); - chunks.clear(); - files.clear(); - player.getPlayer().setPosition(origin, origin.getPitch(), origin.getYaw()); - if (update) { - FaweQueue packetQueue = SetQueue.IMP.getNewQueue(player.getWorld(), true, false); - - int OX = chunkOffset.getBlockX(); - int OZ = chunkOffset.getBlockZ(); - - FaweLocation position = player.getLocation(); - int pcx = (position.getX() >> 4) - OX; - int pcz = (position.getZ() >> 4) - OZ; - - int scx = pcx - 15; - int scz = pcz - 15; - int ecx = pcx + 15; - int ecz = pcz + 15; - - for (int cz = scz; cz <= ecz; cz++) { - for (int cx = scx; cx <= ecx; cx++) { - packetQueue.sendChunk(cx + OX, cz + OZ, 0); - } - } - } - } - - @Override - public boolean playEffect(Vector3 position, int type, int data) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean setBiome(BlockVector2 position, BiomeType biome) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean notifyAndLightBlock(BlockVector3 position, BlockState previousType) throws WorldEditException { - // TODO Auto-generated method stub - return false; - } - - @Override - public BlockVector3 getSpawnPosition() { - // TODO Auto-generated method stub - return null; - } -} +// } +// } +// +// /** +// * Discard chunks outside FOV +// */ +// private void clean() { +// if (chunks.size() > 225) { +// TaskManager.IMP.sync(() -> { +// if (chunks.size() > 225) { +// synchronized (SchemVis.this) { +// Location pos = player.toWorldEditPlayer().getLocation(); +// int centerX = pos.getBlockX() >> 4; +// int centerZ = pos.getBlockZ() >> 4; +// ObjectIterator> iter = chunks.long2ObjectEntrySet().fastIterator(); +// while (iter.hasNext()) { +// Long2ObjectMap.Entry entry = iter.next(); +// long pair = entry.getLongKey(); +// int chunkX = MathMan.unpairIntX(pair); +// int chunkZ = MathMan.unpairIntY(pair); +// if (Math.abs(centerX - chunkX) > 15 || Math.abs(centerZ - chunkZ) > 15) { +// iter.remove(); +// } +// } +// } +// } +// return null; +// }); +// } +// } +// +// /** +// * Send a chunk +// * @param packetQueue +// * @param chunkX +// * @param chunkZ +// */ +// private void send(FaweQueue packetQueue, int chunkX, int chunkZ) { +// TaskManager.IMP.getPublicForkJoinPool().submit(() -> { +// try { +// int OX = chunkOffset.getBlockX(); +// int OZ = chunkOffset.getBlockZ(); +// FaweChunk toSend = getSnapshot(chunkX, chunkZ); +// toSend.setLoc(SchemVis.this, chunkX + OX, chunkZ + OZ); +// packetQueue.sendChunkUpdate(toSend, SchemVis.this.player); +// } catch (Throwable e) { +// e.printStackTrace(); +// } +// }); +// } +// +// /** +// * The offset for this virtual world +// * @return offset vector +// */ +// @Override +// public Vector3 getOrigin() { +// return Vector3.at(chunkOffset.getBlockX() << 4, 0, chunkOffset.getBlockZ() << 4); +// } +// +// private Map.Entry getEntry(File file, long position) { +// return new AbstractMap.SimpleEntry<>(file, position); +// } +// +// /** +// * Replace the blocks with glass, to indicate it's been selected +// * @param chunk +// */ +// private void select(MCAChunk chunk) { +// for (int layer = 0; layer < 16; layer++) { +// int[] ids = chunk.ids[layer]; +// if (ids != null) { +// for (int i = 0; i < ids.length; i++) { +// // TODO FIXME update to 1.13 +// if (ids[i] != 0) ids[i] = (byte) BlockTypes.WHITE_STAINED_GLASS.getInternalId(); +// } +// } +// } +// } +// +// /** +// * Cache a chunk +// * @param chunk +// */ +// private void cacheChunk(MCAChunk chunk, boolean selected) { +// long pair = MathMan.pairInt(chunk.getX(), chunk.getZ()); +// // Light chunk +// for (int layer = 0; layer < 16; layer++) { +// if (chunk.skyLight[layer] != null) { +// Arrays.fill(chunk.skyLight[layer], (byte) 255); +// } +// } +// if (selected) { +// select(chunk); +// } +// synchronized (this) { +// chunks.put(pair, chunk); +// } +// } +// +// /** +// * Get the next free position for a schematic of the provided dimensions +// * @param schemDimensions +// * @return +// */ +// private BlockVector2 registerAndGetChunkOffset(BlockVector2 schemDimensions, File file) { +// int chunkX = schemDimensions.getBlockX() >> 4; +// int chunkZ = schemDimensions.getBlockZ() >> 4; +// MutableBlockVector2 pos2 = new MutableBlockVector2(); +// MutableBlockVector2 curPos = lastPos; +// // Find next free position +// while (!isAreaFree(curPos, pos2.setComponents(curPos.getBlockX() + chunkX, curPos.getBlockZ() + chunkZ))) { +//// if (curPos == lastPos && !files.containsKey(MathMan.pairInt(curPos.getBlockX(), curPos.getBlockZ()))) { +//// curPos = new MutableBlockVector2(); +//// curPos.setComponents(lastPos.getBlockX(), lastPos.getBlockZ()); +//// } +// curPos.nextPosition(); +// } +// // Register the chunks +// Map.Entry originValue = getEntry(file, MathMan.pairInt(curPos.getBlockX(), curPos.getBlockZ())); +// long pairX, pos; +// for (int x = 0; x <= chunkX; x++) { +// int xx = curPos.getBlockX() + x; +// pairX = ((long) xx) << 32; +// for (int z = 0; z <= chunkZ; z++) { +// int zz = curPos.getBlockZ() + z; +// pos = pairX + (zz & 0xffffffffL); +// files.put(pos, originValue); +// } +// } +// for (int i = 0; i < Math.min(chunkX, chunkZ); i++) curPos.nextPosition(); +// return curPos; +// } +// +// private boolean isAreaFree(BlockVector2 chunkPos1, BlockVector2 chunkPos2 /* inclusive */) { +// for (int x = chunkPos1.getBlockX(); x <= chunkPos2.getBlockX(); x++) { +// for (int z = chunkPos1.getBlockZ(); z <= chunkPos2.getBlockZ(); z++) { +// if (files.containsKey(MathMan.pairInt(x, z)) || (x == 0 && z == 0)) return false; +// } +// } +// return true; +// } +// +// private boolean isSelected(File file) { +// ClipboardHolder clipboard = player.getSession().getExistingClipboard(); +// if (clipboard != null) { +// if (clipboard instanceof URIClipboardHolder) { +// return ((URIClipboardHolder) clipboard).contains(file.toURI()); +// } +// } +// return false; +// } +// +// public void add(File file) throws IOException { +// File cached = new File(file.getParentFile(), "." + file.getName() + ".cached"); +// Integer dimensionPair = DIMENSION_CACHE.get(file); +// if (dimensionPair != null) { +// int width = (char) MathMan.unpairX(dimensionPair); +// int length = (char) MathMan.unpairY(dimensionPair); +// BlockVector2 dimensions = BlockVector2.at(width, length); +// BlockVector2 offset = registerAndGetChunkOffset(dimensions, cached); +// return; +// } +// if (cached.exists() && file.lastModified() <= cached.lastModified()) { +// try (InputStream fis = new BufferedInputStream(new FileInputStream(cached), 4)) { +// BlockVector2 dimensions = BlockVector2.at(IOUtil.readVarInt(fis), IOUtil.readVarInt(fis)); +// DIMENSION_CACHE.put(file, MathMan.pair((short) dimensions.getBlockX(), (short) dimensions.getBlockZ())); +// BlockVector2 offset = registerAndGetChunkOffset(dimensions, cached); +// } +// } else { +// try { +// player.sendMessage(BBC.getPrefix() + "Converting: " + file); +// cached.createNewFile(); +// try (FileInputStream in = new FileInputStream(file)) { +// ClipboardFormat format = ClipboardFormats.findByFile(file); +// if (format != null) { +// ClipboardReader reader = format.getReader(in); +// Clipboard clipboard = reader.read(); +// clipboard.setOrigin(clipboard.getMinimumPoint()); +// try { +// MCAQueue queue = new MCAQueue(null, null, false); +// BlockVector2 dimensions = clipboard.getDimensions().toBlockVector2(); +// BlockVector2 offset = registerAndGetChunkOffset(dimensions, cached); +// new Schematic(clipboard).paste(queue, BlockVector3.ZERO, true); +// try (FileOutputStream fos = new FileOutputStream(cached)) { +// IOUtil.writeVarInt(fos, dimensions.getBlockX()); +// IOUtil.writeVarInt(fos, dimensions.getBlockZ()); +// +// try (FaweOutputStream cos = MainUtil.getCompressedOS(fos, 2)) { +// NBTOutputStream nos = new NBTOutputStream((DataOutput) cos); +// Collection writeChunks = queue.getFaweChunks(); +// cos.writeInt(writeChunks.size()); +// +// boolean selected = isSelected(file); +// +// for (FaweChunk chunk : writeChunks) { +// MCAChunk mcaChunk = ((MCAChunk) chunk); +// mcaChunk.write(nos); +// mcaChunk.setLoc(this, mcaChunk.getX() + offset.getBlockX(), mcaChunk.getZ() + offset.getBlockZ()); +// if (Math.abs(mcaChunk.getX()) <= 15 && Math.abs(mcaChunk.getZ()) <= 15) { +// cacheChunk(mcaChunk, selected); +// } +// } +// } +// } +// if (System.getProperty("os.name").contains("Windows")) { +// Path path = cached.toPath(); +// Object hidden = java.nio.file.Files.getAttribute(path, "dos:hidden", LinkOption.NOFOLLOW_LINKS); +// if (hidden != null) { +// //link file to DosFileAttributes +// java.nio.file.Files.setAttribute(path, "dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS); +// } +// } +// +// DIMENSION_CACHE.put(file, MathMan.pair((short) dimensions.getBlockX(), (short) dimensions.getBlockZ())); +// } finally { +// if (clipboard instanceof Closeable) { +// ((Closeable) clipboard).close(); +// } +// } +// } +// } +// } catch (Throwable e) { +// e.printStackTrace(); +// cached.delete(); +// } +// } +// } +// +// private synchronized MCAChunk getCachedChunk(int chunkX, int chunkZ) { +// return chunks.get(MathMan.pairInt(chunkX, chunkZ)); +// } +// +// private MCAChunk getChunk(int chunkX, int chunkZ) { +// long pair = MathMan.pairInt(chunkX, chunkZ); +// // Check cached +// MCAChunk chunk = getCachedChunk(chunkX, chunkZ); +// if (chunk != null) return chunk; +// +// // We need to cache it +// Map.Entry entry = files.get(pair); +// if (entry != null) { +// File cached = entry.getKey(); +// +// // Guard caching by other threads +// synchronized (cached) { +// chunk = getCachedChunk(chunkX, chunkZ); +// +// // Read chunks from disk +// if (chunk == null) { +// clean(); +// String filename = cached.getName(); +// File file = new File(cached.getParentFile(), filename.substring(1, filename.length() - 7)); +// boolean selected = isSelected(file); +// +// long origin = entry.getValue(); +// int OCX = MathMan.unpairIntX(origin); +// int OCZ = MathMan.unpairIntY(origin); +// try (FileInputStream fis = new FileInputStream(cached); FaweInputStream in = MainUtil.getCompressedIS(fis)) { +// NonCloseableInputStream nonCloseable = new NonCloseableInputStream(in); +// try (NBTInputStream nis = new NBTInputStream(nonCloseable)) { +// int numChunks = in.readInt(); +// for (int i = 0; i < numChunks; i++) { +// MCAChunk mcaChunk = new MCAChunk(nis, null, 0, 0, true); +// mcaChunk.setLoc(this, mcaChunk.getX() + OCX, mcaChunk.getZ() + OCZ); +// cacheChunk(mcaChunk, selected); +// } +// } +// } catch (IOException e) { +// e.printStackTrace(); +// } +// // Return the cached chunk, or an empty one +// chunk = getCachedChunk(chunkX, chunkZ); +// if (chunk == null) { +// // TODO use shared chunk +// // TODO synchronize on sending chunk packet +// cacheChunk(chunk = new MCAChunk(this, chunkX, chunkZ), selected); +// } +// } +// } +// } else { +// chunk = new MCAChunk(this, chunkX, chunkZ); +// } +// return chunk; +// } +// +// /** +// * Return a lazily evaluated chunk +// * @param chunkX +// * @param chunkZ +// * @return lazy chunk +// */ +// @Override +// public FaweChunk getSnapshot(int chunkX, int chunkZ) { +// return new LazyFaweChunk(this, chunkX, chunkZ) { +// @Override +// public MCAChunk getChunk() { +// MCAChunk tmp = SchemVis.this.getChunk(chunkX, chunkZ); +// tmp.setLoc(SchemVis.this, getX(), getZ()); +// return tmp; +// } +// +// @Override +// public void addToQueue() { +// MCAChunk cached = getCachedChunk(); +// if (cached != null) setChunk(cached); +// } +// }; +// } +// +// @Override +// public FawePlayer getPlayer() { +// return player; +// } +// +// public void bind() { +// player.setVirtualWorld(this); +// } +// +// /** +// * Send all chunks to the player +// */ +// @Override +// public void update() { +// FaweQueue packetQueue = SetQueue.IMP.getNewQueue(player.getWorld(), true, false); +// +// if (!packetQueue.supports(Capability.CHUNK_PACKETS)) { +// return; +// } +// +// int OX = chunkOffset.getBlockX(); +// int OZ = chunkOffset.getBlockZ(); +// +// Location position = player.toWorldEditPlayer().getLocation(); +// int pcx = (position.getBlockX() >> 4) - OX; +// int pcz = (position.getBlockZ() >> 4) - OZ; +// +// int scx = pcx - 15; +// int scz = pcz - 15; +// int ecx = pcx + 15; +// int ecz = pcz + 15; +// +// for (int cz = scz; cz <= ecz; cz++) { +// for (int cx = scx; cx <= ecx; cx++) { +// send(packetQueue, cx, cz); +// } +// } +// } +// +// @Override +// public void sendChunk(FaweChunk chunk) { /* do nothing - never used */ } +// +// @Override +// public void sendChunk(int x, int z, int bitMask) { /* do nothing - never used*/ } +// +// @Override +// public BiomeType getBiomeType(int x, int z) throws FaweException.FaweChunkLoadException { +// // TODO later (currently not used) +// return BiomeTypes.FOREST; +// } +// +// @Override +// public int getCombinedId4Data(int x, int y, int z) throws FaweException.FaweChunkLoadException { +// MCAChunk chunk = getChunk(x >> 4, z >> 4); +// if (y < 0 || y > 255) return 0; +// return chunk.getBlockCombinedId(x & 15, y, z & 15); +// } +// +// /** +// * Closes this virtual world and sends the normal world chunks to the player +// * @throws IOException +// */ +// @Override +// public synchronized void close(boolean update) throws IOException { +// clear(); +// chunks.clear(); +// files.clear(); +// player.getPlayer().setPosition(origin, origin.getPitch(), origin.getYaw()); +// if (update) { +// FaweQueue packetQueue = SetQueue.IMP.getNewQueue(player.getWorld(), true, false); +// +// int OX = chunkOffset.getBlockX(); +// int OZ = chunkOffset.getBlockZ(); +// +// Location position = player.toWorldEditPlayer().getLocation(); +// int pcx = (position.getBlockX() >> 4) - OX; +// int pcz = (position.getBlockZ() >> 4) - OZ; +// +// int scx = pcx - 15; +// int scz = pcz - 15; +// int ecx = pcx + 15; +// int ecz = pcz + 15; +// +// for (int cz = scz; cz <= ecz; cz++) { +// for (int cx = scx; cx <= ecx; cx++) { +// packetQueue.sendChunk(cx + OX, cz + OZ, 0); +// } +// } +// } +// } +// +// @Override +// public boolean playEffect(Vector3 position, int type, int data) { +// // TODO Auto-generated method stub +// return false; +// } +// +// @Override +// public boolean setBiome(BlockVector2 position, BiomeType biome) { +// // TODO Auto-generated method stub +// return false; +// } +// +// @Override +// public boolean notifyAndLightBlock(BlockVector3 position, BlockState previousType) throws WorldEditException { +// // TODO Auto-generated method stub +// return false; +// } +// +// @Override +// public BlockVector3 getSpawnPosition() { +// // TODO Auto-generated method stub +// return null; +// } +//} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/BrushCache.java b/worldedit-core/src/main/java/com/boydti/fawe/util/BrushCache.java index 38dc5b20a..f15bb7ef0 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/BrushCache.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/BrushCache.java @@ -89,7 +89,7 @@ public final class BrushCache { String json = tool.toString(gson); map.put("weBrushJson", new StringTag(json)); if (display == null) { - map.put("display", new CompoundTag(displayMap = new HashMap())); + map.put("display", new CompoundTag(displayMap = new HashMap<>())); } else { displayMap = ReflectionUtils.getMap(display.getValue()); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/ImgurUtility.java b/worldedit-core/src/main/java/com/boydti/fawe/util/ImgurUtility.java index c4783f2b4..83a0a3087 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/ImgurUtility.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/ImgurUtility.java @@ -49,16 +49,16 @@ public class ImgurUtility { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.connect(); StringBuilder stb = new StringBuilder(); - OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); - wr.write(data); - wr.flush(); - BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - while ((line = rd.readLine()) != null) { - stb.append(line).append("\n"); + try (OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) { + wr.write(data); + wr.flush(); + try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { + String line; + while ((line = rd.readLine()) != null) { + stb.append(line).append("\n"); + } + } } - wr.close(); - rd.close(); return stb.toString(); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/Jars.java b/worldedit-core/src/main/java/com/boydti/fawe/util/Jars.java index 66f4118e0..41d165e25 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/Jars.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/Jars.java @@ -9,11 +9,6 @@ import java.security.NoSuchAlgorithmException; import java.util.Base64; public enum Jars { - WE_B_6_1_7_2("https://addons.cursecdn.com/files/2431/372/worldedit-bukkit-6.1.7.2.jar", - "CRVJCWGJJ6UK40CTGHXQVK2/3C9BBTOS25FWI0ZHD4S=", 1726340), - - VS_B_5_171_0("https://media.forgecdn.net/files/2488/589/VoxelSniper-5.172.0-SNAPSHOT.jar", - "4CTEDDEKCAN/M6R0DHS925++HBSJ/TUYAAKAR4CUWC4=", 3615020), MM_v1_4_0("https://github.com/InventivetalentDev/MapManager/releases/download/1.4.0-SNAPSHOT/MapManager_v1.4.0-SNAPSHOT.jar", "AEO5SKBUGN4YJRS8XGGNLBM2QRZPTI1KF0/1W1URTGA=", 163279), @@ -45,7 +40,7 @@ public enum Jars { public byte[] download() throws IOException { byte[] jarBytes = new byte[this.filesize]; URL url = new URL(this.url); - try (DataInputStream dis = new DataInputStream(url.openConnection().getInputStream());) { + try (DataInputStream dis = new DataInputStream(url.openConnection().getInputStream())) { dis.readFully(jarBytes); if (dis.read() != -1) { // assert that we've read everything throw new IllegalStateException("downloaded jar is longer than expected"); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/MainUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/MainUtil.java index e77efc62a..262c4e933 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/MainUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/MainUtil.java @@ -15,12 +15,15 @@ import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.history.changeset.ChangeSet; import com.sk89q.worldedit.util.Location; -import java.awt.Graphics2D; +import net.jpountz.lz4.*; + +import javax.annotation.Nullable; +import javax.imageio.ImageIO; +import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.lang.reflect.Array; import java.lang.reflect.Method; -import java.lang.reflect.Parameter; import java.net.*; import java.nio.channels.Channels; import java.nio.channels.FileChannel; @@ -28,6 +31,7 @@ import java.nio.channels.ReadableByteChannel; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; +import java.util.List; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ForkJoinPool; @@ -37,9 +41,8 @@ import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.regex.Pattern; import java.util.zip.*; -import javax.annotation.Nullable; -import javax.imageio.ImageIO; -import net.jpountz.lz4.*; + +import static java.lang.System.arraycopy; public class MainUtil { /* @@ -75,35 +78,6 @@ public class MainUtil { return suggestions; } - public static List prepend(String start, List suggestions) { - if (start.isEmpty()) { - return suggestions; - } - suggestions = new ArrayList<>(suggestions); - for (int i = 0; i < suggestions.size(); i++) { - suggestions.set(i, start + suggestions.get(i)); - } - return suggestions; - } - - public static T[] joinArrayGeneric(T[]... arrays) { - int length = 0; - for (T[] array : arrays) { - length += array.length; - } - - //T[] result = new T[length]; - final T[] result = (T[]) Array.newInstance(arrays[0].getClass().getComponentType(), length); - - int offset = 0; - for (T[] array : arrays) { - System.arraycopy(array, 0, result, offset, array.length); - offset += array.length; - } - - return result; - } - public static T getOf(Object[] arr, Class ofType) { for (Object a : arr) { if (a != null && a.getClass() == ofType) { @@ -113,22 +87,6 @@ public class MainUtil { return null; } - public static String[] getParameterNames(Method method) { - Parameter[] parameters = method.getParameters(); - List parameterNames = new ArrayList<>(); - - for (Parameter parameter : parameters) { - if(!parameter.isNamePresent()) { - throw new IllegalArgumentException("Parameter names are not present!"); - } - - String parameterName = parameter.getName(); - parameterNames.add(parameterName); - } - - return parameterNames.toArray(new String[parameterNames.size()]); - } - public static long getTotalSize(Path path) { final AtomicLong size = new AtomicLong(0); traverse(path, new RunnableVal2() { @@ -217,20 +175,17 @@ public class MainUtil { public static int getMaxFileId(File folder) { final int[] max = new int[1]; - folder.listFiles(new FileFilter() { - @Override - public boolean accept(File pathname) { - String name = pathname.getName(); - Integer val = null; - if (pathname.isDirectory()) { - val = StringMan.toInteger(name, 0, name.length()); - } else { - int i = name.lastIndexOf('.'); - if (i != -1) val = StringMan.toInteger(name, 0, i); - } - if (val != null && val > max[0]) max[0] = val; - return false; + folder.listFiles(pathname -> { + String name = pathname.getName(); + Integer val = null; + if (pathname.isDirectory()) { + val = StringMan.toInteger(name, 0, name.length()); + } else { + int i = name.lastIndexOf('.'); + if (i != -1) val = StringMan.toInteger(name, 0, i); } + if (val != null && val > max[0]) max[0] = val; + return false; }); return max[0] + 1; } @@ -294,7 +249,7 @@ public class MainUtil { return baos.toByteArray(); } - public static byte[] decompress(byte[] bytes, byte[] buffer, Inflater inflater) throws IOException, DataFormatException { + public static byte[] decompress(byte[] bytes, byte[] buffer, Inflater inflater) throws DataFormatException { if (buffer == null) { buffer = new byte[8192]; } @@ -452,10 +407,11 @@ public class MainUtil { writer.append("--" + boundary + "--").append(CRLF).flush(); } int responseCode = ((HttpURLConnection) con).getResponseCode(); - java.util.Scanner scanner = new java.util.Scanner(con.getInputStream()).useDelimiter("\\A"); - String content = scanner.next().trim(); - scanner.close(); - if (content != null && !content.startsWith("<")) { + String content; + try (Scanner scanner = new Scanner(con.getInputStream()).useDelimiter("\\A")) { + content = scanner.next().trim(); + } + if (!content.startsWith("<")) { Fawe.debug(content); } if (responseCode == 200) { @@ -512,8 +468,8 @@ public class MainUtil { return loader; } } - } catch (Throwable ignore) { - ignore.printStackTrace(); + } catch (Throwable throwable) { + throwable.printStackTrace(); } return sysloader; } @@ -527,12 +483,13 @@ public class MainUtil { public static void download(URL url, File out) throws IOException { File parent = out.getParentFile(); if (!out.exists()) { - if (parent != null) parent.mkdirs(); + if (parent != null) { + parent.mkdirs(); + } File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp", parent); tempFile.deleteOnExit(); - try (InputStream is = url.openStream()) { - ReadableByteChannel rbc = Channels.newChannel(is); - FileOutputStream fos = new FileOutputStream(tempFile); + try (InputStream is = url.openStream(); ReadableByteChannel rbc = Channels.newChannel(is); + FileOutputStream fos = new FileOutputStream(tempFile)) { fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } Files.copy(tempFile.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING); @@ -616,32 +573,14 @@ public class MainUtil { } destFile.createNewFile(); } - FileInputStream fIn = null; - FileOutputStream fOut = null; - FileChannel source = null; - FileChannel destination = null; - try { - fIn = new FileInputStream(sourceFile); - source = fIn.getChannel(); - fOut = new FileOutputStream(destFile); - destination = fOut.getChannel(); + try (FileInputStream fIn = new FileInputStream(sourceFile); FileChannel source = fIn.getChannel(); + FileOutputStream fOut = new FileOutputStream(destFile); FileChannel destination = fOut.getChannel()) { long transfered = 0; long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } - } finally { - if (source != null) { - source.close(); - } else if (fIn != null) { - fIn.close(); - } - if (destination != null) { - destination.close(); - } else if (fOut != null) { - fOut.close(); - } } return destFile; } @@ -793,31 +732,6 @@ public class MainUtil { return msg; } - public static void smoothArray(int[] data, int width, int radius, int weight) { - int[] copy = data.clone(); - int length = data.length / width; - int diameter = 2 * radius + 1; - weight += diameter * diameter - 1; - for (int x = 0; x < width; x++) { - for (int y = 0; y < length; y++) { - int index = x + width * y; - int value = 0; - int count = 0; - for (int x2 = Math.max(0, x - radius); x2 <= Math.min(width - 1, x + radius); x2++) { - for (int y2 = Math.max(0, y - radius); y2 <= Math.min(length - 1, y + radius); y2++) { - count++; - int index2 = x2 + width * y2; - value += data[index2]; - - } - } - value += data[index] * (weight - count); - value = value / (weight); - data[index] = value; - } - } - } - public static void warnDeprecated(Class... alternatives) { StackTraceElement[] stacktrace = new RuntimeException().getStackTrace(); if (stacktrace.length > 1) { @@ -838,8 +752,8 @@ public class MainUtil { String myName = Class.forName(deprecatedElement.getClassName()).getSimpleName(); Fawe.debug("@" + creator + " used by " + myName + "." + deprecatedElement.getMethodName() + "():" + deprecatedElement.getLineNumber() + " is deprecated."); Fawe.debug(" - Alternatives: " + StringMan.getString(alternatives)); - } catch (Throwable ignore) { - ignore.printStackTrace(); + } catch (Throwable throwable) { + throwable.printStackTrace(); } finally { break; } @@ -972,7 +886,7 @@ public class MainUtil { Class component = arr.getClass().getComponentType(); Object newInnerArray = Array.newInstance(component, innerArrayLength); if (component.isPrimitive()) { - System.arraycopy(arr, 0, newInnerArray, 0, innerArrayLength); + arraycopy(arr, 0, newInnerArray, 0, innerArrayLength); } else { //copy each elem of the array for (int i = 0; i < innerArrayLength; i++) { @@ -1073,14 +987,11 @@ public class MainUtil { public static void deleteOlder(File directory, final long timeDiff, boolean printDebug) { final long now = System.currentTimeMillis(); ForkJoinPool pool = new ForkJoinPool(); - iterateFiles(directory, new Consumer() { - @Override - public void accept(File file) { - long age = now - file.lastModified(); - if (age > timeDiff) { - pool.submit(() -> file.delete()); - if (printDebug) BBC.FILE_DELETED.send(null, file); - } + iterateFiles(directory, file -> { + long age = now - file.lastModified(); + if (age > timeDiff) { + pool.submit(file::delete); + if (printDebug) BBC.FILE_DELETED.send(null, file); } }); pool.shutdown(); @@ -1099,10 +1010,9 @@ public class MainUtil { if (directory.exists()) { File[] files = directory.listFiles(); if (null != files) { - for (int i = 0; i < files.length; i++) { - File file = files[i]; + for (File file : files) { if (file.isDirectory()) { - deleteDirectory(files[i], printDebug); + deleteDirectory(file, printDebug); } else { file.delete(); if (printDebug) BBC.FILE_DELETED.send(null, file); @@ -1131,26 +1041,15 @@ public class MainUtil { return true; } - public static boolean isValidSign(CompoundTag tag) { - Map values = tag.getValue(); - if (values.size() > 4 && values.containsKey("Text1")) { - Tag text1 = values.get("Text1"); - Object value = text1.getValue(); - return value != null && value instanceof String && ((String) value).length() > 0; - } - return false; - } - public enum OS { - LINUX, SOLARIS, WINDOWS, MACOS, UNKNOWN; + LINUX, WINDOWS, MACOS, UNKNOWN; } public static File getWorkingDirectory(String applicationName) { String userHome = System.getProperty("user.home", "."); - File workingDirectory = null; + File workingDirectory; switch (getPlatform()) { case LINUX: - case SOLARIS: workingDirectory = new File(userHome, '.' + applicationName + '/'); break; case WINDOWS: @@ -1181,12 +1080,6 @@ public class MainUtil { if (osName.contains("mac")) { return OS.MACOS; } - if (osName.contains("solaris")) { - return OS.SOLARIS; - } - if (osName.contains("sunos")) { - return OS.SOLARIS; - } if (osName.contains("linux")) { return OS.LINUX; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/cui/CUI.java b/worldedit-core/src/main/java/com/boydti/fawe/util/cui/CUI.java deleted file mode 100644 index 540f6a455..000000000 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/cui/CUI.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.boydti.fawe.util.cui; - -import com.boydti.fawe.object.FawePlayer; -import com.sk89q.worldedit.internal.cui.CUIEvent; - -public abstract class CUI { - private final FawePlayer player; - - public CUI(FawePlayer player) { - this.player = player; - } - - public FawePlayer getPlayer() { - return player; - } - - public abstract void dispatchCUIEvent(CUIEvent event); -} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/image/ImageUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/image/ImageUtil.java index 771dbfb0a..7ba9553c3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/image/ImageUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/image/ImageUtil.java @@ -230,9 +230,7 @@ public class ImageUtil { } else { throw new ParameterException("Invalid image " + arg); } - } catch (IOException e) { - throw new ParameterException(e); - } catch (URISyntaxException e) { + } catch (IOException | URISyntaxException e) { throw new ParameterException(e); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java b/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java index 12fff9e0d..f715fdcd0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java @@ -1757,7 +1757,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, checkNotNull(region); checkNotNull(block); boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); - + if (canBypassAll(region, false, true) && !hasNbt) { return changes = queue.setBlocks((CuboidRegion) region, block.getInternalId()); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java b/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java index e71afeba7..ae99989f7 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java @@ -33,7 +33,6 @@ import com.boydti.fawe.object.clipboard.MultiClipboardHolder; import com.boydti.fawe.object.collection.SparseBitSet; import com.boydti.fawe.object.extent.ResettableExtent; import com.boydti.fawe.util.*; -import com.boydti.fawe.util.cui.CUI; import com.boydti.fawe.wrappers.WorldWrapper; import com.sk89q.jchronic.Chronic; import com.sk89q.jchronic.Options; @@ -127,10 +126,8 @@ public class LocalSession implements TextureHolder { private transient boolean toolControl = true; private transient boolean superPickaxe = false; private transient BlockTool pickaxeMode = new SinglePickaxe(); - private transient boolean hasTool = false; - private transient Tool[] tools = new Tool[ItemTypes.size()]; - + private transient Map tools = new HashMap<>(); private transient int maxBlocksChanged = -1; private transient int maxTimeoutTime; private transient boolean useInventory; @@ -379,6 +376,11 @@ public class LocalSession implements TextureHolder { * @param editSession the edit session */ public void remember(EditSession editSession) { + checkNotNull(editSession); + + // Don't store anything if no changes were made + if (editSession.size() == 0) return; + FawePlayer fp = editSession.getPlayer(); int limit = fp == null ? Integer.MAX_VALUE : fp.getLimit().MAX_HISTORY; remember(editSession, true, limit); @@ -452,7 +454,7 @@ public class LocalSession implements TextureHolder { } // It should have already been flushed, but just in case! editSession.flushQueue(); - if (editSession == null || editSession.getChangeSet() == null || limitMb == 0 || ((historySize >> 20) > limitMb && !append)) { + if (editSession.getChangeSet() == null || limitMb == 0 || historySize >> 20 > limitMb && !append) { return; } // Don't store anything if no changes were made @@ -575,7 +577,7 @@ public class LocalSession implements TextureHolder { } public void unregisterTools(Player player) { - for (Tool tool : tools) { + for (Tool tool : tools.values()) { if (tool instanceof BrushTool) { ((BrushTool) tool).clear(player); } @@ -691,7 +693,7 @@ public class LocalSession implements TextureHolder { } } if (world != null) { - Fawe.imp().registerPacketListener(); + //Fawe.imp().registerPacketListener(); world.update(); } } @@ -959,7 +961,7 @@ public class LocalSession implements TextureHolder { */ @Nullable public Tool getTool(ItemType item) { - return tools[item.getInternalId()]; + return tools.get(item); } @Nullable @@ -988,7 +990,6 @@ public class LocalSession implements TextureHolder { * @return the tool, or {@code null} * @throws InvalidToolBindException if the item can't be bound to that item */ - @Deprecated public BrushTool getBrushTool(ItemType item) throws InvalidToolBindException { return getBrushTool(item.getDefaultState(), null, true); } @@ -1005,9 +1006,9 @@ public class LocalSession implements TextureHolder { public BrushTool getBrushTool(BaseItem item, Player player, boolean create) throws InvalidToolBindException { Tool tool = getTool(item, player); - if ((tool == null || !(tool instanceof BrushTool))) { + if (!(tool instanceof BrushTool)) { if (create) { - tool = new BrushTool(); + tool = new BrushTool("worldedit.brush.sphere"); setTool(item, tool, player); } else { return null; @@ -1025,6 +1026,13 @@ public class LocalSession implements TextureHolder { * @throws InvalidToolBindException if the item can't be bound to that item */ public void setTool(ItemType item, @Nullable Tool tool) throws InvalidToolBindException { + if (item.hasBlockType()) { + throw new InvalidToolBindException(item, "Blocks can't be used"); + } else if (item.getId().equalsIgnoreCase(config.wandItem)) { + throw new InvalidToolBindException(item, "Already used for the wand"); + } else if (item.getId().equalsIgnoreCase(config.navigationWand)) { + throw new InvalidToolBindException(item, "Already used for the navigation wand"); + } setTool(item.getDefaultState(), tool, null); } @@ -1035,7 +1043,7 @@ public class LocalSession implements TextureHolder { public void setTool(BaseItem item, @Nullable Tool tool, Player player) throws InvalidToolBindException { ItemType type = item.getType(); - if (type.hasBlockType() && type.getBlockType().getMaterial().isAir()) { + if (type.hasBlockType()) { throw new InvalidToolBindException(type, "Blocks can't be used"); } else if (type.getId().equalsIgnoreCase(config.wandItem)) { throw new InvalidToolBindException(type, "Already used for the wand"); @@ -1049,18 +1057,20 @@ public class LocalSession implements TextureHolder { if (tool != null) { ((BrushTool) tool).setHolder(item); } else { - this.tools[type.getInternalId()] = null; + this.tools.remove(type); } } else { - previous = this.tools[type.getInternalId()]; - this.tools[type.getInternalId()] = tool; + previous = this.tools.get(type); + this.tools.put(type, tool); if (tool != null) { hasTool = true; } else { hasTool = false; - for (Tool i : this.tools) if (i != null) { - hasTool = true; - break; + for (Tool i : this.tools.values()) { + if (i != null) { + hasTool = true; + break; + } } } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java index 930853dec..123f34c1a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java @@ -19,7 +19,6 @@ package com.sk89q.worldedit.command; -import com.boydti.fawe.Fawe; import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.Commands; import com.boydti.fawe.config.Settings; @@ -29,10 +28,9 @@ import com.boydti.fawe.object.clipboard.MultiClipboardHolder; import com.boydti.fawe.object.clipboard.URIClipboardHolder; import com.boydti.fawe.object.clipboard.remap.ClipboardRemapper; import com.boydti.fawe.object.schematic.StructureFormat; -import com.boydti.fawe.object.schematic.visualizer.SchemVis; +//import com.boydti.fawe.object.schematic.visualizer.SchemVis; import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.chat.Message; -import com.google.common.collect.Multimap; import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandException; @@ -49,42 +47,28 @@ import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; -import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.util.command.binding.Switch; import com.sk89q.worldedit.util.command.parametric.Optional; -import com.sk89q.worldedit.util.io.Closer; import com.sk89q.worldedit.util.io.file.FilenameException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.UUID; +import java.util.*; import java.util.concurrent.atomic.LongAdder; import java.util.regex.Pattern; import static com.boydti.fawe.util.ReflectionUtils.as; -import static com.google.common.base.Preconditions.checkNotNull; /** * Commands that work with schematic files. @@ -111,7 +95,7 @@ public class SchematicCommands extends MethodCommands { aliases = {"loadall"}, usage = "[] ", help = "Load multiple clipboards\n" + - "The -r flag will apply random rotation", + "The -r flag will apply random rotation", desc = "Load multiple clipboards (paste will randomly choose one)" ) @Deprecated @@ -135,9 +119,7 @@ public class SchematicCommands extends MethodCommands { @Command( aliases = {"clear"}, - usage = "", desc = "Clear your clipboard", - min = 0, max = 0 ) @CommandPermissions({"worldedit.clipboard.clear", "worldedit.schematic.clear"}) @@ -165,7 +147,6 @@ public class SchematicCommands extends MethodCommands { uri = new File(root, fileName).toURI(); } - boolean removed = false; ClipboardHolder clipboard = session.getClipboard(); if (clipboard instanceof URIClipboardHolder) { URIClipboardHolder identifiable = (URIClipboardHolder) clipboard; @@ -205,11 +186,15 @@ public class SchematicCommands extends MethodCommands { player.print(BBC.getPrefix() + "Remapped schematic"); } - @Command(aliases = {"load"}, usage = "[] ", desc = "Load a schematic into your clipboard") + @Command( + aliases = {"load"}, + usage = "[] ", + desc = "Load a schematic into your clipboard" + ) @Deprecated @CommandPermissions({"worldedit.clipboard.load", "worldedit.schematic.load", "worldedit.schematic.load.asset", "worldedit.schematic.load.web", "worldedit.schematic.load.other"}) - public void load(final Player player, final LocalSession session, @Optional() final String formatName, String filename) throws FilenameException { - final LocalConfiguration config = this.worldEdit.getConfiguration(); + public void load(Player player, LocalSession session, @Optional() String formatName, String filename) throws FilenameException { + LocalConfiguration config = worldEdit.getConfiguration(); ClipboardFormat format = formatName == null ? null : ClipboardFormats.findByAlias(formatName); InputStream in = null; try { @@ -225,13 +210,12 @@ public class SchematicCommands extends MethodCommands { ReadableByteChannel rbc = Channels.newChannel(url.openStream()); in = Channels.newInputStream(rbc); uri = url.toURI(); - if (format == null) format = BuiltInClipboardFormat.MCEDIT_SCHEMATIC; } else { if (!player.hasPermission("worldedit.schematic.load") && !player.hasPermission("worldedit.clipboard.load")) { BBC.NO_PERM.send(player, "worldedit.clipboard.load"); return; } - File working = this.worldEdit.getWorkingDirectoryFile(config.saveDir); + File working = worldEdit.getWorkingDirectoryFile(config.saveDir); File dir = Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS ? new File(working, player.getUniqueId().toString()) : working; File f; if (filename.startsWith("#")) { @@ -264,7 +248,7 @@ public class SchematicCommands extends MethodCommands { } } if (f == null || !f.exists() || !MainUtil.isInSubDirectory(working, f)) { - player.printError(BBC.getPrefix() + "Schematic " + filename + " does not exist! (" + ((f == null) ? false : f.exists()) + "|" + f + "|" + (f == null ? false : !MainUtil.isInSubDirectory(working, f)) + ")"); + player.printError(BBC.getPrefix() + "Schematic " + filename + " does not exist! (" + ((f != null) && f.exists()) + "|" + f + "|" + (f != null && !MainUtil.isInSubDirectory(working, f)) + ")"); return; } if (format == null) { @@ -294,17 +278,22 @@ public class SchematicCommands extends MethodCommands { } } - @Command(aliases = {"save"}, usage = "[format] ", desc = "Save a schematic into your clipboard", help = "The default format for 1.13 is schem") + @Command( + aliases = {"save"}, + usage = "[format] ", + desc = "Save a schematic into your clipboard", + help = "The default format for 1.13 is schem" + ) @Deprecated @CommandPermissions({"worldedit.clipboard.save", "worldedit.schematic.save", "worldedit.schematic.save.other"}) - public void save(final Player player, final LocalSession session, @Optional("schem") final String formatName, String filename, @Switch('g') boolean global, @Switch('f') boolean allowOverwrite) throws CommandException, WorldEditException { - final LocalConfiguration config = this.worldEdit.getConfiguration(); - final ClipboardFormat format = ClipboardFormats.findByAlias(formatName); + public void save(Player player, LocalSession session, @Optional("schem") String formatName, String filename, @Switch('g') boolean global, @Switch('f') boolean allowOverwrite) throws CommandException, WorldEditException { + LocalConfiguration config = worldEdit.getConfiguration(); + ClipboardFormat format = ClipboardFormats.findByAlias(formatName); if (format == null) { player.printError(BBC.getPrefix() + "Unknown schematic format: " + formatName); return; } - File working = this.worldEdit.getWorkingDirectoryFile(config.saveDir); + File working = worldEdit.getWorkingDirectoryFile(config.saveDir); File dir = !global && Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS ? new File(working, player.getUniqueId().toString()) : working; if (filename.contains("../")) { if (!player.hasPermission("worldedit.schematic.save.other")) { @@ -316,7 +305,7 @@ public class SchematicCommands extends MethodCommands { filename = filename.substring(3); } } - File f = this.worldEdit.getSafeSaveFile(player, dir, filename, format.getPrimaryFileExtension(), format.getPrimaryFileExtension()); + File f = worldEdit.getSafeSaveFile(player, dir, filename, format.getPrimaryFileExtension(), format.getPrimaryFileExtension()); if (f.getName().replaceAll("." + format.getPrimaryFileExtension(), "").isEmpty()) { File directory = f.getParentFile(); if (directory.exists()) { @@ -345,14 +334,14 @@ public class SchematicCommands extends MethodCommands { BBC.SCHEMATIC_MOVE_EXISTS.send(player, f.getName()); } try (FileOutputStream fos = new FileOutputStream(f)) { - final ClipboardHolder holder = session.getClipboard(); - final Clipboard clipboard = holder.getClipboard(); - final Transform transform = holder.getTransform(); - final Clipboard target; + ClipboardHolder holder = session.getClipboard(); + Clipboard clipboard = holder.getClipboard(); + Transform transform = holder.getTransform(); + Clipboard target; // If we have a transform, bake it into the copy if (!transform.isIdentity()) { - final FlattenedClipboardTransform result = FlattenedClipboardTransform.transform(clipboard, transform); + FlattenedClipboardTransform result = FlattenedClipboardTransform.transform(clipboard, transform); target = new BlockArrayClipboard(result.getTransformedRegion(), UUID.randomUUID()); target.setOrigin(clipboard.getOrigin()); Operations.completeLegacy(result.copyTo(target)); @@ -386,12 +375,19 @@ public class SchematicCommands extends MethodCommands { } } - @Command(aliases = {"move", "m"}, usage = "", desc = "Move your loaded schematic", help = "Move your currently loaded schematics", min = 1, max = 1) + @Command( + aliases = {"move", "m"}, + usage = "", + desc = "Move your loaded schematic", + help = "Move your currently loaded schematics", + min = 1, + max = 1 + ) @CommandPermissions({"worldedit.schematic.move", "worldedit.schematic.move.other"}) - public void move(final Player player, final LocalSession session, String directory) throws WorldEditException, IOException { - final LocalConfiguration config = this.worldEdit.getConfiguration(); - final File working = this.worldEdit.getWorkingDirectoryFile(config.saveDir); - final File dir = Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS ? new File(working, player.getUniqueId().toString()) : working; + public void move(Player player, LocalSession session, String directory) throws WorldEditException, IOException { + LocalConfiguration config = worldEdit.getConfiguration(); + File working = worldEdit.getWorkingDirectoryFile(config.saveDir); + File dir = Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS ? new File(working, player.getUniqueId().toString()) : working; File destDir = new File(dir, directory); if (!MainUtil.isInSubDirectory(working, destDir)) { player.printError(BBC.getPrefix() + "Directory " + destDir + " does not exist!"); @@ -432,7 +428,14 @@ public class SchematicCommands extends MethodCommands { } } - @Command(aliases = {"delete", "d"}, usage = "", desc = "Delete a saved schematic", help = "Delete a schematic from the schematic list", min = 1, max = 1) + @Command( + aliases = {"delete", "d"}, + usage = "", + desc = "Delete a saved schematic", + help = "Delete a schematic from the schematic list", + min = 1, + max = 1 + ) @CommandPermissions({"worldedit.schematic.delete", "worldedit.schematic.delete.other"}) public void delete(final Player player, final LocalSession session, final CommandContext args) throws WorldEditException, IOException { final LocalConfiguration config = this.worldEdit.getConfiguration(); @@ -490,7 +493,11 @@ public class SchematicCommands extends MethodCommands { return false; } - @Command(aliases = {"formats", "listformats", "f"}, desc = "List available formats", max = 0) + @Command( + aliases = {"formats", "listformats", "f"}, + desc = "List available formats", + max = 0 + ) @CommandPermissions("worldedit.schematic.formats") public void formats(final Actor actor) throws WorldEditException { BBC.SCHEMATIC_FORMAT.send(actor); @@ -515,12 +522,11 @@ public class SchematicCommands extends MethodCommands { } +/* @Command( aliases = {"show"}, desc = "Show a schematic", usage = "[global|mine|]", - min = 0, - max = -1, flags = "dnp", help = "List all schematics in the schematics directory\n" + " -f restricts by format\n" @@ -578,13 +584,12 @@ public class SchematicCommands extends MethodCommands { throw e; } } +*/ @Command( aliases = {"list", "ls", "all"}, desc = "List saved schematics", usage = "[global|mine|] [page=1]", - min = 0, - max = -1, flags = "dnp", help = "List all schematics in the schematics directory\n" + " -p prints the requested page\n" + diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/UtilityCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/UtilityCommands.java index fd49d224c..3e1be3564 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/UtilityCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/UtilityCommands.java @@ -183,8 +183,8 @@ public class UtilityCommands extends MethodCommands { desc = "Generate the heightmap interface: https://github.com/boy0001/HeightMap" ) @CommandPermissions("fawe.admin") - public void heightmapInterface(FawePlayer player, @Optional("100") int min, @Optional("200") int max) throws IOException { - player.sendMessage("Please wait while we generate the minified heightmaps."); + public void heightmapInterface(Player player, @Optional("100") int min, @Optional("200") int max) throws IOException { + player.print("Please wait while we generate the minified heightmaps."); File srcFolder = MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.HEIGHTMAP); File webSrc = new File(Fawe.imp().getDirectory(), "web" + File.separator + "heightmap"); @@ -206,7 +206,7 @@ public class UtilityCommands extends MethodCommands { BufferedImage img = MainUtil.readImage(file); BufferedImage minImg = ImageUtil.getScaledInstance(img, min, min, RenderingHints.VALUE_INTERPOLATION_BILINEAR, true); BufferedImage maxImg = max == -1 ? img : ImageUtil.getScaledInstance(img, max, max, RenderingHints.VALUE_INTERPOLATION_BILINEAR, true); - player.sendMessage("Writing " + name); + player.print("Writing " + name); File minFile = new File(minImages, name); File maxFile = new File(maxImages, name); minFile.getParentFile().mkdirs(); @@ -231,9 +231,9 @@ public class UtilityCommands extends MethodCommands { config.append("// The local source for the image (used in commands)\n"); config.append("var src_local = \"file://\";\n"); File configFile = new File(webSrc, "config.js"); - player.sendMessage("Writing " + configFile); + player.print("Writing " + configFile); Files.write(configFile.toPath(), config.toString().getBytes()); - player.sendMessage("Done! See: `FastAsyncWorldEdit/web/heightmap`"); + player.print("Done! See: `FastAsyncWorldEdit/web/heightmap`"); } @Command( diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java index 57617749e..c7543019b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java @@ -98,7 +98,6 @@ public class SelectionCommand extends SimpleCommand { CuboidRegion cuboid = (CuboidRegion) selection; RegionFunction function = ((RegionVisitor) operation).function; RegionWrapper current = new RegionWrapper(cuboid.getMinimumPoint(), cuboid.getMaximumPoint()); - FawePlayer fp = FawePlayer.wrap(player); FaweRegionExtent regionExtent = editSession.getRegionExtent(); if (function instanceof BlockReplace && regionExtent == null || regionExtent.isGlobal()) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/Extent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/Extent.java index 9c2416eb0..ccdcb61e2 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/Extent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/Extent.java @@ -20,7 +20,6 @@ package com.sk89q.worldedit.extent; import com.boydti.fawe.jnbt.anvil.generator.*; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.clipboard.WorldCopyClipboard; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.BaseEntity; @@ -32,7 +31,6 @@ import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.MutableBlockVector3; -import com.sk89q.worldedit.math.MutableVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.registry.state.PropertyGroup; import com.sk89q.worldedit.session.ClipboardHolder; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/BuiltInClipboardFormat.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/BuiltInClipboardFormat.java index 0f4cd464f..b09530eb9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/BuiltInClipboardFormat.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/BuiltInClipboardFormat.java @@ -19,9 +19,19 @@ package com.sk89q.worldedit.extent.clipboard.io; +import com.boydti.fawe.object.io.PGZIPOutputStream; +import com.boydti.fawe.object.io.ResettableFileInputStream; +import com.boydti.fawe.object.schematic.PNGWriter; +import com.boydti.fawe.object.schematic.StructureFormat; +import com.google.common.collect.ImmutableSet; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.NBTInputStream; +import com.sk89q.jnbt.NBTOutputStream; +import com.sk89q.jnbt.NamedTag; +import com.sk89q.jnbt.Tag; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; -import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -32,28 +42,21 @@ import java.util.Set; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; -import com.boydti.fawe.object.clipboard.AbstractClipboardFormat; -import com.boydti.fawe.object.io.PGZIPOutputStream; -import com.boydti.fawe.object.io.ResettableFileInputStream; -import com.boydti.fawe.object.schematic.PNGWriter; -import com.boydti.fawe.object.schematic.StructureFormat; -import com.google.common.collect.ImmutableSet; -import com.sk89q.jnbt.CompoundTag; -import com.sk89q.jnbt.NBTConstants; -import com.sk89q.jnbt.NBTInputStream; -import com.sk89q.jnbt.NBTOutputStream; -import com.sk89q.jnbt.NamedTag; -import com.sk89q.jnbt.Tag; - /** * A collection of supported clipboard formats. */ -public enum BuiltInClipboardFormat implements ClipboardFormat{ +public enum BuiltInClipboardFormat implements ClipboardFormat { + /** * The Schematic format used by MCEdit. */ - @Deprecated MCEDIT_SCHEMATIC("mcedit", "mce", "schematic") { + + @Override + public String getPrimaryFileExtension() { + return "schematic"; + } + @Override public ClipboardReader getReader(InputStream inputStream) throws IOException { if (inputStream instanceof FileInputStream) { @@ -73,32 +76,31 @@ public enum BuiltInClipboardFormat implements ClipboardFormat{ @Override public boolean isFormat(File file) { - try (NBTInputStream str = new NBTInputStream(new GZIPInputStream(new FileInputStream(file)))) { - NamedTag rootTag = str.readNamedTag(); - if (!rootTag.getName().equals("Schematic")) { - return false; - } - CompoundTag schematicTag = (CompoundTag) rootTag.getTag(); + try (NBTInputStream str = new NBTInputStream(new GZIPInputStream(new FileInputStream(file)))) { + NamedTag rootTag = str.readNamedTag(); + if (!rootTag.getName().equals("Schematic")) { + return false; + } + CompoundTag schematicTag = (CompoundTag) rootTag.getTag(); - // Check - Map schematic = schematicTag.getValue(); - if (!schematic.containsKey("Materials")) { - return false; - } - } catch (Exception e) { - return false; - } - return true; + // Check + Map schematic = schematicTag.getValue(); + if (!schematic.containsKey("Materials")) { + return false; + } + } catch (Exception e) { + return false; + } + return true; } + }, + SPONGE_SCHEMATIC("sponge", "schem") { @Override public String getPrimaryFileExtension() { - return "schematic"; + return "schem"; } - }, - @Deprecated - SPONGE_SCHEMATIC("sponge", "schem") { @Override public ClipboardReader getReader(InputStream inputStream) throws IOException { if (inputStream instanceof FileInputStream) { @@ -106,8 +108,7 @@ public enum BuiltInClipboardFormat implements ClipboardFormat{ } BufferedInputStream buffered = new BufferedInputStream(inputStream); NBTInputStream nbtStream = new NBTInputStream(new BufferedInputStream(new GZIPInputStream(buffered))); - SpongeSchematicReader input = new SpongeSchematicReader(nbtStream); - return input; + return new SpongeSchematicReader(nbtStream); } @Override @@ -117,8 +118,7 @@ public enum BuiltInClipboardFormat implements ClipboardFormat{ gzip = outputStream; } else { outputStream = new BufferedOutputStream(outputStream); - PGZIPOutputStream pigz = new PGZIPOutputStream(outputStream); - gzip = pigz; + gzip = new PGZIPOutputStream(outputStream); } NBTOutputStream nbtStream = new NBTOutputStream(new BufferedOutputStream(gzip)); return new SpongeSchematicWriter(nbtStream); @@ -145,10 +145,6 @@ public enum BuiltInClipboardFormat implements ClipboardFormat{ return true; } - @Override - public String getPrimaryFileExtension() { - return "schem"; - } }, /** @@ -166,13 +162,7 @@ public enum BuiltInClipboardFormat implements ClipboardFormat{ @Override public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { outputStream = new BufferedOutputStream(outputStream); - OutputStream gzip; - if (outputStream instanceof PGZIPOutputStream || outputStream instanceof GZIPOutputStream) { - gzip = outputStream; - } else { - PGZIPOutputStream pigz = new PGZIPOutputStream(outputStream); - gzip = pigz; - } + OutputStream gzip = new PGZIPOutputStream(outputStream); NBTOutputStream nbtStream = new NBTOutputStream(new BufferedOutputStream(gzip)); return new StructureFormat(nbtStream); } @@ -194,7 +184,7 @@ public enum BuiltInClipboardFormat implements ClipboardFormat{ PNG("png", "image") { @Override - public ClipboardReader getReader(InputStream inputStream) throws IOException { + public ClipboardReader getReader(InputStream inputStream) { return null; } @@ -235,4 +225,4 @@ public enum BuiltInClipboardFormat implements ClipboardFormat{ return ImmutableSet.of(getPrimaryFileExtension()); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/WorldEditBinding.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/WorldEditBinding.java index 8f2c46486..061bfab72 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/WorldEditBinding.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/WorldEditBinding.java @@ -19,7 +19,6 @@ package com.sk89q.worldedit.internal.command; -import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.IncompleteRegionException; @@ -89,7 +88,7 @@ public class WorldEditBinding { public Object getSelection(ArgumentStack context) throws IncompleteRegionException, ParameterException { Player sender = getPlayer(context); LocalSession session = worldEdit.getSessionManager().get(sender); - return session.getSelection(FawePlayer.wrap(sender).getWorldForEditing()); + return session.getSelection(sender.getWorld()); } /** @@ -307,7 +306,7 @@ public class WorldEditBinding { type = BlockVector3.class, behavior = BindingBehavior.CONSUMES, consumedCount = 1) - public BlockVector3 getDirection(ArgumentStack context, Direction direction) + public BlockVector3 getDirection(ArgumentStack context, Direction direction) throws ParameterException, UnknownDirectionException { Player sender = getPlayer(context); if (direction.includeDiagonals()) { @@ -380,4 +379,4 @@ public class WorldEditBinding { -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/SimpleWorld.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/SimpleWorld.java index d9028c95f..c6040cd60 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/SimpleWorld.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/SimpleWorld.java @@ -46,6 +46,7 @@ import javax.annotation.Nullable; /** * An abstract implementation of {@link World}. + * Added by FAWE. */ public interface SimpleWorld extends World { @Override @@ -155,4 +156,4 @@ public interface SimpleWorld extends World { default void setWeather(WeatherType weatherType, long duration) { } -} \ No newline at end of file +}