diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java index 1d3b5fb53..7c1821ce1 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java @@ -83,6 +83,9 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit // ------------------------------------------------------------------------ public Spigot_v1_13_R2() throws NoSuchFieldException, NoSuchMethodException { + // A simple test + CraftServer.class.cast(Bukkit.getServer()); + // The list of tags on an NBTTagList nbtListTagListField = NBTTagList.class.getDeclaredField("list"); nbtListTagListField.setAccessible(true); @@ -139,6 +142,7 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit @Nullable private static String getEntityId(Entity entity) { MinecraftKey minecraftkey = EntityTypes.getName(entity.getBukkitEntity().getHandle().P()); + return minecraftkey == null ? null : minecraftkey.toString(); } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/ArrayWrapper.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/ArrayWrapper.java index fc84afa67..d24b7cc19 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/ArrayWrapper.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/ArrayWrapper.java @@ -23,6 +23,7 @@ public final class ArrayWrapper { * * @param elements The elements of the array. */ + @SafeVarargs public ArrayWrapper(E... elements) { setArray(elements); } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/FancyMessage.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/FancyMessage.java index 35045946e..22983d20a 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/FancyMessage.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/FancyMessage.java @@ -12,27 +12,17 @@ import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.function.Consumer; import java.util.logging.Level; -import org.bukkit.Achievement; + import org.bukkit.Bukkit; import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.Statistic; -import org.bukkit.Statistic.Type; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.configuration.serialization.ConfigurationSerialization; -import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import static com.boydti.fawe.bukkit.chat.TextualComponent.rawText; @@ -271,162 +261,6 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< return this; } - /** - * Set the behavior of the current editing component to display information about an achievement when the client hovers over the text. - *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

- * - * @param name The name of the achievement to display, excluding the "achievement." prefix. - * @return This builder instance. - */ - public FancyMessage achievementTooltip(final String name) { - onHover("show_achievement", new JsonString("achievement." + name)); - return this; - } - - /** - * Set the behavior of the current editing component to display information about an achievement when the client hovers over the text. - *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

- * - * @param which The achievement to display. - * @return This builder instance. - */ - public FancyMessage achievementTooltip(final Achievement which) { - try { - Object achievement = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name").get(achievement)); - } catch (IllegalAccessException e) { - Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); - return this; - } catch (IllegalArgumentException e) { - Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); - return this; - } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); - return this; - } - } - - /** - * Set the behavior of the current editing component to display information about a parameterless statistic when the client hovers over the text. - *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

- * - * @param which The statistic to display. - * @return This builder instance. - * @throws IllegalArgumentException If the statistic requires a parameter which was not supplied. - */ - public FancyMessage statisticTooltip(final Statistic which) { - Type type = which.getType(); - if (type != Type.UNTYPED) { - throw new IllegalArgumentException("That statistic requires an additional " + type + " parameter!"); - } - try { - Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class).invoke(null, which); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); - } catch (IllegalAccessException e) { - Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); - return this; - } catch (IllegalArgumentException e) { - Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); - return this; - } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); - return this; - } - } - - /** - * Set the behavior of the current editing component to display information about a statistic parameter with a material when the client hovers over the text. - *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

- * - * @param which The statistic to display. - * @param item The sole material parameter to the statistic. - * @return This builder instance. - * @throws IllegalArgumentException If the statistic requires a parameter which was not supplied, or was supplied a parameter that was not required. - */ - public FancyMessage statisticTooltip(final Statistic which, Material item) { - Type type = which.getType(); - if (type == Type.UNTYPED) { - throw new IllegalArgumentException("That statistic needs no additional parameter!"); - } - if ((type == Type.BLOCK && item.isBlock()) || type == Type.ENTITY) { - throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!"); - } - try { - Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", Statistic.class, Material.class).invoke(null, which, item); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); - } catch (IllegalAccessException e) { - Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); - return this; - } catch (IllegalArgumentException e) { - Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); - return this; - } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); - return this; - } - } - - /** - * Set the behavior of the current editing component to display information about a statistic parameter with an entity type when the client hovers over the text. - *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

- * - * @param which The statistic to display. - * @param entity The sole entity type parameter to the statistic. - * @return This builder instance. - * @throws IllegalArgumentException If the statistic requires a parameter which was not supplied, or was supplied a parameter that was not required. - */ - public FancyMessage statisticTooltip(final Statistic which, EntityType entity) { - Type type = which.getType(); - if (type == Type.UNTYPED) { - throw new IllegalArgumentException("That statistic needs no additional parameter!"); - } - if (type != Type.ENTITY) { - throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!"); - } - try { - Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class).invoke(null, which, entity); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); - } catch (IllegalAccessException e) { - Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); - return this; - } catch (IllegalArgumentException e) { - Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); - return this; - } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); - return this; - } - } - - /** - * Set the behavior of the current editing component to display information about an item when the client hovers over the text. - *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

- * - * @param itemJSON A string representing the JSON-serialized NBT data tag of an {@link ItemStack}. - * @return This builder instance. - */ - public FancyMessage itemTooltip(final String itemJSON) { - onHover("show_item", new JsonString(itemJSON)); // Seems a bit hacky, considering we have a JSON object as a parameter - return this; - } - - /** - * Set the behavior of the current editing component to display information about an item when the client hovers over the text. - *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

- * - * @param itemStack The stack for which to display information. - * @return This builder instance. - */ - public FancyMessage itemTooltip(final ItemStack itemStack) { - try { - Object nmsItem = Reflection.getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class).invoke(null, itemStack); - return itemTooltip(Reflection.getMethod(Reflection.getNMSClass("ItemStack"), "save", Reflection.getNMSClass("NBTTagCompound")).invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()).toString()); - } catch (Exception e) { - e.printStackTrace(); - return this; - } - } - /** * Set the behavior of the current editing component to display raw text when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

@@ -579,9 +413,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @return This builder instance. */ public FancyMessage translationReplacements(final FancyMessage... replacements) { - for (FancyMessage str : replacements) { - latest().translationReplacements.add(str); - } + Collections.addAll(latest().translationReplacements, replacements); dirty = true; @@ -873,6 +705,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< /** * Internally called method. Not for API consumption. */ + @NotNull public Iterator iterator() { return messageParts.iterator(); } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/TextualComponent.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/TextualComponent.java index e42b691bc..53365f433 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/TextualComponent.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/TextualComponent.java @@ -1,7 +1,6 @@ package com.boydti.fawe.bukkit.chat; import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMap; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.HashMap; @@ -75,48 +74,6 @@ public abstract class TextualComponent implements Cloneable { throw new UnsupportedOperationException("This feature is only supported in snapshot releases."); } - /** - * Create a textual component representing a scoreboard value. - * The client will see their own score for the specified objective as the text represented by this component. - *

- * This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients. - *

- * - * @param scoreboardObjective The name of the objective for which to display the score. - * @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during - * JSON serialization. - */ - public static TextualComponent objectiveScore(String scoreboardObjective) { - return objectiveScore("*", scoreboardObjective); - } - - /** - * Create a textual component representing a scoreboard value. - * The client will see the score of the specified player for the specified objective as the text represented by this component. - * - *

This method is currently guaranteed to throw an {@code UnsupportedOperationException} - * as it is only supported on snapshot clients. - * - * @param playerName The name of the player whos score will be shown. If - * this string represents the single-character sequence - * "*", the viewing player's score will be displayed. - * Standard minecraft selectors (@a, @p, etc) - * are not supported. - * @param scoreboardObjective The name of the objective for - * which to display the score. - * @return The text component representing the specified scoreboard score - * for the specified player, or {@code null} if an error occurs during JSON serialization. - */ - public static TextualComponent objectiveScore(String playerName, String scoreboardObjective) { - throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE - // OVERLOADS documentation accordingly - - return new ComplexTextTypeComponent("score", ImmutableMap.builder() - .put("name", playerName) - .put("objective", scoreboardObjective) - .build()); - } - /** * Create a textual component representing a player name, retrievable by using a standard minecraft selector. * The client will see the players or entities captured by the specified selector as the text represented by this component. diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/FactionsFeature.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/FactionsFeature.java index 0fd1e943f..bf33997e5 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/FactionsFeature.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/FactionsFeature.java @@ -14,11 +14,9 @@ import org.bukkit.plugin.Plugin; public class FactionsFeature extends BukkitMaskManager implements Listener { FaweBukkit plugin; - private Plugin factions; public FactionsFeature(final Plugin factionsPlugin, final FaweBukkit p3) { super(factionsPlugin.getName()); - this.factions = factionsPlugin; this.plugin = p3; } @@ -42,8 +40,7 @@ public class FactionsFeature extends BukkitMaskManager implements Listener { } }; } - } - else if (fac.getOnlinePlayers().contains(player)) { + } else if (fac.getOnlinePlayers().contains(player)) { if (!fac.getComparisonName().equals("wilderness")) { final Chunk chunk = loc.getChunk(); final Location pos1 = new Location(loc.getWorld(), chunk.getX() * 16, 0, chunk.getZ() * 16); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/Worldguard.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/Worldguard.java index cb7a91675..44ec28ac3 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/Worldguard.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/Worldguard.java @@ -26,14 +26,14 @@ import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; public class Worldguard extends BukkitMaskManager implements Listener { - WorldGuardPlugin worldguard; + private WorldGuardPlugin worldguard; FaweBukkit plugin; private WorldGuardPlugin getWorldGuard() { final Plugin plugin = Bukkit.getPluginManager().getPlugin("WorldGuard"); // WorldGuard may not be loaded - if ((plugin == null) || !(plugin instanceof WorldGuardPlugin)) { + if (!(plugin instanceof WorldGuardPlugin)) { return null; // Maybe you want throw an exception instead } @@ -46,13 +46,13 @@ public class Worldguard extends BukkitMaskManager implements Listener { this.plugin = p3; } - public ProtectedRegion getRegion(final com.sk89q.worldguard.LocalPlayer player, final Location loc) { + public ProtectedRegion getRegion(final LocalPlayer player, final Location location) { RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); if (container == null) { System.out.println("Region capability is not enabled for WorldGuard."); return null; } - RegionManager manager = container.get(FaweAPI.getWorld(loc.getWorld().getName())); + RegionManager manager = container.get(FaweAPI.getWorld(location.getWorld().getName())); if (manager == null) { System.out.println("Region capability is not enabled for that world."); return null; @@ -61,7 +61,7 @@ public class Worldguard extends BukkitMaskManager implements Listener { if (global != null && isAllowed(player, global)) { return global; } - final ApplicableRegionSet regions = manager.getApplicableRegions(BlockVector3.at(loc.getX(), loc.getY(), loc.getZ())); + final ApplicableRegionSet regions = manager.getApplicableRegions(BlockVector3.at(location.getX(), location.getY(), location.getZ())); for (final ProtectedRegion region : regions) { if (isAllowed(player, region)) { return region; @@ -71,7 +71,7 @@ public class Worldguard extends BukkitMaskManager implements Listener { } public boolean isAllowed(LocalPlayer localplayer, ProtectedRegion region) { - if (region.isOwner(localplayer) || region.isOwner(localplayer.getName())) { + if (region.isOwner(localplayer) || region.isOwner(localplayer)) { return true; } else if (region.getId().toLowerCase().equals(localplayer.getName().toLowerCase())) { return true; @@ -81,7 +81,7 @@ public class Worldguard extends BukkitMaskManager implements Listener { return true; } if (localplayer.hasPermission("fawe.worldguard.member")) { - if (region.isMember(localplayer) || region.isMember(localplayer.getName())) { + if (region.isMember(localplayer) || region.isMember(localplayer)) { return true; } else if (region.isMember("*")) { return true; @@ -93,7 +93,7 @@ public class Worldguard extends BukkitMaskManager implements Listener { @Override public FaweMask getMask(FawePlayer fp, MaskType type) { final Player player = fp.parent; - final com.sk89q.worldguard.LocalPlayer localplayer = this.worldguard.wrapPlayer(player); + final LocalPlayer localplayer = this.worldguard.wrapPlayer(player); final Location location = player.getLocation(); final ProtectedRegion myregion = this.getRegion(localplayer, location); if (myregion != null) { diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/BukkitReflectionUtils.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/BukkitReflectionUtils.java index 1079f8c2d..69f960507 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/BukkitReflectionUtils.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/BukkitReflectionUtils.java @@ -15,49 +15,33 @@ public class BukkitReflectionUtils { * prefix of minecraft classes */ private static volatile String preClassM = null; - /** - * boolean value, TRUE if server uses forge or MCPC+ - */ - private static boolean forge = false; /** * check server version and class names */ public static void init() { - if (Bukkit.getServer() != null) { - if (Bukkit.getVersion().contains("MCPC") || Bukkit.getVersion().contains("Forge")) { - forge = true; - } - final Server server = Bukkit.getServer(); - final Class bukkitServerClass = server.getClass(); - String[] pas = bukkitServerClass.getName().split("\\."); + final Server server = Bukkit.getServer(); + final Class bukkitServerClass = server.getClass(); + String[] pas = bukkitServerClass.getName().split("\\."); + if (pas.length == 5) { + final String verB = pas[3]; + preClassB = "org.bukkit.craftbukkit." + verB; + } + try { + final Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle"); + final Object handle = getHandle.invoke(server); + final Class handleServerClass = handle.getClass(); + pas = handleServerClass.getName().split("\\."); if (pas.length == 5) { - final String verB = pas[3]; - preClassB = "org.bukkit.craftbukkit." + verB; - } - try { - final Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle"); - final Object handle = getHandle.invoke(server); - final Class handleServerClass = handle.getClass(); - pas = handleServerClass.getName().split("\\."); - if (pas.length == 5) { - final String verM = pas[3]; - preClassM = "net.minecraft.server." + verM; - } - } catch (final Exception ignored) { - MainUtil.handleError(ignored); + final String verM = pas[3]; + preClassM = "net.minecraft.server." + verM; } + } catch (final Exception e) { + MainUtil.handleError(e); } } - /** - * @return true if server has forge classes - */ - public static boolean isForge() { - return forge; - } - /** * Get class for name. Replace {nms} to net.minecraft.server.V*. Replace {cb} to org.bukkit.craftbukkit.V*. Replace * {nm} to net.minecraft diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/ItemUtil.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/ItemUtil.java index 28015ebb0..5bd1e046c 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/ItemUtil.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/ItemUtil.java @@ -61,7 +61,7 @@ public class ItemUtil { Int2ObjectOpenHashMap> map = hashToNMSTag.get(); if (map == null) { map = new Int2ObjectOpenHashMap<>(); - hashToNMSTag = new SoftReference(new Int2ObjectOpenHashMap<>(map)); + hashToNMSTag = new SoftReference<>(new Int2ObjectOpenHashMap<>(map)); } WeakReference nativeTagRef = map.get(nmsTag.hashCode()); if (nativeTagRef != null) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java b/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java index ef9625376..a3aa65f71 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java @@ -442,7 +442,7 @@ public class Fawe { } public static boolean isMainThread() { - return INSTANCE != null ? INSTANCE.thread == Thread.currentThread() : true; + return INSTANCE == null || INSTANCE.thread == Thread.currentThread(); } /** diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/FaweParser.java b/worldedit-core/src/main/java/com/boydti/fawe/command/FaweParser.java index 2e7c334ed..337636a97 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/FaweParser.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/command/FaweParser.java @@ -75,7 +75,7 @@ public abstract class FaweParser extends InputParser { } } } - inputs.add(toParse.substring(last, toParse.length())); + inputs.add(toParse.substring(last)); for (int i = 0; i < inputs.size(); i++) { String full = inputs.get(i); String command = full; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/installer/JSystemFileChooser.java b/worldedit-core/src/main/java/com/boydti/fawe/installer/JSystemFileChooser.java index f26736b96..c5e5f7ec8 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/installer/JSystemFileChooser.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/installer/JSystemFileChooser.java @@ -41,7 +41,7 @@ public class JSystemFileChooser extends JFileChooser { private static FilePane findFilePane(Container parent){ for(Component comp: parent.getComponents()){ - if(FilePane.class.isInstance(comp)){ + if(comp instanceof FilePane){ return (FilePane)comp; } if(comp instanceof Container){ diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java index 2b8297c42..5845de303 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java @@ -227,14 +227,14 @@ public class SchematicStreamer extends NBTStreamer { if (forwardType.hasProperty(PropertyKey.SHAPE) && forwardType.hasProperty(PropertyKey.FACING)) { Direction forwardFacing = (Direction) forwardBlock.getState(PropertyKey.FACING); if (forwardFacing == left) { - BlockStateHolder rightBlock = fc.getBlock(x + right.getBlockX(), y + right.getBlockY(), z + right.getBlockZ()); + BlockStateHolder rightBlock = fc.getBlock(x + right.toBlockVector().getBlockX(), y + right.toBlockVector().getBlockY(), z + right.toBlockVector().getBlockZ()); BlockType rightType = rightBlock.getBlockType(); if (!rightType.hasProperty(PropertyKey.SHAPE) || rightBlock.getState(PropertyKey.FACING) != facing) { fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "inner_left")); } return; } else if (forwardFacing == right) { - BlockStateHolder leftBlock = fc.getBlock(x + left.getBlockX(), y + left.getBlockY(), z + left.getBlockZ()); + BlockStateHolder leftBlock = fc.getBlock(x + left.toBlockVector().getBlockX(), y + left.toBlockVector().getBlockY(), z + left.toBlockVector().getBlockZ()); BlockType leftType = leftBlock.getBlockType(); if (!leftType.hasProperty(PropertyKey.SHAPE) || leftBlock.getState(PropertyKey.FACING) != facing) { fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "inner_right")); @@ -248,14 +248,14 @@ public class SchematicStreamer extends NBTStreamer { if (backwardsType.hasProperty(PropertyKey.SHAPE) && backwardsType.hasProperty(PropertyKey.FACING)) { Direction backwardsFacing = (Direction) backwardsBlock.getState(PropertyKey.FACING); if (backwardsFacing == left) { - BlockStateHolder rightBlock = fc.getBlock(x + right.getBlockX(), y + right.getBlockY(), z + right.getBlockZ()); + BlockStateHolder rightBlock = fc.getBlock(x + right.toBlockVector().getBlockX(), y + right.toBlockVector().getBlockY(), z + right.toBlockVector().getBlockZ()); BlockType rightType = rightBlock.getBlockType(); if (!rightType.hasProperty(PropertyKey.SHAPE) || rightBlock.getState(PropertyKey.FACING) != facing) { fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "outer_left")); } return; } else if (backwardsFacing == right) { - BlockStateHolder leftBlock = fc.getBlock(x + left.getBlockX(), y + left.getBlockY(), z + left.getBlockZ()); + BlockStateHolder leftBlock = fc.getBlock(x + left.toBlockVector().getBlockX(), y + left.toBlockVector().getBlockY(), z + left.toBlockVector().getBlockZ()); BlockType leftType = leftBlock.getBlockType(); if (!leftType.hasProperty(PropertyKey.SHAPE) || leftBlock.getState(PropertyKey.FACING) != facing) { fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "outer_right")); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFilter.java index f264d6d23..26d013593 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFilter.java @@ -14,7 +14,6 @@ import java.util.concurrent.ForkJoinPool; public class MCAFilter extends IterableThreadLocal { public void withPool(ForkJoinPool pool, MCAQueue queue) { - return; } /** diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAQueue.java index 7069f4114..53255a02b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAQueue.java @@ -621,8 +621,8 @@ public class MCAQueue extends NMSMappedFaweQueue { } out.writeNamedTag("InhabitedTime", inhabitedTime); out.writeNamedTag("LastUpdate", lastUpdate); - if (biomes != null) { - out.writeNamedTag("Biomes", biomes); - } + out.writeNamedTag("Biomes", biomes); int len = 0; for (boolean hasSection : hasSections) { if (hasSection) len++; 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 6c340cd5d..34d49a39a 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 @@ -98,7 +98,7 @@ public abstract class FawePlayer extends Metadatable { FakePlayer fake = new FakePlayer(actor.getName(), actor.getUniqueId(), actor); return fake.toFawePlayer(); } - if (obj != null && obj.getClass().getName().contains("CraftPlayer") && !Fawe.imp().getPlatform().equals("bukkit")) { + if (obj.getClass().getName().contains("CraftPlayer") && !Fawe.imp().getPlatform().equals("bukkit")) { try { Method methodGetHandle = obj.getClass().getDeclaredMethod("getHandle"); obj = methodGetHandle.invoke(obj); @@ -206,7 +206,7 @@ public abstract class FawePlayer extends Metadatable { if (region != null) { BlockVector3 min = region.getMinimumPoint(); BlockVector3 max = region.getMaximumPoint(); - long area = (long) ((max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1)); + long area = (max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1); if (area > 2 << 18) { setConfirmTask(task, context, command); BlockVector3 base = max.subtract(min).add(BlockVector3.ONE); @@ -220,7 +220,7 @@ public abstract class FawePlayer extends Metadatable { public synchronized boolean confirm() { Runnable confirm = deleteMeta("cmdConfirm"); - if (!(confirm instanceof Runnable)) { + if (confirm == null) { return false; } queueAction(() -> { @@ -341,7 +341,7 @@ public abstract class FawePlayer extends Metadatable { if (session.getClipboard() != null) { return; } - } catch (EmptyClipboardException e) { + } catch (EmptyClipboardException ignored) { } if (player != null) { Clipboard clip = doc.toClipboard(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BrushSettings.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BrushSettings.java index 0dde45926..8a5286618 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BrushSettings.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BrushSettings.java @@ -222,7 +222,7 @@ public class BrushSettings { } public BrushSettings addPermissions(String... perms) { - for (String perm : perms) permissions.add(perm); + Collections.addAll(permissions, perms); return this; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/SweepBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/SweepBrush.java index 707925c5e..092f1b647 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/SweepBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/SweepBrush.java @@ -45,7 +45,7 @@ public class SweepBrush implements Brush, ResettableTool { return; } - boolean newPos = this.position == null || !position.equals(this.position); + boolean newPos = !position.equals(this.position); this.position = position; FawePlayer player = editSession.getPlayer(); if (newPos) { @@ -98,7 +98,6 @@ public class SweepBrush implements Brush, ResettableTool { MutableVector3 last = new MutableVector3(0, 0, 0); for (double pos = 0D; pos <= 1D; pos += step) { Vector3 gradient = interpol.get1stDerivative(pos); - if (last == null) last = new MutableVector3(interpol.get1stDerivative(pos)); double dist = MathMan.sqrtApprox(last.distanceSq(gradient)); last.mutX(gradient.getX()); last.mutY(gradient.getY()); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweChangeSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweChangeSet.java index 75161e5f4..d494eadc1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweChangeSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweChangeSet.java @@ -2,7 +2,6 @@ package com.boydti.fawe.object.changeset; import com.boydti.fawe.Fawe; import com.boydti.fawe.FaweAPI; -import com.boydti.fawe.FaweCache; import com.boydti.fawe.config.Settings; import com.boydti.fawe.logging.rollback.RollbackOptimizedHistory; import com.boydti.fawe.object.FaweChunk; @@ -14,9 +13,6 @@ import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.TaskManager; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.world.block.BaseBlock; -import com.sk89q.worldedit.world.block.BlockID; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.history.change.BlockChange; import com.sk89q.worldedit.history.change.Change; @@ -27,7 +23,8 @@ import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockID; import java.util.Iterator; import java.util.Map; @@ -58,7 +55,7 @@ public abstract class FaweChangeSet implements ChangeSet { public FaweChangeSet(String world) { this.worldName = world; - this.mainThread = (Fawe.get() != null) ? Fawe.isMainThread() : true; + this.mainThread = (Fawe.get() == null) || Fawe.isMainThread(); this.layers = FaweChunk.HEIGHT >> 4; } @@ -85,15 +82,12 @@ public abstract class FaweChangeSet implements ChangeSet { public boolean closeAsync() { waitingAsync.incrementAndGet(); - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - waitingAsync.decrementAndGet(); - synchronized (waitingAsync) { - waitingAsync.notifyAll(); - } - close(); + TaskManager.IMP.async(() -> { + waitingAsync.decrementAndGet(); + synchronized (waitingAsync) { + waitingAsync.notifyAll(); } + close(); }); return true; } @@ -153,8 +147,6 @@ public abstract class FaweChangeSet implements ChangeSet { public void delete() { } - ; - public EditSession toEditSession(FawePlayer player) { return toEditSession(player, null); } @@ -258,115 +250,109 @@ public abstract class FaweChangeSet implements ChangeSet { @Override public void run(final FaweChunk previous, final FaweChunk next) { FaweChangeSet.this.waitingCombined.incrementAndGet(); - Runnable run = new Runnable() { - @Override - public void run() { - try { - int cx = previous.getX(); - int cz = previous.getZ(); - int bx = cx << 4; - int bz = cz << 4; - synchronized (FaweChangeSet.this) { - BiomeType[] previousBiomes = previous.getBiomeArray(); - if (previousBiomes != null) { - BiomeType[] nextBiomes = next.getBiomeArray(); - int index = 0; - for (int z = 0; z < 16; z++) { - int zz = bz + z; - for (int x = 0; x < 16; x++) { - BiomeType idFrom = previousBiomes[index]; - BiomeType idTo = nextBiomes[index]; - if (idFrom != idTo && idTo != null) { - addBiomeChange(bx + x, zz, idFrom, idTo); - } - index++; + Runnable run = () -> { + try { + int cx = previous.getX(); + int cz = previous.getZ(); + int bx = cx << 4; + int bz = cz << 4; + synchronized (FaweChangeSet.this) { + BiomeType[] previousBiomes = previous.getBiomeArray(); + if (previousBiomes != null) { + BiomeType[] nextBiomes = next.getBiomeArray(); + int index = 0; + for (int z = 0; z < 16; z++) { + int zz = bz + z; + for (int x = 0; x < 16; x++) { + BiomeType idFrom = previousBiomes[index]; + BiomeType idTo = nextBiomes[index]; + if (idFrom != idTo && idTo != null) { + addBiomeChange(bx + x, zz, idFrom, idTo); } + index++; } } - // Block changes - for (int layer = 0; layer < layers; layer++) { - int[] currentLayer = next.getIdArray(layer); - int[] previousLayer = previous.getIdArray(layer); - if (currentLayer == null) { - continue; - } - int startY = layer << 4; - int index = 0; - for (int y = 0; y < 16; y++) { - int yy = y + startY; - for (int z = 0; z < 16; z++) { - int zz = z + bz; - for (int x = 0; x < 16; x++, index++) { - int xx = x + bx; - int combinedIdCurrent = currentLayer[index]; - switch (combinedIdCurrent) { - case 0: - continue; - default: - int combinedIdPrevious; - if (previousLayer != null) { - combinedIdPrevious = previousLayer[index]; - if (combinedIdPrevious == 0) { - combinedIdPrevious = BlockID.AIR; - } - } else { - combinedIdPrevious = BlockID.AIR; - } - if (combinedIdCurrent != combinedIdPrevious) { - add(xx, yy, zz, combinedIdPrevious, combinedIdCurrent); - } + } + // Block changes + for (int layer = 0; layer < layers; layer++) { + int[] currentLayer = next.getIdArray(layer); + int[] previousLayer = previous.getIdArray(layer); + if (currentLayer == null) { + continue; + } + int startY = layer << 4; + int index = 0; + for (int y = 0; y < 16; y++) { + int yy = y + startY; + for (int z = 0; z < 16; z++) { + int zz = z + bz; + for (int x = 0; x < 16; x++, index++) { + int xx = x + bx; + int combinedIdCurrent = currentLayer[index]; + if (combinedIdCurrent != 0) { + int combinedIdPrevious; + if (previousLayer != null) { + combinedIdPrevious = previousLayer[index]; + if (combinedIdPrevious == 0) { + combinedIdPrevious = BlockID.AIR; + } + } else { + combinedIdPrevious = BlockID.AIR; + } + if (combinedIdCurrent != combinedIdPrevious) { + add(xx, yy, zz, combinedIdPrevious, combinedIdCurrent); } } } } } - // Tile changes - { - // Tiles created - Map tiles = next.getTiles(); - if (!tiles.isEmpty()) { - for (Map.Entry entry : tiles.entrySet()) { - addTileCreate(entry.getValue()); - } - } - // Tiles removed - tiles = previous.getTiles(); - if (!tiles.isEmpty()) { - for (Map.Entry entry : tiles.entrySet()) { - addTileRemove(entry.getValue()); - } + } + // Tile changes + { + // Tiles created + Map tiles = next.getTiles(); + if (!tiles.isEmpty()) { + for (Map.Entry entry : tiles.entrySet()) { + addTileCreate(entry.getValue()); } } - // Entity changes - { - // Entities created - Set entities = next.getEntities(); - if (!entities.isEmpty()) { - for (CompoundTag entityTag : entities) { - addEntityCreate(entityTag); - } - } - // Entities removed - entities = previous.getEntities(); - if (!entities.isEmpty()) { - for (CompoundTag entityTag : entities) { - addEntityRemove(entityTag); - } + // Tiles removed + tiles = previous.getTiles(); + if (!tiles.isEmpty()) { + for (Map.Entry entry : tiles.entrySet()) { + addTileRemove(entry.getValue()); } } } - } catch (Throwable e) { - MainUtil.handleError(e); - } finally { - if (FaweChangeSet.this.waitingCombined.decrementAndGet() <= 0) { - synchronized (FaweChangeSet.this.waitingAsync) { - FaweChangeSet.this.waitingAsync.notifyAll(); + // Entity changes + { + // Entities created + Set entities = next.getEntities(); + if (!entities.isEmpty()) { + for (CompoundTag entityTag : entities) { + addEntityCreate(entityTag); + } } - synchronized (FaweChangeSet.this.waitingCombined) { - FaweChangeSet.this.waitingCombined.notifyAll(); + // Entities removed + entities = previous.getEntities(); + if (!entities.isEmpty()) { + for (CompoundTag entityTag : entities) { + addEntityRemove(entityTag); + } } } } + } catch (Throwable e) { + MainUtil.handleError(e); + } finally { + if (FaweChangeSet.this.waitingCombined.decrementAndGet() <= 0) { + synchronized (FaweChangeSet.this.waitingAsync) { + FaweChangeSet.this.waitingAsync.notifyAll(); + } + synchronized (FaweChangeSet.this.waitingCombined) { + FaweChangeSet.this.waitingCombined.notifyAll(); + } + } } }; if (mainThread) { @@ -377,4 +363,4 @@ public abstract class FaweChangeSet implements ChangeSet { } }); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweStreamChangeSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweStreamChangeSet.java index 631fe0d36..ddf572ddd 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweStreamChangeSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweStreamChangeSet.java @@ -229,8 +229,8 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet { // skip mode int mode = is.read(); // origin - int x = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + (is.read() << 0)); - int z = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + (is.read() << 0)); + int x = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + is.read()); + int z = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + is.read()); setOrigin(x, z); setupStreamDelegates(mode); } @@ -328,7 +328,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet { public void addBiomeChange(int x, int z, BiomeType from, BiomeType to) { blockSize++; try { - OutputStream os = getBiomeOS(); + FaweOutputStream os = getBiomeOS(); os.write((byte) (x >> 24)); os.write((byte) (x >> 16)); os.write((byte) (x >> 8)); @@ -337,8 +337,8 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet { os.write((byte) (z >> 16)); os.write((byte) (z >> 8)); os.write((byte) (z)); - ((FaweOutputStream) os).writeVarInt(from.getInternalId()); - ((FaweOutputStream) os).writeVarInt(to.getInternalId()); + os.writeVarInt(from.getInternalId()); + os.writeVarInt(to.getInternalId()); } catch (Throwable e) { MainUtil.handleError(e); } @@ -412,7 +412,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet { change.z = posDel.readZ(is) + originZ; idDel.readCombined(is, change, dir); return change; - } catch (EOFException ignoreOEF) { + } catch (EOFException ignored) { } catch (Exception e) { e.printStackTrace(); MainUtil.handleError(e); @@ -448,7 +448,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet { } public Iterator getBiomeIterator(final boolean dir) throws IOException { - final InputStream is = getBiomeIS(); + final FaweInputStream is = getBiomeIS(); if (is == null) { return new ArrayList().iterator(); } @@ -460,14 +460,14 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet { try { int int1 = is.read(); if (int1 != -1) { - int x = ((int1 << 24) + (is.read() << 16) + (is.read() << 8) + (is.read() << 0)); - int z = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + (is.read() << 0)); - int from = ((FaweInputStream) is).readVarInt(); - int to = ((FaweInputStream) is).readVarInt(); + int x = ((int1 << 24) + (is.read() << 16) + (is.read() << 8) + is.read()); + int z = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + is.read()); + int from = is.readVarInt(); + int to = is.readVarInt(); change.setBiome(x, z, from, to); return change; } - } catch (EOFException ignoreOEF) { + } catch (EOFException ignored) { } catch (Exception e) { e.printStackTrace(); MainUtil.handleError(e); @@ -516,9 +516,6 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet { public Iterator getFullBlockIterator(BlockBag blockBag, int inventory, final boolean dir) throws IOException { final FaweInputStream is = new FaweInputStream(getBlockIS()); - if (is == null) { - return new ArrayList().iterator(); - } final MutableFullBlockChange change = new MutableFullBlockChange(blockBag, inventory, dir); return new Iterator() { private MutableFullBlockChange last = read(); @@ -530,7 +527,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet { change.z = posDel.readZ(is) + originZ; idDel.readCombined(is, change, dir); return change; - } catch (EOFException ignoreOEF) { + } catch (EOFException ignored) { } catch (Exception e) { e.printStackTrace(); MainUtil.handleError(e); @@ -576,10 +573,9 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet { public MutableEntityChange read() { try { - CompoundTag tag = (CompoundTag) is.readTag(); - change.tag = tag; + change.tag = (CompoundTag) is.readTag(); return change; - } catch (Exception ignoreOEF) { + } catch (Exception ignored) { } try { is.close(); @@ -626,10 +622,9 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet { public MutableTileChange read() { try { - CompoundTag tag = (CompoundTag) is.readTag(); - change.tag = tag; + change.tag = (CompoundTag) is.readTag(); return change; - } catch (Exception ignoreOEF) { + } catch (Exception ignored) { } try { is.close(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/DiskOptimizedClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/DiskOptimizedClipboard.java index 86152947d..678fe777f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/DiskOptimizedClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/DiskOptimizedClipboard.java @@ -24,6 +24,7 @@ import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; +import sun.misc.Unsafe; import java.io.Closeable; import java.io.File; @@ -209,7 +210,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { MainUtil.handleError(e); } this.braf = new RandomAccessFile(file, "rw"); - long volume = (long) width * (long) height * (long) length * 4l + (long) HEADER_SIZE; + long volume = (long) width * (long) height * (long) length * 4L + (long) HEADER_SIZE; braf.setLength(0); braf.setLength(volume); if (width * height * length != 0) { @@ -243,7 +244,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { length = dimensions.getBlockZ(); area = width * length; volume = width * length * height; - long size = width * height * length * 4l + HEADER_SIZE + (hasBiomes() ? area : 0); + long size = width * height * length * 4L + HEADER_SIZE + (hasBiomes() ? area : 0); if (braf.length() < size) { close(); this.braf = new RandomAccessFile(file, "rw"); @@ -505,7 +506,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { mbb.putInt(index, combined); boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); if (hasNbt) { - setTile(x, y, z, ((BaseBlock)block).getNbtData()); + setTile(x, y, z, block.getNbtData()); } return true; } catch (Exception e) { @@ -520,13 +521,13 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { int combined = block.getInternalId(); int index = (HEADER_SIZE) + (i << 2); mbb.putInt(index, combined); - boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); + boolean hasNbt = block instanceof BaseBlock && block.hasNbtData(); if (hasNbt) { int y = i / area; int newI = (i - (y * area)); int z = newI / width; int x = newI - z * width; - setTile(x, y, z, ((BaseBlock)block).getNbtData()); + setTile(x, y, z, block.getNbtData()); } return true; } catch (Exception e) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/EmptyClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/EmptyClipboard.java index 41062cffd..d838fb473 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/EmptyClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/EmptyClipboard.java @@ -2,8 +2,6 @@ package com.boydti.fawe.object.clipboard; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.world.block.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.clipboard.Clipboard; @@ -14,12 +12,13 @@ import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; +import javax.annotation.Nullable; import java.util.Collections; import java.util.List; -import javax.annotation.Nullable; public class EmptyClipboard implements Clipboard { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ResizableClipboardBuilder.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ResizableClipboardBuilder.java index 6c7dfa4fc..cd65424a2 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ResizableClipboardBuilder.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ResizableClipboardBuilder.java @@ -77,7 +77,7 @@ public class ResizableClipboardBuilder extends MemoryOptimizedHistory { int x = tileChange.tag.getInt("x"); int y = tileChange.tag.getInt("y"); int z = tileChange.tag.getInt("z"); - clipboard.setTile(x, y, z, tileChange.tag); + clipboard.setTile(BlockVector3.at(x,y,z), tileChange.tag); } } } catch (WorldEditException e) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BlockVectorSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BlockVectorSet.java index a16f43a9d..9b5ab33b6 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BlockVectorSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BlockVectorSet.java @@ -7,13 +7,9 @@ import com.sk89q.worldedit.math.MutableBlockVector3; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectIterator; -import java.util.AbstractCollection; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.Set; +import org.jetbrains.annotations.NotNull; + +import java.util.*; /** * The BlockVectorSet is a Memory optimized Set for storing BlockVectors @@ -35,23 +31,19 @@ public class BlockVectorSet extends AbstractCollection implements public BlockVector3 get(int index) { int count = 0; - ObjectIterator> iter = localSets.int2ObjectEntrySet().iterator(); - while (iter.hasNext()) { - Int2ObjectMap.Entry entry = iter.next(); + for (Int2ObjectMap.Entry entry : localSets.int2ObjectEntrySet()) { LocalBlockVectorSet set = entry.getValue(); int size = set.size(); int newSize = count + size; if (newSize > index) { int localIndex = index - count; MutableBlockVector3 pos = new MutableBlockVector3(set.getIndex(localIndex)); - if (pos != null) { - int pair = entry.getIntKey(); - int cx = MathMan.unpairX(pair); - int cz = MathMan.unpairY(pair); - pos.mutX((cx << 11) + pos.getBlockX()); - pos.mutZ((cz << 11) + pos.getBlockZ()); - return pos; - } + int pair = entry.getIntKey(); + int cx = MathMan.unpairX(pair); + int cz = MathMan.unpairY(pair); + pos.mutX((cx << 11) + pos.getBlockX()); + pos.mutZ((cz << 11) + pos.getBlockZ()); + return pos; } count += newSize; } @@ -83,11 +75,12 @@ public class BlockVectorSet extends AbstractCollection implements return false; } + @NotNull @Override public Iterator iterator() { final ObjectIterator> entries = localSets.int2ObjectEntrySet().iterator(); if (!entries.hasNext()) { - return new ArrayList().iterator(); + return Collections.emptyIterator(); } return new Iterator() { Int2ObjectMap.Entry entry = entries.next(); @@ -182,7 +175,7 @@ public class BlockVectorSet extends AbstractCollection implements } @Override - public boolean retainAll(Collection c) { + public boolean retainAll(@NotNull Collection c) { Objects.requireNonNull(c); boolean modified = false; Iterator it = iterator(); @@ -209,4 +202,4 @@ public class BlockVectorSet extends AbstractCollection implements public void clear() { localSets.clear(); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/HeightBoundExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/HeightBoundExtent.java index f69ef88f6..0949e106c 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/HeightBoundExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/HeightBoundExtent.java @@ -6,6 +6,7 @@ import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.regions.Region; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; public class HeightBoundExtent extends FaweRegionExtent { @@ -35,6 +36,6 @@ public class HeightBoundExtent extends FaweRegionExtent { @Override public Collection getRegions() { - return Arrays.asList(new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, min, max, Integer.MIN_VALUE, Integer.MAX_VALUE)); + return Collections.singletonList(new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, min, max, Integer.MIN_VALUE, Integer.MAX_VALUE)); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SingleRegionExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SingleRegionExtent.java index b991ad92d..5f859ae82 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SingleRegionExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SingleRegionExtent.java @@ -5,6 +5,7 @@ import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.regions.Region; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; public class SingleRegionExtent extends FaweRegionExtent { @@ -32,6 +33,6 @@ public class SingleRegionExtent extends FaweRegionExtent { @Override public Collection getRegions() { - return Arrays.asList(region); + return Collections.singletonList(region); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/DFSVisitor.java b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/DFSVisitor.java index dd9acaefd..bece42121 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/DFSVisitor.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/DFSVisitor.java @@ -103,7 +103,7 @@ public abstract class DFSVisitor implements Operation { BlockVector3 bv2 = BlockVector3.at(from.getX() + direction.x, from.getY() + direction.y, from.getZ() + direction.z); if (isVisitable(bv, bv2)) { adjacent = new Node(bv2.getBlockX(), bv2.getBlockY(), bv2.getBlockZ()); - if ((current.from == null || !adjacent.equals(current.from))) { + if ((!adjacent.equals(current.from))) { AtomicInteger adjacentCount = visited.get(adjacent); if (adjacentCount == null) { if (countAdd++ < maxBranch) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastChunkIterator.java b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastChunkIterator.java index 44c241f87..e45c70ed1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastChunkIterator.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastChunkIterator.java @@ -8,6 +8,7 @@ import com.boydti.fawe.util.ExtentTraverser; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.math.BlockVector2; +import org.jetbrains.annotations.NotNull; import java.util.Iterator; import javax.annotation.Nonnull; @@ -27,18 +28,19 @@ public class FastChunkIterator implements Iterable { } public FastChunkIterator(@Nonnull Iterable iter, @Nullable HasFaweQueue editSession) { - this(iter, (FaweQueue) (editSession != null ? editSession.getQueue() : null)); + this(iter, editSession != null ? editSession.getQueue() : null); } public FastChunkIterator(@Nonnull Iterable iter, @Nullable FaweQueue faweQueue) { this.iterable = iter; - this.queue = faweQueue != null && faweQueue instanceof MappedFaweQueue ? (MappedFaweQueue) faweQueue : null; + this.queue = faweQueue instanceof MappedFaweQueue ? (MappedFaweQueue) faweQueue : null; } public Iterable getIterable() { return iterable; } + @NotNull @Override public Iterator iterator() { if (queue == null || Settings.IMP.QUEUE.PRELOAD_CHUNKS <= 1) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweChunkManager.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweChunkManager.java index 9c98ff6e3..362f380e1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweChunkManager.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweChunkManager.java @@ -44,66 +44,57 @@ public class FaweChunkManager extends ChunkManager { @Override public void swap(final Location pos1, final Location pos2, final Location pos3, final Location pos4, final Runnable whenDone) { - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - synchronized (FaweChunkManager.class) { - EditSession sessionA = new EditSessionBuilder(pos1.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); - EditSession sessionB = new EditSessionBuilder(pos3.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); - CuboidRegion regionA = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); - CuboidRegion regionB = new CuboidRegion(BlockVector3.at(pos3.getX(), pos3.getY(), pos3.getZ()), BlockVector3.at(pos4.getX(), pos4.getY(), pos4.getZ())); - ForwardExtentCopy copyA = new ForwardExtentCopy(sessionA, regionA, sessionB, regionB.getMinimumPoint()); - ForwardExtentCopy copyB = new ForwardExtentCopy(sessionB, regionB, sessionA, regionA.getMinimumPoint()); - try { - Operations.completeLegacy(copyA); - Operations.completeLegacy(copyB); - sessionA.flushQueue(); - sessionB.flushQueue(); - } catch (MaxChangedBlocksException e) { - e.printStackTrace(); - } - TaskManager.IMP.task(whenDone); + TaskManager.IMP.async(() -> { + synchronized (FaweChunkManager.class) { + EditSession sessionA = new EditSessionBuilder(pos1.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); + EditSession sessionB = new EditSessionBuilder(pos3.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); + CuboidRegion regionA = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); + CuboidRegion regionB = new CuboidRegion(BlockVector3.at(pos3.getX(), pos3.getY(), pos3.getZ()), BlockVector3.at(pos4.getX(), pos4.getY(), pos4.getZ())); + ForwardExtentCopy copyA = new ForwardExtentCopy(sessionA, regionA, sessionB, regionB.getMinimumPoint()); + ForwardExtentCopy copyB = new ForwardExtentCopy(sessionB, regionB, sessionA, regionA.getMinimumPoint()); + try { + Operations.completeLegacy(copyA); + Operations.completeLegacy(copyB); + sessionA.flushQueue(); + sessionB.flushQueue(); + } catch (MaxChangedBlocksException e) { + e.printStackTrace(); } + TaskManager.IMP.task(whenDone); } }); } @Override public boolean copyRegion(final Location pos1, final Location pos2, final Location pos3, final Runnable whenDone) { - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - synchronized (FaweChunkManager.class) { - EditSession from = new EditSessionBuilder(pos1.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); - EditSession to = new EditSessionBuilder(pos3.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); - CuboidRegion region = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); - ForwardExtentCopy copy = new ForwardExtentCopy(from, region, to, BlockVector3.at(pos3.getX(), pos3.getY(), pos3.getZ())); - try { - Operations.completeLegacy(copy); - to.flushQueue(); - } catch (MaxChangedBlocksException e) { - e.printStackTrace(); - } + TaskManager.IMP.async(() -> { + synchronized (FaweChunkManager.class) { + EditSession from = new EditSessionBuilder(pos1.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); + EditSession to = new EditSessionBuilder(pos3.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); + CuboidRegion region = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); + ForwardExtentCopy copy = new ForwardExtentCopy(from, region, to, BlockVector3.at(pos3.getX(), pos3.getY(), pos3.getZ())); + try { + Operations.completeLegacy(copy); + to.flushQueue(); + } catch (MaxChangedBlocksException e) { + e.printStackTrace(); } - TaskManager.IMP.task(whenDone); } + TaskManager.IMP.task(whenDone); }); return true; } @Override public boolean regenerateRegion(final Location pos1, final Location pos2, boolean ignore, final Runnable whenDone) { - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - synchronized (FaweChunkManager.class) { - EditSession editSession = new EditSessionBuilder(pos1.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); - World world = editSession.getWorld(); - CuboidRegion region = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); - world.regenerate(region, editSession); - editSession.flushQueue(); - TaskManager.IMP.task(whenDone); - } + TaskManager.IMP.async(() -> { + synchronized (FaweChunkManager.class) { + EditSession editSession = new EditSessionBuilder(pos1.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); + World world = editSession.getWorld(); + CuboidRegion region = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); + world.regenerate(region, editSession); + editSession.flushQueue(); + TaskManager.IMP.task(whenDone); } }); return true; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweSchematicHandler.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweSchematicHandler.java index dd541e791..6eb019120 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweSchematicHandler.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweSchematicHandler.java @@ -1,11 +1,8 @@ package com.boydti.fawe.regions.general.plot; import com.boydti.fawe.FaweCache; -import com.boydti.fawe.object.FaweOutputStream; import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.clipboard.ReadOnlyClipboard; -import com.boydti.fawe.object.io.FastByteArrayOutputStream; -import com.boydti.fawe.object.io.FastByteArraysInputStream; import com.boydti.fawe.object.io.PGZIPOutputStream; import com.boydti.fawe.util.EditSessionBuilder; import com.boydti.fawe.util.IOUtil; @@ -22,15 +19,12 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompressedCompoundTag; import com.sk89q.jnbt.CompressedSchematicTag; import com.sk89q.jnbt.NBTOutputStream; -import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.SpongeSchematicWriter; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; -import net.jpountz.lz4.LZ4BlockInputStream; -import net.jpountz.lz4.LZ4BlockOutputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; @@ -45,7 +39,6 @@ import java.net.URL; import java.util.Map; import java.util.Set; import java.util.UUID; -import java.util.zip.GZIPInputStream; public class FaweSchematicHandler extends SchematicHandler { @Override @@ -62,25 +55,22 @@ public class FaweSchematicHandler extends SchematicHandler { @Override public void getCompoundTag(final String world, final Set regions, final RunnableVal whenDone) { - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - Location[] corners = MainUtil.getCorners(world, regions); - Location pos1 = corners[0]; - Location pos2 = corners[1]; - final CuboidRegion region = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); - final EditSession editSession = new EditSessionBuilder(world).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); + TaskManager.IMP.async(() -> { + Location[] corners = MainUtil.getCorners(world, regions); + Location pos1 = corners[0]; + Location pos2 = corners[1]; + final CuboidRegion region = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); + final EditSession editSession = new EditSessionBuilder(world).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); - final int mx = pos1.getX(); - final int my = pos1.getY(); - final int mz = pos1.getZ(); + final int mx = pos1.getX(); + final int my = pos1.getY(); + final int mz = pos1.getZ(); - ReadOnlyClipboard clipboard = ReadOnlyClipboard.of(editSession, region); + ReadOnlyClipboard clipboard = ReadOnlyClipboard.of(editSession, region); - Clipboard holder = new BlockArrayClipboard(region, clipboard); - CompressedSchematicTag tag = new CompressedSchematicTag(holder); - whenDone.run(tag); - } + Clipboard holder = new BlockArrayClipboard(region, clipboard); + CompressedSchematicTag tag = new CompressedSchematicTag(holder); + whenDone.run(tag); }); } @@ -109,7 +99,7 @@ public class FaweSchematicHandler extends SchematicHandler { } else { try (OutputStream stream = new FileOutputStream(tmp); NBTOutputStream output = new NBTOutputStream(new PGZIPOutputStream(stream))) { Map map = tag.getValue(); - output.writeNamedTag("Schematic", map.containsKey("Schematic") ? map.get("Schematic") : tag); + output.writeNamedTag("Schematic", map.getOrDefault("Schematic", tag)); } } } catch (FileNotFoundException e) { @@ -136,7 +126,7 @@ public class FaweSchematicHandler extends SchematicHandler { com.sk89q.jnbt.CompoundTag weTag = (com.sk89q.jnbt.CompoundTag) FaweCache.asTag(tag); try (NBTOutputStream nos = new NBTOutputStream(gzip)) { Map map = weTag.getValue(); - nos.writeNamedTag("Schematic", map.containsKey("Schematic") ? map.get("Schematic") : weTag); + nos.writeNamedTag("Schematic", map.getOrDefault("Schematic", weTag)); } } } catch (IOException e) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotTrim.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotTrim.java index 59426fa39..2bb7aa619 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotTrim.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotTrim.java @@ -88,8 +88,7 @@ public class PlotTrim { return false; } }); - ArrayList plots = new ArrayList<>(); - plots.addAll(PlotSquared.get().getPlots(area)); + ArrayList plots = new ArrayList<>(PlotSquared.get().getPlots(area)); if (ExpireManager.IMP != null) { plots.removeAll(ExpireManager.IMP.getPendingExpired()); } 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 4adbcdc35..38dc5b20a 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 @@ -50,13 +50,11 @@ public final class BrushCache { tool.setHolder(item); brushCache.put(key, tool); return tool; - } catch (Throwable ignore) { - ignore.printStackTrace(); + } catch (Exception throwable) { + throwable.printStackTrace(); Fawe.debug("Invalid brush for " + player + " holding " + item.getType() + ": " + json.getValue()); - if (item != null) { - item.setNbtData(null); - brushCache.remove(key); - } + item.setNbtData(null); + brushCache.remove(key); } finally { RECURSION.remove(); } @@ -123,4 +121,4 @@ public final class BrushCache { } return tool; } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/CachedMathMan.java b/worldedit-core/src/main/java/com/boydti/fawe/util/CachedMathMan.java index 1055cf95b..0da1cc9cf 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/CachedMathMan.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/CachedMathMan.java @@ -77,7 +77,7 @@ public class CachedMathMan { add = 0.0f; } - float invDiv = 1.0f / (((x < y) ? y : x) * INV_ATAN2_DIM_MINUS_1); + float invDiv = 1.0f / ((Math.max(x, y)) * INV_ATAN2_DIM_MINUS_1); int xi = (int) (x * invDiv); int yi = (int) (y * invDiv); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/ColorUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/ColorUtil.java index eecf0ef28..635e8247d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/ColorUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/ColorUtil.java @@ -26,7 +26,7 @@ public class ColorUtil { : Float.parseFloat(color)); switch (type) { case PARSE_ALPHA: - return (c < 0f) ? 0f : ((c > 1f) ? 1f : c); + return (c < 0f) ? 0f : (Math.min(c, 1f)); case PARSE_PERCENT: return (c <= 0f) ? 0f : ((c >= 100f) ? 1f : (c / 100f)); case PARSE_COMPONENT: diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/EditSessionBuilder.java b/worldedit-core/src/main/java/com/boydti/fawe/util/EditSessionBuilder.java index b6e3de434..a20c8d3d5 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/EditSessionBuilder.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/EditSessionBuilder.java @@ -54,7 +54,7 @@ public class EditSessionBuilder { public EditSessionBuilder(@Nonnull World world) { checkNotNull(world); this.world = world; - this.worldName = Fawe.imp().getWorldName(world); + this.worldName = world.getName(); } public EditSessionBuilder(@Nonnull String worldName) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/MathMan.java b/worldedit-core/src/main/java/com/boydti/fawe/util/MathMan.java index 64eabfc60..711de5ff8 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/MathMan.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/MathMan.java @@ -81,11 +81,11 @@ public class MathMan { } public static int clamp(int check, int min, int max) { - return check > max ? max : (check < min ? min : check); + return check > max ? max : (Math.max(check, min)); } public static float clamp(float check, float min, float max) { - return check > max ? max : (check < min ? min : check); + return check > max ? max : (Math.max(check, min)); } public static double hypot(final double... pars) { @@ -104,7 +104,7 @@ public class MathMan { return sum; } - public static final int wrap(int value, int min, int max) { + public static int wrap(int value, int min, int max) { if (max < min) { return value; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/ReflectionUtils.java b/worldedit-core/src/main/java/com/boydti/fawe/util/ReflectionUtils.java index 05f51b8fc..40b609b95 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/ReflectionUtils.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/ReflectionUtils.java @@ -7,11 +7,7 @@ import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; +import java.util.*; import sun.reflect.ConstructorAccessor; import sun.reflect.FieldAccessor; @@ -126,7 +122,7 @@ public class ReflectionUtils { Class[] additionalTypes, Object[] additionalValues) throws Exception { Object[] parms = new Object[additionalValues.length + 2]; parms[0] = value; - parms[1] = Integer.valueOf(ordinal); + parms[1] = ordinal; System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length); return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms)); } @@ -332,12 +328,12 @@ public class ReflectionUtils { } public static Method[] sortMethods(Method[] methods) { - Arrays.sort(methods, (o1, o2) -> o1.getName().compareTo(o2.getName())); + Arrays.sort(methods, Comparator.comparing(Method::getName)); return methods; } public static Field[] sortFields(Field[] fields) { - Arrays.sort(fields, (o1, o2) -> o1.getName().compareTo(o2.getName())); + Arrays.sort(fields, Comparator.comparing(Field::getName)); return fields; } 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 240cc5428..12fff9e0d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java @@ -42,7 +42,6 @@ import com.boydti.fawe.object.changeset.CPUOptimizedChangeSet; import com.boydti.fawe.object.changeset.DiskStorageHistory; import com.boydti.fawe.object.changeset.FaweChangeSet; import com.boydti.fawe.object.changeset.MemoryOptimizedHistory; -import com.boydti.fawe.object.collection.BlockVectorSet; import com.boydti.fawe.object.collection.LocalBlockVectorSet; import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.object.extent.FastWorldEditExtent; @@ -79,28 +78,18 @@ import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.ChangeSetExtent; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.MaskingExtent; -import com.sk89q.worldedit.extent.cache.LastAccessExtentCache; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.BlockBagExtent; -import com.sk89q.worldedit.extent.reorder.ChunkBatchingExtent; -import com.sk89q.worldedit.extent.reorder.MultiStageReorder; -import com.sk89q.worldedit.extent.validation.BlockChangeLimiter; -import com.sk89q.worldedit.extent.validation.DataValidatorExtent; -import com.sk89q.worldedit.extent.world.BlockQuirkExtent; -import com.sk89q.worldedit.extent.world.ChunkLoadingExtent; -import com.sk89q.worldedit.extent.world.FastModeExtent; import com.sk89q.worldedit.extent.world.SurvivalModeExtent; import com.sk89q.worldedit.function.GroundFunction; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.RegionMaskingFilter; -import com.sk89q.worldedit.function.block.BlockDistributionCounter; import com.sk89q.worldedit.function.block.BlockReplace; import com.sk89q.worldedit.function.block.Naturalizer; import com.sk89q.worldedit.function.generator.ForestGenerator; import com.sk89q.worldedit.function.generator.GardenPatchGenerator; import com.sk89q.worldedit.function.mask.BlockMask; import com.sk89q.worldedit.function.mask.BlockMaskBuilder; -import com.sk89q.worldedit.function.mask.BlockStateMask; import com.sk89q.worldedit.function.mask.BlockTypeMask; import com.sk89q.worldedit.function.mask.BoundedHeightMask; import com.sk89q.worldedit.function.mask.ExistingBlockMask; @@ -116,7 +105,6 @@ import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; -import com.sk89q.worldedit.function.pattern.WaterloggedRemover; import com.sk89q.worldedit.function.util.RegionOffset; import com.sk89q.worldedit.function.visitor.DirectionalVisitor; import com.sk89q.worldedit.function.visitor.DownwardVisitor; @@ -127,14 +115,12 @@ import com.sk89q.worldedit.function.visitor.RecursiveVisitor; import com.sk89q.worldedit.function.visitor.RegionVisitor; import com.sk89q.worldedit.history.UndoContext; import com.sk89q.worldedit.history.change.BlockChange; -import com.sk89q.worldedit.history.changeset.BlockOptimizedHistory; import com.sk89q.worldedit.history.changeset.ChangeSet; import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.ExpressionException; import com.sk89q.worldedit.internal.expression.runtime.EvaluationException; import com.sk89q.worldedit.internal.expression.runtime.RValue; import com.sk89q.worldedit.internal.expression.runtime.ExpressionTimeoutException; -import com.sk89q.worldedit.internal.expression.runtime.RValue; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.MathUtils; @@ -159,14 +145,11 @@ import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment; import com.sk89q.worldedit.util.Countable; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.TreeGenerator; -import com.sk89q.worldedit.util.collection.DoubleArrayList; import com.sk89q.worldedit.util.eventbus.EventBus; -import com.sk89q.worldedit.world.NullWorld; import com.sk89q.worldedit.world.SimpleWorld; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.*; -import com.sk89q.worldedit.world.registry.LegacyMapper; import com.sk89q.worldedit.world.weather.WeatherType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -190,6 +173,7 @@ import static com.sk89q.worldedit.regions.Regions.minimumBlockY; * {@link Extent}s that are chained together. For example, history is logged * using the {@link ChangeSetExtent}.

*/ +@SuppressWarnings({"FieldCanBeLocal"}) public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, SimpleWorld, AutoCloseable { private static final Logger log = LoggerFactory.getLogger(EditSession.class); @@ -204,7 +188,31 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, BEFORE_CHANGE } - private World world; + /** + * Reorder mode for {@link EditSession#setReorderMode(ReorderMode)}. + * NOT FUNCTIONAL IN FAWE AS OF June 3,2019 + * + * MULTI_STAGE = Multi stage reorder, may not be great with mods. + * FAST = Use the fast mode. Good for mods. + * NONE = Place blocks without worrying about placement order. + */ + public enum ReorderMode { + MULTI_STAGE("multi"), + FAST("fast"), + NONE("none"); + + private String displayName; + + ReorderMode(String displayName) { + this.displayName = displayName; + } + + public String getDisplayName() { + return this.displayName; + } + } + + private final World world; private String worldName; private FaweQueue queue; private boolean wrapped; @@ -233,11 +241,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, this(null, world, queue, player, limit, changeSet, allowedRegions, autoQueue, fastmode, checkMemory, combineStages, blockBag, bus, event); } - @Deprecated - public EditSession(@Nullable String worldName, @Nullable World world, @Nullable FaweQueue queue, @Nullable FawePlayer player, @Nullable FaweLimit limit, @Nullable FaweChangeSet changeSet, @Nullable RegionWrapper[] allowedRegions, @Nullable Boolean autoQueue, @Nullable Boolean fastmode, @Nullable Boolean checkMemory, @Nullable Boolean combineStages, @Nullable BlockBag blockBag, @Nullable EventBus bus, @Nullable EditSessionEvent event) { - this(worldName, world, queue, player, limit, changeSet, (Region[]) allowedRegions, autoQueue, fastmode, checkMemory, combineStages, blockBag, bus, event); - } - public EditSession(@Nullable String worldName, @Nullable World world, @Nullable FaweQueue queue, @Nullable FawePlayer player, @Nullable FaweLimit limit, @Nullable FaweChangeSet changeSet, @Nullable Region[] allowedRegions, @Nullable Boolean autoQueue, @Nullable Boolean fastmode, @Nullable Boolean checkMemory, @Nullable Boolean combineStages, @Nullable BlockBag blockBag, @Nullable EventBus bus, @Nullable EditSessionEvent event) { super(world); this.worldName = worldName == null ? world == null ? queue == null ? "" : queue.getWorldName() : Fawe.imp().getWorldName(world) : worldName; @@ -396,41 +399,16 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, setExtent(this.extent); } - /** - * Create a new instance. - * - * @param world a world - * @param maxBlocks the maximum number of blocks that can be changed, or -1 to use no limit - * @deprecated use {@link WorldEdit#getEditSessionFactory()} to create {@link EditSession}s - */ - @Deprecated - public EditSession(final World world, final int maxBlocks) { - this(world, maxBlocks, null); - } - - /** - * Create a new instance. - * - * @param world a world - * @param maxBlocks the maximum number of blocks that can be changed, or -1 to use no limit - * @param blockBag the block bag to set, or null to use none - * @deprecated use {@link WorldEdit#getEditSessionFactory()} to create {@link EditSession}s - */ - @Deprecated - public EditSession(final World world, final int maxBlocks, @Nullable final BlockBag blockBag) { - this(WorldEdit.getInstance().getEventBus(), world, maxBlocks, blockBag, new EditSessionEvent(world, null, maxBlocks, null)); - } - /** * Construct the object with a maximum number of blocks and a block bag. * - * @param eventBus the event bus - * @param world the world + * @param eventBus the event bus + * @param world the world * @param maxBlocks the maximum number of blocks that can be changed, or -1 to use no limit - * @param blockBag an optional {@link BlockBag} to use, otherwise null - * @param event the event to call with the extent + * @param blockBag an optional {@link BlockBag} to use, otherwise null + * @param event the event to call with the extent */ - public EditSession(final EventBus eventBus, World world, final int maxBlocks, @Nullable final BlockBag blockBag, EditSessionEvent event) { + public EditSession(EventBus eventBus, World world, int maxBlocks, @Nullable BlockBag blockBag, EditSessionEvent event) { this(world, null, null, null, null, null, true, null, null, null, blockBag, eventBus, event); } @@ -582,7 +560,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } @Deprecated - private AbstractDelegateExtent wrapExtent(final AbstractDelegateExtent extent, final EventBus eventBus, EditSessionEvent event, final Stage stage) { + private AbstractDelegateExtent wrapExtent(Extent extent, EventBus eventBus, EditSessionEvent event, Stage stage) { event = event.clone(stage); event.setExtent(extent); eventBus.post(event); @@ -595,7 +573,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } if (!(toReturn instanceof AbstractDelegateExtent)) { Fawe.debug("Extent " + toReturn + " must be AbstractDelegateExtent"); - return extent; + return (AbstractDelegateExtent) extent; } if (toReturn != extent) { String className = toReturn.getClass().getName().toLowerCase(); @@ -618,7 +596,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } } } - return extent; + return (AbstractDelegateExtent) extent; } // pkg private for TracedEditSession only, may later become public API @@ -635,6 +613,25 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, setBatchingChunks(true); } + /** + * Sets the {@link ReorderMode} of this EditSession, and flushes the session. + * + * @param reorderMode The reorder mode + */ + public void setReorderMode(ReorderMode reorderMode) { + //TODO Not working yet. + } + + //TODO: Reorder mode. + /** + * Get the reorder mode. + * + * @return the reorder mode + */ + public ReorderMode getReorderMode() { + return null; + } + /** * Get the world. * @@ -688,6 +685,9 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } /** + * Get the maximum number of blocks that can be changed. -1 will be returned + * if it the limit disabled. + * * @return the limit (>= 0) or -1 for no limit * @see #getLimit() */ @@ -701,7 +701,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * * @param limit the limit (>= 0) or -1 for no limit */ - public void setBlockChangeLimit(final int limit) { + public void setBlockChangeLimit(int limit) { // Nothing } @@ -709,7 +709,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * Returns queue status. * * @return whether the queue is enabled - * @deprecated Use {@link EditSession#getReorderMode()} with MULTI_STAGE instead. */ @Deprecated public boolean isQueueEnabled() { @@ -718,9 +717,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, /** * Queue certain types of block for better reproduction of those blocks. - * - * Uses {@link ReorderMode#MULTI_STAGE} - * @deprecated Use {@link EditSession#setReorderMode(ReorderMode)} with MULTI_STAGE instead. */ @Deprecated public void enableQueue() { @@ -731,7 +727,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, */ @Deprecated public void disableQueue() { - if (this.isQueueEnabled()) { + if (isQueueEnabled()) { this.flushQueue(); } } @@ -861,7 +857,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, /** * Set whether fast mode is enabled. - *

+ * *

Fast mode may skip lighting checks or adjacent block * notification.

* @@ -927,7 +923,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * * @param blockBag the block bag to set, or null to use none */ - public void setBlockBag(final BlockBag blockBag) { + public void setBlockBag(BlockBag blockBag) { this.blockBag = blockBag; } @@ -1001,12 +997,17 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, public void setBatchingChunks(boolean batchingChunks) { } + /** + * Disable all buffering extents. + * + * @see #setBatchingChunks(boolean) + */ public void disableBuffering() { } /** * Get the number of blocks changed, including repeated block changes. - *

+ * *

This number may not be accurate.

* * @return the number of block changes @@ -1099,17 +1100,10 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @param z the Z coordinate * @param minY minimal height * @param maxY maximal height - * @param filter a mask of blocks to consider, or null to consider any solid (movement-blocking) block * @return height of highest block found or 'minY' */ public int getHighestTerrainBlock(int x, int z, int minY, int maxY) { - for (int y = maxY; y >= minY; --y) { - BlockVector3 pt = BlockVector3.at(x, y, z); - if (getBlock(pt).getBlockType().getMaterial().isMovementBlocker()) { - return y; - } - } - return minY; + return getHighestTerrainBlock(x, z, minY, maxY, null); } /** @@ -1125,10 +1119,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, public int getHighestTerrainBlock(int x, int z, int minY, int maxY, Mask filter) { for (int y = maxY; y >= minY; --y) { BlockVector3 pt = BlockVector3.at(x, y, z); - if (filter.test(pt)) { + if (filter == null + ? getBlock(pt).getBlockType().getMaterial().isMovementBlocker() + : filter.test(pt)) { return y; } } + return minY; } @@ -1178,7 +1175,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, throw new RuntimeException("Unexpected exception", e); } } - + /** * Set a block, bypassing history but still utilizing block re-ordering. * @@ -1248,10 +1245,10 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * Set a block (only if a previous block was not there) if {@link Math#random()} * returns a number less than the given probability. * - * @param position the position - * @param block the block + * @param position the position + * @param block the block * @param probability a probability between 0 and 1, inclusive - * @return whether a block was changed + * @return Whether the block changed -- not entirely dependable * @throws MaxChangedBlocksException thrown if too many blocks are changed */ public boolean setChanceBlockIfAir(final BlockVector3 position, final BaseBlock block, final double probability) throws MaxChangedBlocksException { @@ -1307,8 +1304,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * * @param editSession a new {@link EditSession} to perform the undo in */ - public void undo(final EditSession editSession) { - final UndoContext context = new UndoContext(); + public void undo(EditSession editSession) { + UndoContext context = new UndoContext(); context.setExtent(editSession.bypassAll); ChangeSet changeSet = getChangeSet(); editSession.getQueue().setChangeTask(null); @@ -1331,8 +1328,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * * @param editSession a new {@link EditSession} to perform the redo in */ - public void redo(final EditSession editSession) { - final UndoContext context = new UndoContext(); + public void redo(EditSession editSession) { + UndoContext context = new UndoContext(); context.setExtent(editSession.bypassAll); ChangeSet changeSet = getChangeSet(); editSession.getQueue().setChangeTask(null); @@ -1373,7 +1370,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } @Override - public List getEntities(final Region region) { + public List getEntities(Region region) { return this.extent.getEntities(region); } @@ -1381,7 +1378,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, public List getEntities() { return this.extent.getEntities(); } - + /** * Closing an EditSession {@linkplain #flushSession() flushes its buffers}. */ @@ -1494,11 +1491,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, /** * Count the number of blocks of a list of types in a region. * - * @param region the region + * @param region the region * @param searchBlocks the list of blocks to search * @return the number of blocks that matched the pattern */ - public int countBlocks(final Region region, final Set searchBlocks) { + public int countBlocks(Region region, Set searchBlocks) { Mask mask = new BlockMaskBuilder().addBlocks(searchBlocks).build(extent); RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { @Override @@ -1582,24 +1579,25 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, /** * Fills an area recursively in the X/Z directions. * - * @param origin the location to start from - * @param block the block to fill with - * @param radius the radius of the spherical area to fill - * @param depth the maximum depth, starting from the origin + * @param origin the location to start from + * @param block the block to fill with + * @param radius the radius of the spherical area to fill + * @param depth the maximum depth, starting from the origin * @param recursive whether a breadth-first search should be performed * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ public > int fillXZ(BlockVector3 origin, B block, double radius, int depth, boolean recursive) throws MaxChangedBlocksException { - return fillXZ(origin, block, radius, depth, recursive); + return fillXZ(origin, new BlockPattern(block), radius, depth, recursive); } + /** * Fills an area recursively in the X/Z directions. * - * @param origin the origin to start the fill from - * @param pattern the pattern to fill with - * @param radius the radius of the spherical area to fill, with 0 as the smallest radius - * @param depth the maximum depth, starting from the origin, with 1 as the smallest depth + * @param origin the origin to start the fill from + * @param pattern the pattern to fill with + * @param radius the radius of the spherical area to fill, with 0 as the smallest radius + * @param depth the maximum depth, starting from the origin, with 1 as the smallest depth * @param recursive whether a breadth-first search should be performed * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed @@ -1609,8 +1607,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, checkNotNull(pattern); checkArgument(radius >= 0, "radius >= 0"); checkArgument(depth >= 1, "depth >= 1"); - final MaskIntersection mask = new MaskIntersection(new RegionMask(new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), new BoundedHeightMask(Math.max( - (origin.getBlockY() - depth) + 1, getMinimumPoint().getBlockY()), Math.min(getMaximumPoint().getBlockY(), origin.getBlockY())), Masks.negate(new ExistingBlockMask(EditSession.this))); + + MaskIntersection mask = new MaskIntersection( + new RegionMask(new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), + new BoundedHeightMask( + Math.max((origin.getBlockY() - depth) + 1, getMinimumPoint().getBlockY()), + Math.min(getMaximumPoint().getBlockY(), origin.getBlockY())), + Masks.negate(new ExistingBlockMask(this))); // Want to replace blocks BlockReplace replace = new BlockReplace(this, pattern); @@ -1628,6 +1631,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, // Execute Operations.completeBlindly(visitor); + return this.changes = visitor.getAffected(); } @@ -1635,8 +1639,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * Remove a cuboid above the given position with a given apothem and a given height. * * @param position base position - * @param apothem an apothem of the cuboid (on the XZ plane), where the minimum is 1 - * @param height the height of the cuboid, where the minimum is 1 + * @param apothem an apothem of the cuboid (on the XZ plane), where the minimum is 1 + * @param height the height of the cuboid, where the minimum is 1 * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ @@ -1647,8 +1651,9 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, Region region = new CuboidRegion( getWorld(), // Causes clamping of Y range - position.add(-apothem + 1, 0, -apothem + 1), position.add(apothem - 1, height - 1, apothem - 1)); - Pattern pattern = BlockTypes.AIR.getDefaultState(); + position.add(-apothem + 1, 0, -apothem + 1), + position.add(apothem - 1, height - 1, apothem - 1)); + Pattern pattern = new BlockPattern(BlockTypes.AIR.getDefaultState()); return setBlocks(region, pattern); } @@ -1656,8 +1661,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * Remove a cuboid below the given position with a given apothem and a given height. * * @param position base position - * @param apothem an apothem of the cuboid (on the XZ plane), where the minimum is 1 - * @param height the height of the cuboid, where the minimum is 1 + * @param apothem an apothem of the cuboid (on the XZ plane), where the minimum is 1 + * @param height the height of the cuboid, where the minimum is 1 * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ @@ -1666,18 +1671,20 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, checkArgument(apothem >= 1, "apothem >= 1"); checkArgument(height >= 1, "height >= 1"); - Region region = new CuboidRegion(getWorld(), // Causes clamping of Y range - position.add(-apothem + 1, 0, -apothem + 1), position.add(apothem - 1, -height + 1, apothem - 1)); - Pattern pattern = (BlockTypes.AIR.getDefaultState()); + Region region = new CuboidRegion( + getWorld(), // Causes clamping of Y range + position.add(-apothem + 1, 0, -apothem + 1), + position.add(apothem - 1, -height + 1, apothem - 1)); + Pattern pattern = new BlockPattern(BlockTypes.AIR.getDefaultState()); return setBlocks(region, pattern); } /** * Remove blocks of a certain type nearby a given position. * - * @param position center position of cuboid - * @param mask the block type to match - * @param apothem an apothem of the cuboid, where the minimum is 1 + * @param position center position of cuboid + * @param mask the mask to match + * @param apothem an apothem of the cuboid, where the minimum is 1 * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ @@ -1734,7 +1741,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, getWorld(), // Causes clamping of Y range position.add(adjustment.multiply(-1)), position.add(adjustment)); - Pattern pattern = (BlockTypes.AIR.getDefaultState()); + Pattern pattern = new BlockPattern(BlockTypes.AIR.getDefaultState()); return replaceBlocks(region, mask, pattern); } @@ -1742,11 +1749,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * Sets all the blocks inside a region to a given block type. * * @param region the region - * @param block the block + * @param block the block * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public > int setBlocks(final Region region, final B block) throws MaxChangedBlocksException { + public > int setBlocks(Region region, B block) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(block); boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); @@ -1806,7 +1813,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @throws MaxChangedBlocksException thrown if too many blocks are changed */ public > int replaceBlocks(Region region, Set filter, B replacement) throws MaxChangedBlocksException { - return replaceBlocks(region, filter, (replacement)); + return replaceBlocks(region, filter, new BlockPattern(replacement)); } /** @@ -1838,9 +1845,10 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, checkNotNull(region); checkNotNull(mask); checkNotNull(pattern); - final BlockReplace replace = new BlockReplace(EditSession.this, pattern); - final RegionMaskingFilter filter = new RegionMaskingFilter(mask, replace); - final RegionVisitor visitor = new RegionVisitor(region, filter, queue instanceof MappedFaweQueue ? (MappedFaweQueue) queue : null); + + BlockReplace replace = new BlockReplace(this, pattern); + RegionMaskingFilter filter = new RegionMaskingFilter(mask, replace); + RegionVisitor visitor = new RegionVisitor(region, filter, queue instanceof MappedFaweQueue ? (MappedFaweQueue) queue : null); Operations.completeBlindly(visitor); return this.changes = visitor.getAffected(); } @@ -1855,8 +1863,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return the number of blocks placed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int center(final Region region, final Pattern pattern) { + public int center(Region region, Pattern pattern) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(pattern); @@ -1877,9 +1884,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public > int makeCuboidFaces(final Region region, final B block) { - return this.makeCuboidFaces(region, (Pattern) (block)); + public > int makeCuboidFaces(Region region, B block) throws MaxChangedBlocksException { + return makeCuboidFaces(region, new BlockPattern(block)); } /** @@ -1890,14 +1896,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int makeCuboidFaces(final Region region, final Pattern pattern) { + public int makeCuboidFaces( Region region, Pattern pattern) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(pattern); - final CuboidRegion cuboid = CuboidRegion.makeCuboid(region); - final Region faces = cuboid.getFaces(); - return this.setBlocks(faces, pattern); + CuboidRegion cuboid = CuboidRegion.makeCuboid(region); + Region faces = cuboid.getFaces(); + return setBlocks(faces, pattern); } /** @@ -1910,13 +1915,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int makeFaces(final Region region, final Pattern pattern) throws WorldEditException { + public int makeFaces(final Region region, Pattern pattern) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(pattern); if (region instanceof CuboidRegion) { - return this.makeCuboidFaces(region, pattern); + return makeCuboidFaces(region, pattern); } else { return new RegionShape(region).generate(this, pattern, true); } @@ -1932,9 +1936,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public > int makeCuboidWalls(final Region region, final B block) { - return this.makeCuboidWalls(region, (Pattern) (block)); + public > int makeCuboidWalls(Region region, B block) throws MaxChangedBlocksException { + return makeCuboidWalls(region, new BlockPattern(block)); } /** @@ -1946,14 +1949,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int makeCuboidWalls(final Region region, final Pattern pattern) { + public int makeCuboidWalls(Region region, Pattern pattern) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(pattern); - final CuboidRegion cuboid = CuboidRegion.makeCuboid(region); - final Region faces = cuboid.getWalls(); - return this.setBlocks(faces, pattern); + CuboidRegion cuboid = CuboidRegion.makeCuboid(region); + Region faces = cuboid.getWalls(); + return setBlocks(faces, pattern); } /** @@ -1966,13 +1968,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int makeWalls(final Region region, final Pattern pattern) throws WorldEditException { + public int makeWalls(final Region region, Pattern pattern) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(pattern); if (region instanceof CuboidRegion) { - return this.makeCuboidWalls(region, pattern); + return makeCuboidWalls(region, pattern); } else { for (BlockVector3 position : region) { int x = position.getBlockX(); @@ -1997,7 +1998,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, */ public > int overlayCuboidBlocks(Region region, B block) throws MaxChangedBlocksException { checkNotNull(block); - return overlayCuboidBlocks(region, (block)); + return overlayCuboidBlocks(region, new BlockPattern(block)); } /** @@ -2009,12 +2010,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int overlayCuboidBlocks(final Region region, final Pattern pattern) { + public int overlayCuboidBlocks(Region region, Pattern pattern) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(pattern); - final BlockReplace replace = new BlockReplace(EditSession.this, pattern); - final RegionOffset offset = new RegionOffset(BlockVector3.at(0, 1, 0), replace); + BlockReplace replace = new BlockReplace(this, pattern); + RegionOffset offset = new RegionOffset(BlockVector3.UNIT_Y, replace); int minY = region.getMinimumPoint().getBlockY(); int maxY = Math.min(getMaximumPoint().getBlockY(), region.getMaximumPoint().getBlockY() + 1); SurfaceRegionFunction surface = new SurfaceRegionFunction(this, offset, minY, maxY); @@ -2031,11 +2031,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int naturalizeCuboidBlocks(final Region region) { + public int naturalizeCuboidBlocks(Region region) throws MaxChangedBlocksException { checkNotNull(region); - final Naturalizer naturalizer = new Naturalizer(EditSession.this); - final FlatRegion flatRegion = Regions.asFlatRegion(region); - final LayerVisitor visitor = new LayerVisitor(flatRegion, minimumBlockY(region), maximumBlockY(region), naturalizer); + + Naturalizer naturalizer = new Naturalizer(this); + FlatRegion flatRegion = Regions.asFlatRegion(region); + LayerVisitor visitor = new LayerVisitor(flatRegion, minimumBlockY(region), maximumBlockY(region), naturalizer); Operations.completeBlindly(visitor); return this.changes = naturalizer.getAffected(); } @@ -2054,13 +2055,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int stackCuboidRegion(final Region region, final BlockVector3 dir, final int count, final boolean copyAir, boolean copyEntities, boolean copyBiomes) { + public int stackCuboidRegion(Region region, BlockVector3 dir, int count, boolean copyAir, boolean copyEntities, boolean copyBiomes) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(dir); checkArgument(count >= 1, "count >= 1 required"); - final BlockVector3 size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); - final BlockVector3 to = region.getMinimumPoint(); - final ForwardExtentCopy copy = new ForwardExtentCopy(EditSession.this, region, EditSession.this, to); + BlockVector3 size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); + BlockVector3 to = region.getMinimumPoint(); + ForwardExtentCopy copy = new ForwardExtentCopy(this, region, this, to); copy.setCopyingEntities(copyEntities); copy.setCopyBiomes(copyBiomes); copy.setRepetitions(count); @@ -2072,7 +2073,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, setSourceMask(null); } if (!copyAir) { - copy.setSourceMask(new ExistingBlockMask(EditSession.this)); + copy.setSourceMask(new ExistingBlockMask(this)); } Operations.completeBlindly(copy); return this.changes = copy.getAffected(); @@ -2089,7 +2090,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks moved * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int moveRegion(final Region region, final BlockVector3 dir, final int distance, final boolean copyAir, final BlockStateHolder replacement) { + public int moveRegion(Region region, BlockVector3 dir, int distance, boolean copyAir, BlockStateHolder replacement) throws MaxChangedBlocksException { return moveRegion(region, dir, distance, copyAir, true, false, replacement); } @@ -2113,10 +2114,10 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, queue.dequeue(); } - final ForwardExtentCopy copy = new ForwardExtentCopy(EditSession.this, region, EditSession.this, to); + ForwardExtentCopy copy = new ForwardExtentCopy(this, region, this, to); if (replacement == null) replacement = nullBlock; - final BlockReplace remove = replacement instanceof ExistingPattern ? null : new BlockReplace(EditSession.this, replacement); + final BlockReplace remove = replacement instanceof ExistingPattern ? null : new BlockReplace(this, replacement); copy.setCopyBiomes(copyBiomes); copy.setCopyingEntities(copyEntities); @@ -2124,12 +2125,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, copy.setRepetitions(1); Mask sourceMask = getSourceMask(); if (sourceMask != null) { - new MaskTraverser(sourceMask).reset(EditSession.this); + new MaskTraverser(sourceMask).reset(this); copy.setSourceMask(sourceMask); setSourceMask(null); } if (!copyAir) { - copy.setSourceMask(new ExistingBlockMask(EditSession.this)); + copy.setSourceMask(new ExistingBlockMask(this)); } Operations.completeBlindly(copy); return this.changes = copy.getAffected(); @@ -2146,8 +2147,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks moved * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int moveCuboidRegion(final Region region, final BlockVector3 dir, final int distance, final boolean copyAir, final Pattern replacement) { - return this.moveRegion(region, dir, distance, copyAir, true, false, replacement); + public int moveCuboidRegion(Region region, BlockVector3 dir, int distance, boolean copyAir, Pattern replacement) { + return moveRegion(region, dir, distance, copyAir, true, false, replacement); } /** @@ -2158,11 +2159,20 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int drainArea(final BlockVector3 origin, final double radius) { + public int drainArea(BlockVector3 origin, double radius) throws MaxChangedBlocksException { return drainArea(origin, radius, false); } - public int drainArea(final BlockVector3 origin, final double radius, boolean waterLogged) { + /** + * Drain nearby pools of water or lava, optionally removed waterlogged states from blocks. + * + * @param origin the origin to drain from, which will search a 3x3 area + * @param radius the radius of the removal, where a value should be 0 or greater + * @param waterlogged true to make waterlogged blocks non-waterlogged as well + * @return number of blocks affected + * @throws MaxChangedBlocksException thrown if too many blocks are changed + */ + public int drainArea(BlockVector3 origin, double radius, boolean waterlogged) throws MaxChangedBlocksException { checkNotNull(origin); checkArgument(radius >= 0, "radius >= 0 required"); Mask liquidMask; @@ -2180,11 +2190,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), liquidMask); - final BlockReplace replace = new BlockReplace(EditSession.this, BlockTypes.AIR.getDefaultState()); - final RecursiveVisitor visitor = new RecursiveVisitor(mask, replace, (int) (radius * 2 + 1), this); + BlockReplace replace = new BlockReplace(this, BlockTypes.AIR.getDefaultState()); + RecursiveVisitor visitor = new RecursiveVisitor(mask, replace, (int) (radius * 2 + 1), this); // Around the origin in a 3x3 block - for (final BlockVector3 position : CuboidRegion.fromCenter(origin, 1)) { + for (BlockVector3 position : CuboidRegion.fromCenter(origin, 1)) { if (mask.test(position)) { visitor.visit(position); } @@ -2199,10 +2209,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * * @param origin the original position * @param radius the radius to fix + * @param fluid the type of the fluid * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int fixLiquid(final BlockVector3 origin, final double radius, BlockType fluid) { + public int fixLiquid(BlockVector3 origin, double radius, BlockType fluid) throws MaxChangedBlocksException { checkNotNull(origin); checkArgument(radius >= 0, "radius >= 0 required"); @@ -2216,7 +2227,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, MaskIntersection mask = new MaskIntersection( new BoundedHeightMask(0, Math.min(origin.getBlockY(), getWorld().getMaxY())), new RegionMask(new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), - blockMask); + blockMask + ); BlockReplace replace = new BlockReplace(this, new BlockPattern(fluid.getDefaultState())); NonRisingVisitor visitor = new NonRisingVisitor(mask, replace); @@ -2229,6 +2241,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } Operations.completeLegacy(visitor); + return visitor.getAffected(); } @@ -2259,7 +2272,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makeCylinder(BlockVector3 pos, final Pattern block, double radiusX, double radiusZ, int height, final boolean filled) { + public int makeCylinder(BlockVector3 pos, Pattern block, double radiusX, double radiusZ, int height, boolean filled) throws MaxChangedBlocksException{ return makeCylinder(pos, block, radiusX, radiusZ, height, 0, filled); } @@ -2473,7 +2486,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makeSphere(BlockVector3 pos, Pattern block, double radius, boolean filled) { + public int makeSphere(BlockVector3 pos, Pattern block, double radius, boolean filled) throws MaxChangedBlocksException { return makeSphere(pos, block, radius, radius, radius, filled); } @@ -2489,8 +2502,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makeSphere(final BlockVector3 pos, final Pattern block, double radiusX, double radiusY, double radiusZ, final boolean filled) { -// System.out.println("Make sphere"); + public int makeSphere(BlockVector3 pos, Pattern block, double radiusX, double radiusY, double radiusZ, boolean filled) throws MaxChangedBlocksException { radiusX += 0.5; radiusY += 0.5; radiusZ += 0.5; @@ -2579,12 +2591,14 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, */ public int makePyramid(BlockVector3 position, Pattern block, int size, boolean filled) throws MaxChangedBlocksException { int affected = 0; + int height = size; for (int y = 0; y <= height; ++y) { size--; for (int x = 0; x <= size; ++x) { for (int z = 0; z <= size; ++z) { + if ((filled && z <= size && x <= size) || z == size || x == size) { if (setBlock(position.add(x, y, z), block)) { @@ -2623,15 +2637,18 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, int ox = position.getBlockX(); int oy = position.getBlockY(); int oz = position.getBlockZ(); + BlockState air = BlockTypes.AIR.getDefaultState(); BlockState water = BlockTypes.WATER.getDefaultState(); + int ceilRadius = (int) Math.ceil(radius); for (int x = ox - ceilRadius; x <= ox + ceilRadius; ++x) { for (int z = oz - ceilRadius; z <= oz + ceilRadius; ++z) { if ((BlockVector3.at(x, oy, z)).distanceSq(position) > radiusSq) { continue; } - for (int y = maxY; y >= 1; --y) { + + for (int y = world.getMaxY(); y >= 1; --y) { BlockVector3 pt = BlockVector3.at(x, y, z); BlockType id = getBlock(pt).getBlockType(); @@ -2644,8 +2661,9 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, ++affected; } } else if (id.getMaterial().isAir()) { - continue; + continue; } + break; } } @@ -2679,30 +2697,33 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, if ((BlockVector3.at(x, oy, z)).distanceSq(position) > radiusSq) { continue; } - for (int y = maxY; y >= 1; --y) { + + for (int y = world.getMaxY(); y >= 1; --y) { BlockVector3 pt = BlockVector3.at(x, y, z); BlockType id = getBlock(pt).getBlockType(); + if (id.getMaterial().isAir()) { continue; } + // Ice! if (id == BlockTypes.WATER) { if (setBlock(pt, ice)) { ++affected; } - break; + break; } // Snow should not cover these blocks - if (id.getMaterial().isTranslucent()) { + if (id.getMaterial().isTranslucent()) { // Add snow on leaves if (!BlockCategories.LEAVES.contains(id)) { break; - } + } } // Too high? - if (y == maxY) { + if (y == world.getMaxY()) { break; } @@ -2723,13 +2744,10 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * * @param position a position * @param radius a radius + * @param onlyNormalDirt only affect normal dirt (data value 0) * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int green(final BlockVector3 position, final double radius) { - return this.green(position, radius, false); - } - public int green(BlockVector3 position, double radius, boolean onlyNormalDirt) throws MaxChangedBlocksException { int affected = 0; @@ -2739,8 +2757,10 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, final int oy = position.getBlockY(); final int oz = position.getBlockZ(); + final BlockState grass = BlockTypes.GRASS_BLOCK.getDefaultState(); + final int ceilRadius = (int) Math.ceil(radius); - for (int x = ox - ceilRadius; x <= (ox + ceilRadius); ++x) { + for (int x = ox - ceilRadius; x <= ox + ceilRadius; ++x) { int dx = x - ox; int dx2 = dx * dx; for (int z = oz - ceilRadius; z <= (oz + ceilRadius); ++z) { @@ -2750,19 +2770,20 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, continue; } loop: - for (int y = maxY; y >= 1; --y) { - BlockType block = getBlockType(x, y, z); - switch (block.getInternalId()) { - case BlockID.DIRT: - this.setBlock(x, y, z, BlockTypes.GRASS_BLOCK.getDefaultState()); + for (int y = world.getMaxY(); y >= 1; --y) { + final BlockVector3 pt = BlockVector3.at(x, y, z); + final BlockState block = getBlock(pt); + + if (block.getBlockType() == BlockTypes.DIRT || + (!onlyNormalDirt && block.getBlockType() == BlockTypes.COARSE_DIRT)) { + if (setBlock(pt, grass)) { break loop; - case BlockID.WATER: - case BlockID.LAVA: - break loop; - default: - if (block.getMaterial().isMovementBlocker()) { - break loop; - } + } + break; + } else if (block.getBlockType() == BlockTypes.WATER || block.getBlockType() == BlockTypes.LAVA) { + break loop; + } else if (block.getBlockType().getMaterial().isMovementBlocker()) { + break loop; } } } @@ -2771,18 +2792,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return changes; } - /** - * Makes pumpkin patches randomly in an area around the given position. - * - * @param position the base position - * @param apothem the apothem of the (square) area - * @return number of patches created - * @throws MaxChangedBlocksException thrown if too many blocks are changed - */ - public int makePumpkinPatches(final BlockVector3 position, final int apothem) { - return makePumpkinPatches(position, apothem, 0.02); - } - /** * Makes pumpkin patches randomly in an area around the given position. * @@ -2791,17 +2800,20 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of patches created * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makePumpkinPatches(final BlockVector3 position, final int apothem, double density) { + public int makePumpkinPatches(BlockVector3 position, int apothem) throws MaxChangedBlocksException { // We want to generate pumpkins - final GardenPatchGenerator generator = new GardenPatchGenerator(EditSession.this); + GardenPatchGenerator generator = new GardenPatchGenerator(this); generator.setPlant(GardenPatchGenerator.getPumpkinPattern()); // In a region of the given radius - final FlatRegion region = new CuboidRegion(EditSession.this.getWorld(), // Causes clamping of Y range - position.add(-apothem, -5, -apothem), position.add(apothem, 10, apothem)); + FlatRegion region = new CuboidRegion( + getWorld(), // Causes clamping of Y range + position.add(-apothem, -5, -apothem), + position.add(apothem, 10, apothem)); + double density = 0.02; - final GroundFunction ground = new GroundFunction(new ExistingBlockMask(EditSession.this), generator); - final LayerVisitor visitor = new LayerVisitor(region, minimumBlockY(region), maximumBlockY(region), ground); + GroundFunction ground = new GroundFunction(new ExistingBlockMask(this), generator); + LayerVisitor visitor = new LayerVisitor(region, minimumBlockY(region), maximumBlockY(region), ground); visitor.setMask(new NoiseFilter2D(new RandomNoise(), density)); Operations.completeBlindly(visitor); return this.changes = ground.getAffected(); @@ -2817,7 +2829,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of trees created * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makeForest(final BlockVector3 basePosition, final int size, final double density, TreeGenerator.TreeType treeType) { + public int makeForest(BlockVector3 basePosition, int size, double density, TreeGenerator.TreeType treeType) throws MaxChangedBlocksException { try { for (int x = basePosition.getBlockX() - size; x <= (basePosition.getBlockX() + size); ++x) { for (int z = basePosition.getBlockZ() - size; z <= (basePosition.getBlockZ() + size); ++z) { @@ -2919,11 +2931,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * Generate a shape for the given expression. * * @param region the region to generate the shape in - * @param zero the coordinate origin for x/y/z variables - * @param unit the scale of the x/y/z/ variables - * @param pattern the default material to make the shape from - * @param expressionString the expression defining the shape - * @param hollow whether the shape should be hollow * @return number of blocks changed * @throws ExpressionException * @throws MaxChangedBlocksException @@ -2986,8 +2993,22 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return distribution; } - public int makeShape(final Region region, final Vector3 zero, final Vector3 unit, final Pattern pattern, final String expressionString, final boolean hollow) throws ExpressionException, - MaxChangedBlocksException { + /** + * Generate a shape for the given expression. + * + * @param region the region to generate the shape in + * @param zero the coordinate origin for x/y/z variables + * @param unit the scale of the x/y/z/ variables + * @param pattern the default material to make the shape from + * @param expressionString the expression defining the shape + * @param hollow whether the shape should be hollow + * @return number of blocks changed + * @throws ExpressionException + * @throws MaxChangedBlocksException + */ + public int makeShape(final Region region, final Vector3 zero, final Vector3 unit, + final Pattern pattern, final String expressionString, final boolean hollow) + throws ExpressionException, MaxChangedBlocksException { final Expression expression = Expression.compile(expressionString, "x", "y", "z", "type", "data"); expression.optimize(); @@ -3030,9 +3051,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return changed; } - public int deformRegion(final Region region, final Vector3 zero, final Vector3 unit, final String expressionString) throws ExpressionException, MaxChangedBlocksException { + public int deformRegion(final Region region, final Vector3 zero, final Vector3 unit, final String expressionString) + throws ExpressionException, MaxChangedBlocksException { final Expression expression = Expression.compile(expressionString, "x", "y", "z"); expression.optimize(); + final RValue x = expression.getVariable("x", false).optimize(); final RValue y = expression.getVariable("y", false).optimize(); final RValue z = expression.getVariable("z", false).optimize(); @@ -3073,12 +3096,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @param region the region to hollow out. * @param thickness the thickness of the shell to leave (manhattan distance) * @param pattern The block pattern to use + * * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int hollowOutRegion(final Region region, final int thickness, final Pattern pattern) { + public int hollowOutRegion(Region region, int thickness, Pattern pattern) throws MaxChangedBlocksException { try { - final Set outside = new LocalBlockVectorSet(); + final Set outside = new LocalBlockVectorSet(); final BlockVector3 min = region.getMinimumPoint(); final BlockVector3 max = region.getMaximumPoint(); @@ -3112,24 +3136,27 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } for (int i = 1; i < thickness; ++i) { - final Set newOutside = new LocalBlockVectorSet(); + final Set newOutside = new LocalBlockVectorSet(); outer: for (BlockVector3 position : region) { for (BlockVector3 recurseDirection : recurseDirections) { BlockVector3 neighbor = position.add(recurseDirection); + if (outside.contains(neighbor)) { newOutside.add(position); continue outer; } } } + outside.addAll(newOutside); } outer: for (BlockVector3 position : region) { for (BlockVector3 recurseDirection : recurseDirections) { BlockVector3 neighbor = position.add(recurseDirection); - if (outside.contains(neighbor)) { - continue outer; + + if (outside.contains(neighbor)) { + continue outer; } } this.changes++; @@ -3158,7 +3185,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int drawLine(final Pattern pattern, final BlockVector3 pos1, final BlockVector3 pos2, final double radius, final boolean filled, boolean flat) { + public int drawLine(Pattern pattern, BlockVector3 pos1, BlockVector3 pos2, double radius, boolean filled, boolean flat) { LocalBlockVectorSet vset = new LocalBlockVectorSet(); boolean notdrawn = true; @@ -3217,7 +3244,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, newVset = this.getHollowed(newVset); } } - return this.setBlocks(newVset, pattern); + return setBlocks(newVset, pattern); } /** @@ -3235,11 +3262,15 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int drawSpline(final Pattern pattern, final List nodevectors, final double tension, final double bias, final double continuity, final double quality, final double radius, final boolean filled) throws WorldEditException { - LocalBlockVectorSet vset = new LocalBlockVectorSet(); - final List nodes = new ArrayList<>(nodevectors.size()); + public int drawSpline(Pattern pattern, List nodevectors, double tension, double bias, + double continuity, double quality, double radius, boolean filled) + throws MaxChangedBlocksException { + + LocalBlockVectorSet vset = new LocalBlockVectorSet(); + List nodes = new ArrayList<>(nodevectors.size()); + + Interpolation interpol = new KochanekBartelsInterpolation(); - final KochanekBartelsInterpolation interpol = new KochanekBartelsInterpolation(); for (BlockVector3 nodevector : nodevectors) { Node n = new Node(nodevector.toVector3()); n.setTension(tension); @@ -3249,7 +3280,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } interpol.setNodes(nodes); - final double splinelength = interpol.arcLength(0, 1); + double splinelength = interpol.arcLength(0, 1); for (double loop = 0; loop <= 1; loop += 1D / splinelength / quality) { final BlockVector3 tipv = interpol.getPosition(loop).toBlockPoint(); if (radius == 0) { @@ -3264,19 +3295,21 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, if (!filled) { newVset = this.getHollowed(newVset); } - return this.setBlocks(newVset, pattern); + return setBlocks(newVset, pattern); } return changes; } - private Set getBallooned(final Set vset, final double radius) { + private Set getBallooned(Set vset, double radius) { if (radius < 1) { return vset; } - final LocalBlockVectorSet returnset = new LocalBlockVectorSet(); - final int ceilrad = (int) Math.ceil(radius); - for (final BlockVector3 v : vset) { - final int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ(); + LocalBlockVectorSet returnset = new LocalBlockVectorSet(); + int ceilrad = (int) Math.ceil(radius); + + for (BlockVector3 v : vset) { + int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ(); + for (int loopx = tipx - ceilrad; loopx <= (tipx + ceilrad); loopx++) { for (int loopy = tipy - ceilrad; loopy <= (tipy + ceilrad); loopy++) { for (int loopz = tipz - ceilrad; loopz <= (tipz + ceilrad); loopz++) { @@ -3343,6 +3376,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, private void recurseHollow(Region region, BlockVector3 origin, Set outside) { final LocalBlockVectorSet queue = new LocalBlockVectorSet(); + while (!queue.isEmpty()) { Iterator iter = queue.iterator(); while (iter.hasNext()) { @@ -3368,7 +3402,9 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } } - public int makeBiomeShape(final Region region, final Vector3 zero, final Vector3 unit, final BiomeType biomeType, final String expressionString, final boolean hollow) throws ExpressionException, MaxChangedBlocksException { + public int makeBiomeShape(final Region region, final Vector3 zero, final Vector3 unit, final BiomeType biomeType, + final String expressionString, final boolean hollow) + throws ExpressionException, MaxChangedBlocksException { final Vector2 zero2D = zero.toVector2(); final Vector2 unit2D = unit.toVector2(); @@ -3391,6 +3427,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return null; } + // TODO: Allow biome setting via a script variable (needs BiomeType<->int mapping) return defaultBiomeType; } catch (Exception e) { log.warn("Failed to create shape", e); @@ -3401,6 +3438,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, int changed = shape.generate(this, biomeType, hollow); return changed; } + private static final BlockVector3[] recurseDirections = { Direction.NORTH.toBlockVector(), Direction.EAST.toBlockVector(), @@ -3409,11 +3447,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, Direction.UP.toBlockVector(), Direction.DOWN.toBlockVector(), }; - private double lengthSq(final double x, final double y, final double z) { + + private static double lengthSq(double x, double y, double z) { return (x * x) + (y * y) + (z * z); } - private double lengthSq(final double x, final double z) { + private static double lengthSq(double x, double z) { return (x * x) + (z * z); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/GenerationCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/GenerationCommands.java index a92f3cd2a..9edebfa3d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/GenerationCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/GenerationCommands.java @@ -293,15 +293,14 @@ public class GenerationCommands extends MethodCommands { @Command( aliases = {"pumpkins"}, - usage = "[size=10] [density=0.02]", + usage = "[size=10]", desc = "Generate pumpkin patches", - min = 0, max = 2 ) @CommandPermissions("worldedit.generation.pumpkins") @Logging(POSITION) - public void pumpkins(Player player, LocalSession session, EditSession editSession, @Optional("10") int apothem, @Optional("0.02") double density) throws WorldEditException, ParameterException { - int affected = editSession.makePumpkinPatches(session.getPlacementPosition(player), apothem, density); + public void pumpkins(Player player, LocalSession session, EditSession editSession, @Optional("10") int apothem) throws WorldEditException, ParameterException { + int affected = editSession.makePumpkinPatches(session.getPlacementPosition(player), apothem); BBC.COMMAND_PUMPKIN.send(player, affected); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/HelpBuilder.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/HelpBuilder.java index 0434c5209..1804eb85f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/HelpBuilder.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/HelpBuilder.java @@ -9,22 +9,18 @@ import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.util.command.*; import com.sk89q.worldedit.util.command.parametric.AParametricCallable; +import org.jetbrains.annotations.NotNull; import java.util.*; public abstract class HelpBuilder implements Runnable { private final CommandCallable callable; private final CommandContext args; - private final String prefix; private final int perPage; - public HelpBuilder(CommandCallable callable, CommandContext args, final String prefix, int perPage) { - if (callable == null) { - callable = WorldEdit.getInstance().getPlatformManager().getCommandManager().getDispatcher(); - } + HelpBuilder(@NotNull CommandCallable callable, CommandContext args, int perPage) { this.callable = callable; this.args = args; - this.prefix = prefix; this.perPage = perPage; } @@ -33,7 +29,6 @@ public abstract class HelpBuilder implements Runnable { try { CommandCallable callable = this.callable; int page = -1; - String category = null; int effectiveLength = args.argsLength(); // Detect page from args @@ -84,11 +79,7 @@ public abstract class HelpBuilder implements Runnable { } group = group.replace("/", ""); group = StringMan.toProperCase(group); - Map queue = grouped.get(group); - if (queue == null) { - queue = new LinkedHashMap<>(); - grouped.put(group, queue); - } + Map queue = grouped.computeIfAbsent(group, k -> new LinkedHashMap<>()); if (c instanceof Dispatcher) { for (CommandMapping m : ((Dispatcher) c).getCommands()) { queue.put(m, mapping.getPrimaryAlias() + " "); @@ -190,28 +181,25 @@ public abstract class HelpBuilder implements Runnable { return; } } -// else - { - Collections.sort(aliases, new PrimaryAliasComparator(CommandManager.COMMAND_CLEAN_PATTERN)); + aliases.sort(new PrimaryAliasComparator(CommandManager.COMMAND_CLEAN_PATTERN)); - // Calculate pagination - int offset = perPage * Math.max(0, page); - int pageTotal = (int) Math.ceil(aliases.size() / (double) perPage); + // Calculate pagination + int offset = perPage * Math.max(0, page); + int pageTotal = (int) Math.ceil(aliases.size() / (double) perPage); - // Box - if (offset >= aliases.size()) { - displayFailure(String.format(BBC.getPrefix() + "There is no page %d (total number of pages is %d).", page + 1, pageTotal)); - } else { - int end = Math.min(offset + perPage, aliases.size()); - List subAliases = aliases.subList(offset, end); - List subPrefixes = prefixes.subList(offset, end); - Map commandMap = new LinkedHashMap<>(); - for (int i = 0; i < subAliases.size(); i++) { - commandMap.put(subAliases.get(i), subPrefixes.get(i)); - } - String visitedString = Joiner.on(" ").join(visited); - displayCommands(commandMap, visitedString, page, pageTotal, effectiveLength); + // Box + if (offset >= aliases.size()) { + displayFailure(String.format(BBC.getPrefix() + "There is no page %d (total number of pages is %d).", page + 1, pageTotal)); + } else { + int end = Math.min(offset + perPage, aliases.size()); + List subAliases = aliases.subList(offset, end); + List subPrefixes = prefixes.subList(offset, end); + Map commandMap = new LinkedHashMap<>(); + for (int i = 0; i < subAliases.size(); i++) { + commandMap.put(subAliases.get(i), subPrefixes.get(i)); } + String visitedString = Joiner.on(" ").join(visited); + displayCommands(commandMap, visitedString, page, pageTotal, effectiveLength); } } else { String cmd = (WorldEdit.getInstance().getConfiguration().noDoubleSlash ? "" : "/") + Joiner.on(" ").join(visited); 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 437e6db74..fd49d224c 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 @@ -53,14 +53,11 @@ import com.sk89q.worldedit.command.util.CreatureButcher; import com.sk89q.worldedit.command.util.EntityRemover; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.Player; -import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.extension.factory.DefaultTransformParser; import com.sk89q.worldedit.extension.factory.parser.mask.DefaultMaskParser; -import com.sk89q.worldedit.extension.factory.parser.pattern.ClipboardPatternParser; import com.sk89q.worldedit.extension.factory.parser.pattern.DefaultPatternParser; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Capability; -import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; @@ -78,16 +75,12 @@ import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CylinderRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.command.binding.Range; -import com.sk89q.worldedit.session.SessionOwner; import com.sk89q.worldedit.util.command.CommandCallable; import com.sk89q.worldedit.util.command.CommandMapping; import com.sk89q.worldedit.util.command.Dispatcher; -import com.sk89q.worldedit.util.command.PrimaryAliasComparator; import com.sk89q.worldedit.util.command.binding.Text; import com.sk89q.worldedit.util.command.parametric.Optional; -import com.sk89q.worldedit.util.command.parametric.ParameterData; import com.sk89q.worldedit.world.World; -import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockTypes; import javax.imageio.ImageIO; @@ -96,7 +89,6 @@ import java.awt.image.BufferedImage; import java.io.File; import java.io.FileFilter; import java.io.IOException; -import java.lang.reflect.Type; import java.net.URI; import java.nio.file.Files; import java.util.*; @@ -105,9 +97,6 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; - -import static com.sk89q.minecraft.util.commands.Logging.LogMode.PLACEMENT; - /** * Utility commands. */ @@ -460,7 +449,7 @@ public class UtilityCommands extends MethodCommands { we.checkMaxRadius(size); final boolean onlyNormalDirt = !args.hasFlag('f'); - final int affected = editSession.green(session.getPlacementPosition(player), size); + final int affected = editSession.green(session.getPlacementPosition(player), size, onlyNormalDirt); BBC.VISITOR_BLOCK.send(player, affected); } @@ -997,13 +986,13 @@ public class UtilityCommands extends MethodCommands { } public static void help(CommandContext args, WorldEdit we, Actor actor) { - help(args, we, actor, "/", null); + help(args, we, actor, "/", we.getPlatformManager().getCommandManager().getDispatcher()); } public static void help(CommandContext args, WorldEdit we, Actor actor, String prefix, CommandCallable callable) { final int perPage = actor instanceof Player ? 12 : 20; // More pages for console - HelpBuilder builder = new HelpBuilder(callable, args, prefix, perPage) { + HelpBuilder builder = new HelpBuilder(callable, args, perPage) { @Override public void displayFailure(String message) { actor.printError(message); @@ -1023,7 +1012,7 @@ public class UtilityCommands extends MethodCommands { String s1 = Commands.getAlias(UtilityCommands.class, "/help") + " " + entry.getKey(); String s2 = entry.getValue().size() + ""; msg.text(BBC.HELP_ITEM_ALLOWED, "&a" + s1, s2); - msg.tooltip(StringMan.join(entry.getValue().keySet(), ", ", cm -> cm.getPrimaryAlias())); + msg.tooltip(StringMan.join(entry.getValue().keySet(), ", ", CommandMapping::getPrimaryAlias)); msg.command(s1); msg.newline(); } 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 3cb322eea..57617749e 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 @@ -20,11 +20,7 @@ package com.sk89q.worldedit.command.composition; import com.boydti.fawe.config.BBC; -import com.boydti.fawe.object.FaweChunk; -import com.boydti.fawe.object.FawePlayer; -import com.boydti.fawe.object.FaweQueue; -import com.boydti.fawe.object.RegionWrapper; -import com.boydti.fawe.object.RunnableVal; +import com.boydti.fawe.object.*; import com.boydti.fawe.object.extent.FaweRegionExtent; import com.boydti.fawe.util.MainUtil; import com.google.common.base.Joiner; @@ -36,8 +32,6 @@ import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.WorldEdit; - -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.function.Contextual; @@ -53,14 +47,11 @@ import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.command.argument.CommandArgs; import com.sk89q.worldedit.util.command.composition.CommandExecutor; import com.sk89q.worldedit.util.command.composition.SimpleCommand; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockTypes; import java.lang.reflect.Field; import java.util.List; - import static com.google.common.base.Preconditions.checkNotNull; public class SelectionCommand extends SimpleCommand { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/ShapedBrushCommand.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/ShapedBrushCommand.java index f22fceb4e..3de5dc6ed 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/ShapedBrushCommand.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/ShapedBrushCommand.java @@ -82,7 +82,7 @@ public class ShapedBrushCommand extends SimpleCommand { WorldEdit.getInstance().getPlatformManager().getCommandManager().getExceptionConverter().convert(e); } - player.print(BBC.getPrefix() + "Set brush to " + factory); + player.print("Set brush to " + factory); return true; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java index d1ef66637..12a663ed3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java @@ -37,7 +37,7 @@ public class CylinderBrush implements Brush { @Override public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { if (pattern == null) { - pattern = (BlockTypes.COBBLESTONE.getDefaultState()); + pattern = new BlockPattern(BlockTypes.COBBLESTONE.getDefaultState()); } editSession.makeCylinder(position, pattern, size, size, height, true); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultBlockParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultBlockParser.java index 09d4ce435..d8dbe0a63 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultBlockParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultBlockParser.java @@ -192,7 +192,8 @@ public class DefaultBlockParser extends InputParser { state = LegacyMapper.getInstance().getBlockFromLegacy(type.getLegacyCombinedId() >> 4, data); } } - } catch (NumberFormatException ignore) {} + } catch (NumberFormatException e) { + } } if (state == null) { @@ -220,10 +221,10 @@ public class DefaultBlockParser extends InputParser { throw new InputParseException("Your selection is not complete."); } state = world.getBlock(primaryPosition); - } else if (typeString.equalsIgnoreCase("hand")) { + } else if ("hand".equalsIgnoreCase(typeString)) { // Get the block type from the item in the user's hand. state = getBlockInHand(context.requireActor(), HandSide.MAIN_HAND); - } else if (typeString.equalsIgnoreCase("offhand")) { + } else if ("offhand".equalsIgnoreCase(typeString)) { // Get the block type from the item in the user's off hand. state = getBlockInHand(context.requireActor(), HandSide.OFF_HAND); } else if (typeString.matches("slot[0-9]+")) { @@ -241,7 +242,7 @@ public class DefaultBlockParser extends InputParser { BaseItem item = slottable.getItem(slot); if (!item.getType().hasBlockType()) { - throw new InputParseException(BBC.getPrefix() + "You're not holding a block!"); + throw new InputParseException("You're not holding a block!"); } state = item.getType().getBlockType().getDefaultState(); nbt = item.getNbtData(); @@ -249,7 +250,7 @@ public class DefaultBlockParser extends InputParser { BlockType type = BlockTypes.parse(typeString.toLowerCase()); if (type != null) state = type.getDefaultState(); if (state == null) { - throw new NoMatchException(BBC.getPrefix() + "Does not match a valid block type: '" + input + "'"); + throw new NoMatchException("Does not match a valid block type: '" + input + "'"); } } if (nbt == null) nbt = state.getNbtData(); @@ -309,10 +310,9 @@ public class DefaultBlockParser extends InputParser { break; } } - Platform capability = worldEdit.getPlatformManager().queryCapability(Capability.USER_COMMANDS); - if (!capability.isValidMobType(mobName)) { + if (!worldEdit.getPlatformManager().queryCapability(Capability.USER_COMMANDS).isValidMobType(mobName)) { final String finalMobName = mobName.toLowerCase(); - throw new SuggestInputParseException(BBC.getPrefix() + "Unknown mob type '" + mobName + "'", mobName, () -> Stream.of(MobType.values()) + throw new SuggestInputParseException("Unknown mob type '" + mobName + "'", mobName, () -> Stream.of(MobType.values()) .map(m -> m.getName().toLowerCase()) .filter(s -> s.startsWith(finalMobName)) .collect(Collectors.toList())); @@ -350,4 +350,4 @@ public class DefaultBlockParser extends InputParser { } return holder; } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java index 9334567ee..167fe0495 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java @@ -170,10 +170,8 @@ public final class CommandManager { builder.setAuthorizer(new ActorAuthorizer()); builder.setDefaultCompleter(new UserCommandCompleter(platformManager)); builder.addBinding(new WorldEditBinding(worldEdit)); - builder.addBinding(new PatternBinding(worldEdit), com.sk89q.worldedit.function.pattern.Pattern.class); builder.addBinding(new MaskBinding(worldEdit), com.sk89q.worldedit.function.mask.Mask.class); - builder.addInvokeListener(new LegacyCommandsHandler()); builder.addInvokeListener(new CommandLoggingHandler(worldEdit, commandLog)); @@ -371,7 +369,7 @@ public final class CommandManager { setupDispatcher(); } - public void unregister() { + void unregister() { dynamicHandler.setHandler(null); } @@ -401,8 +399,7 @@ public final class CommandManager { public void handleCommandOnCurrentThread(CommandEvent event) { Actor actor = platformManager.createProxyActor(event.getActor()); - final String args = event.getArguments(); - final String[] split = commandDetection(args.split(" ")); + String[] split = commandDetection(event.getArguments().split(" ")); // No command found! if (!dispatcher.contains(split[0])) { return; @@ -410,7 +407,7 @@ public final class CommandManager { if (!actor.isPlayer()) { actor = FakePlayer.wrap(actor.getName(), actor.getUniqueId(), actor); } - final LocalSession session = worldEdit.getSessionManager().get(actor); + LocalSession session = worldEdit.getSessionManager().get(actor); Request.request().setSession(session); if (actor instanceof Entity) { Extent extent = ((Entity) actor).getExtent(); @@ -419,7 +416,8 @@ public final class CommandManager { } } LocalConfiguration config = worldEdit.getConfiguration(); - final CommandLocals locals = new CommandLocals(); + + CommandLocals locals = new CommandLocals(); final FawePlayer fp = FawePlayer.wrap(actor); if (fp == null) { throw new IllegalArgumentException("FAWE doesn't support: " + actor); @@ -430,7 +428,7 @@ public final class CommandManager { if (actor instanceof Player) { Player player = (Player) actor; Player unwrapped = LocationMaskedPlayerWrapper.unwrap(player); - actor = new LocationMaskedPlayerWrapper((Player) unwrapped, player.getLocation(), true) { + actor = new LocationMaskedPlayerWrapper(unwrapped, player.getLocation(), true) { @Override public boolean hasPermission(String permission) { if (!super.hasPermission(permission)) { @@ -452,8 +450,7 @@ public final class CommandManager { }; } locals.put(Actor.class, actor); - final Actor finalActor = actor; - locals.put("arguments", args); + locals.put("arguments", event.getArguments()); ThrowableSupplier task = () -> dispatcher.call(Joiner.on(" ").join(split), locals, new String[0]); @@ -527,7 +524,6 @@ public final class CommandManager { } } catch (Throwable e) { Exception faweException = FaweException.get(e); - String message = e.getMessage(); if (faweException != null) { BBC.WORLDEDIT_CANCEL_REASON.send(actor, faweException.getMessage()); } else { @@ -541,7 +537,7 @@ public final class CommandManager { editSession.flushQueue(); worldEdit.flushBlockBag(locals.get(Actor.class), editSession); session.remember(editSession); - final long time = System.currentTimeMillis() - start; + long time = System.currentTimeMillis() - start; if (time > 1000) { BBC.ACTION_COMPLETE.send(actor, (time / 1000d)); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/AbstractDelegateExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/AbstractDelegateExtent.java index d3021c391..be54386b0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/AbstractDelegateExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/AbstractDelegateExtent.java @@ -43,8 +43,12 @@ import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.registry.BundledBlockData; import java.util.List; + import javax.annotation.Nullable; +/** + * A base class for {@link Extent}s that merely passes extents onto another. + */ public class AbstractDelegateExtent implements LightingExtent { private transient final Extent extent; protected MutableBlockVector3 mutable = new MutableBlockVector3(0, 0, 0); @@ -264,8 +268,7 @@ public class AbstractDelegateExtent implements LightingExtent { } @Override - public @Nullable - Operation commit() { + public @Nullable Operation commit() { Operation ours = commitBefore(); Operation other = null; if (extent != this) other = extent.commit(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/ChangeSetExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/ChangeSetExtent.java index f1f68924d..5a8f771f8 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/ChangeSetExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/ChangeSetExtent.java @@ -40,11 +40,10 @@ import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockStateHolder; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; -import static com.google.common.base.Preconditions.checkNotNull; +import javax.annotation.Nullable; /** * Stores changes to a {@link ChangeSet}. diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/MaskingExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/MaskingExtent.java index 9e8eaf8b8..b92caaa5f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/MaskingExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/MaskingExtent.java @@ -30,22 +30,18 @@ import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; - -import static com.google.common.base.Preconditions.checkNotNull; - /** * Requires that all mutating methods pass a given {@link Mask}. */ public class MaskingExtent extends AbstractDelegateExtent { private Mask mask; -// private MutableBlockVector3 mutable = new MutableBlockVector3(); /** * Create a new instance. * * @param extent the extent - * @param mask the mask + * @param mask the mask */ public MaskingExtent(Extent extent, Mask mask) { super(extent); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/NullExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/NullExtent.java index ec4c276a7..2d59364ea 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/NullExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/NullExtent.java @@ -34,10 +34,11 @@ import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; -import javax.annotation.Nullable; import java.util.Collections; import java.util.List; +import javax.annotation.Nullable; + /** * An extent that returns air blocks for all blocks and does not * pass on any changes. diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/BlockArrayClipboard.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/BlockArrayClipboard.java index 819329d64..0359c51b8 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/BlockArrayClipboard.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/BlockArrayClipboard.java @@ -28,12 +28,6 @@ import com.boydti.fawe.object.extent.LightingExtent; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.WorldEditException; - -import com.sk89q.worldedit.world.biome.BiomeType; -import com.sk89q.worldedit.world.block.BlockState; -import static com.google.common.base.Preconditions.checkNotNull; - -import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.operation.Operation; @@ -41,15 +35,18 @@ import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; +import com.sk89q.worldedit.world.biome.BiomeType; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockTypes; +import javax.annotation.Nullable; import java.io.Closeable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; -import javax.annotation.Nullable; - import static com.google.common.base.Preconditions.checkNotNull; @@ -63,27 +60,21 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable private BlockVector3 origin; public FaweClipboard IMP; private BlockVector3 size; - private int mx; - private int my; - private int mz; private BlockStateHolder[][][] blocks; private final List entities = new ArrayList<>(); - + public BlockArrayClipboard(Region region) { checkNotNull(region); this.region = region.clone(); this.size = getDimensions(); this.IMP = Settings.IMP.CLIPBOARD.USE_DISK ? new DiskOptimizedClipboard(size.getBlockX(), size.getBlockY(), size.getBlockZ()) : new MemoryOptimizedClipboard(size.getBlockX(), size.getBlockY(), size.getBlockZ()); this.origin = region.getMinimumPoint(); - this.mx = origin.getBlockX(); - this.my = origin.getBlockY(); - this.mz = origin.getBlockZ(); this.blocks = new BlockStateHolder[size.getBlockX()][size.getBlockY()][size.getBlockZ()]; } /** * Create a new instance. - *

+ * *

The origin will be placed at the region's lowest minimum point.

* * @param region the bounding region @@ -94,9 +85,6 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable this.size = getDimensions(); this.IMP = Settings.IMP.CLIPBOARD.USE_DISK ? new DiskOptimizedClipboard(size.getBlockX(), size.getBlockY(), size.getBlockZ(), clipboardId) : new MemoryOptimizedClipboard(size.getBlockX(), size.getBlockY(), size.getBlockZ()); this.origin = region.getMinimumPoint(); - this.mx = origin.getBlockX(); - this.my = origin.getBlockY(); - this.mz = origin.getBlockZ(); this.blocks = new BlockStateHolder[size.getBlockX()][size.getBlockY()][size.getBlockZ()]; } @@ -105,9 +93,6 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable this.region = region.clone(); this.size = getDimensions(); this.origin = region.getMinimumPoint(); - this.mx = origin.getBlockX(); - this.my = origin.getBlockY(); - this.mz = origin.getBlockZ(); this.IMP = clipboard; this.blocks = new BlockStateHolder[size.getBlockX()][size.getBlockY()][size.getBlockZ()]; } @@ -119,9 +104,6 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable this.size = getDimensions(); this.IMP = fc; this.origin = region.getMinimumPoint(); - this.mx = origin.getBlockX(); - this.my = origin.getBlockY(); - this.mz = origin.getBlockZ(); this.blocks = new BlockStateHolder[size.getBlockX()][size.getBlockY()][size.getBlockZ()]; } @@ -196,12 +178,11 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable @Override public BlockState getBlock(BlockVector3 position) { if (region.contains(position)) { - int x = position.getBlockX() - mx; - int y = position.getBlockY() - my; - int z = position.getBlockZ() - mz; - return IMP.getBlock(x, y, z).toImmutableState(); + BlockVector3 v = position.subtract(region.getMinimumPoint()); + return IMP.getBlock(v.getX(),v.getY(),v.getZ()).toImmutableState(); } - return EditSession.nullBlock; + + return BlockTypes.AIR.getDefaultState(); } public BlockState getBlockAbs(int x, int y, int z) { @@ -215,13 +196,12 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable @Override public BaseBlock getFullBlock(BlockVector3 position) { - if(region.contains(position)) { - int x = position.getBlockX() - mx; - int y = position.getBlockY() - my; - int z = position.getBlockZ() - mz; - return IMP.getBlock(x, y, z); + if (region.contains(position)) { + BlockVector3 v = position.subtract(region.getMinimumPoint()); + return IMP.getBlock(v.getX(),v.getY(),v.getZ()); } - return EditSession.nullBlock.toBaseBlock(); + + return BlockTypes.AIR.getDefaultState().toBaseBlock(); } @Override @@ -235,33 +215,28 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable return false; } - public boolean setTile(int x, int y, int z, CompoundTag tag) { - x -= mx; - y -= my; - z -= mz; - return IMP.setTile(x, y, z, tag); + public boolean setTile(BlockVector3 position, CompoundTag tag) { + BlockVector3 v = position.subtract(region.getMinimumPoint()); + return IMP.setTile(v.getX(), v.getY(), v.getZ(), tag); } @Override public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { - x -= mx; - y -= my; - z -= mz; - return IMP.setBlock(x, y, z, block); + BlockVector3 position = BlockVector3.at(x, y, z); + BlockVector3 v = position.subtract(region.getMinimumPoint()); + return IMP.setBlock(v.getX(), v.getY(), v.getZ(), block); } @Override public BiomeType getBiome(BlockVector2 position) { - int x = position.getBlockX() - mx; - int z = position.getBlockZ() - mz; - return IMP.getBiome(x, z); + BlockVector2 v = position.subtract(region.getMinimumPoint().toBlockVector2()); + return IMP.getBiome(v.getX(), v.getZ()); } @Override public boolean setBiome(BlockVector2 position, BiomeType biome) { - int x = position.getBlockX() - mx; - int z = position.getBlockZ() - mz; - IMP.setBiome(x, z, biome); + BlockVector2 v = position.subtract(region.getMinimumPoint().toBlockVector2()); + IMP.setBiome(v.getX(), v.getZ(), biome); return true; } @@ -297,4 +272,4 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable public int getBrightness(int x, int y, int z) { return getBlock(BlockVector3.at(x, y, z)).getBlockType().getMaterial().getLightValue(); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/Clipboard.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/Clipboard.java index e0022d480..aeaf07e85 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/Clipboard.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/Clipboard.java @@ -20,6 +20,7 @@ package com.sk89q.worldedit.extent.clipboard; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; @@ -58,4 +59,15 @@ public interface Clipboard extends Extent { */ void setOrigin(BlockVector3 origin); + /** + * Returns true if the clipboard has biome data. This can be checked since {@link Extent#getBiome(BlockVector2)} + * strongly suggests returning {@link com.sk89q.worldedit.world.biome.BiomeTypes.OCEAN} instead of {@code null} + * if biomes aren't present. However, it might not be desired to set areas to ocean if the clipboard is defaulting + * to ocean, instead of having biomes explicitly set. + * + * @return true if the clipboard has biome data set + */ + default boolean hasBiomes() { + return false; + } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/inventory/BlockBagExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/inventory/BlockBagExtent.java index 04ec91136..fb7d038e4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/inventory/BlockBagExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/inventory/BlockBagExtent.java @@ -1,12 +1,28 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + package com.sk89q.worldedit.extent.inventory; import com.boydti.fawe.object.exception.FaweException; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.extent.AbstractDelegateExtent; -import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -33,7 +49,7 @@ public class BlockBagExtent extends AbstractDelegateExtent { /** * Create a new instance. * - * @param extent the extent + * @param extent the extent * @param blockBag the block bag */ public BlockBagExtent(Extent extent, @Nonnull BlockBag blockBag) { @@ -52,9 +68,7 @@ public class BlockBagExtent extends AbstractDelegateExtent { * * @return a block bag, which may be null if none is used */ - public - @Nullable - BlockBag getBlockBag() { + public @Nullable BlockBag getBlockBag() { return blockBag; } @@ -92,34 +106,32 @@ public class BlockBagExtent extends AbstractDelegateExtent { @Override public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { - if(blockBag != null) { - BlockStateHolder lazyBlock = getExtent().getLazyBlock(x, y, z); - BlockType fromType = lazyBlock.getBlockType(); - if(!block.getBlockType().equals(fromType)) { - BlockType type = block.getBlockType(); - if (!type.getMaterial().isAir()) { - try { - blockBag.fetchPlacedBlock(block.toImmutableState()); - } catch (UnplaceableBlockException e) { - throw new FaweException.FaweBlockBagException(); - } catch (BlockBagException e) { - missingBlocks[type.getInternalId()]++; - throw new FaweException.FaweBlockBagException(); - } - } - if (mine) { - - if (!fromType.getMaterial().isAir()) { - try { - blockBag.storeDroppedBlock(fromType.getDefaultState()); - } catch (BlockBagException ignored) { - } - } - } - } + if (blockBag != null) { + BlockState existing = getExtent().getBlock(BlockVector3.at(x,y,z)); + + if (!block.getBlockType().equals(existing.getBlockType())) { + if (!block.getBlockType().getMaterial().isAir()) { + try { + blockBag.fetchPlacedBlock(block.toImmutableState()); + } catch (UnplaceableBlockException e) { + throw new FaweException.FaweBlockBagException(); + } catch (BlockBagException e) { + missingBlocks[block.getBlockType().getInternalId()]++; + throw new FaweException.FaweBlockBagException(); + } + } + if (mine) { + + if (!existing.getBlockType().getMaterial().isAir()) { + try { + blockBag.storeDroppedBlock(existing); + } catch (BlockBagException ignored) { + } + } + } + } } - return getExtent().setBlock(x, y, z, block); + + return super.setBlock(x, y, z, block); } - - -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/transform/BlockTransformExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/transform/BlockTransformExtent.java index 1c1a9cdb4..0958c1341 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/transform/BlockTransformExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/transform/BlockTransformExtent.java @@ -1,3 +1,22 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + package com.sk89q.worldedit.extent.transform; import com.boydti.fawe.object.extent.ResettableExtent; @@ -32,6 +51,7 @@ import java.util.Collection; import java.util.List; import java.util.Map; +import static com.google.common.base.Preconditions.checkNotNull; import static com.sk89q.worldedit.util.Direction.*; public class BlockTransformExtent extends ResettableExtent { @@ -46,8 +66,14 @@ public class BlockTransformExtent extends ResettableExtent { this(parent, new AffineTransform()); } - public BlockTransformExtent(Extent parent, Transform transform) { - super(parent); + /** + * Create a new instance. + * + * @param extent the extent + */ + public BlockTransformExtent(Extent extent, Transform transform) { + super(extent); + checkNotNull(transform); this.transform = transform; this.transformInverse = this.transform.inverse(); cache(); @@ -134,7 +160,7 @@ public class BlockTransformExtent extends ResettableExtent { continue; default: System.out.println("Unknown direction " + value); - result.add(0l); + result.add(0L); } } return adapt(result.toArray(new Long[0])); @@ -174,7 +200,7 @@ public class BlockTransformExtent extends ResettableExtent { break; default: System.out.println("Unknown direction " + value); - directions.add(0l); + directions.add(0L); } } return adapt(directions.toArray(new Long[0])); @@ -268,7 +294,7 @@ public class BlockTransformExtent extends ResettableExtent { } } - private static final BaseBlock transformBaseBlockNBT(BlockState transformed, CompoundTag tag, Transform transform) { + private static BaseBlock transformBaseBlockNBT(BlockState transformed, CompoundTag tag, Transform transform) { if (tag != null) { if (tag.containsKey("Rot")) { int rot = tag.asInt("Rot"); @@ -321,7 +347,7 @@ public class BlockTransformExtent extends ResettableExtent { newMaskedId = tmp.getInternalId(); } - for (AbstractProperty property : (Collection) (Collection) type.getProperties()) { + for (AbstractProperty property : (List>) type.getProperties()) { if (isDirectional(property)) { long[] directions = getDirections(property); if (directions != null) { @@ -358,7 +384,6 @@ public class BlockTransformExtent extends ResettableExtent { BLOCK_ROTATION_BITMASK = new int[BlockTypes.size()]; BLOCK_TRANSFORM = new int[BlockTypes.size()][]; BLOCK_TRANSFORM_INVERSE = new int[BlockTypes.size()][]; - outer: for (int i = 0; i < BLOCK_TRANSFORM.length; i++) { BLOCK_TRANSFORM[i] = ALL; BLOCK_TRANSFORM_INVERSE[i] = ALL; @@ -392,7 +417,7 @@ public class BlockTransformExtent extends ResettableExtent { cache(); } - private final BlockState transform(BlockState state, int[][] transformArray, Transform transform) { + private BlockState transform(BlockState state, int[][] transformArray, Transform transform) { int typeId = state.getInternalBlockTypeId(); int[] arr = transformArray[typeId]; if (arr == ALL) { @@ -478,4 +503,4 @@ public class BlockTransformExtent extends ResettableExtent { } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/AbstractPattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/AbstractPattern.java index b22a7cf6d..b53930597 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/AbstractPattern.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/AbstractPattern.java @@ -1,10 +1,26 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + package com.sk89q.worldedit.function.pattern; -import java.io.Serializable; - -public abstract class AbstractPattern implements Pattern, Serializable { - public AbstractPattern() { - } - - +/** + * An abstract implementation for {@link Pattern}s. + */ +public abstract class AbstractPattern implements Pattern { } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/BlockPattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/BlockPattern.java index 8f0560364..fa49f5108 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/BlockPattern.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/BlockPattern.java @@ -16,6 +16,7 @@ * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ + package com.sk89q.worldedit.function.pattern; import static com.google.common.base.Preconditions.checkNotNull; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/ClipboardPattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/ClipboardPattern.java index e686f454d..9f226a1ab 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/ClipboardPattern.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/ClipboardPattern.java @@ -1,3 +1,22 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + package com.sk89q.worldedit.function.pattern; import com.sk89q.worldedit.extent.clipboard.Clipboard; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/Pattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/Pattern.java index 290240c2c..2c000c668 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/Pattern.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/Pattern.java @@ -26,23 +26,12 @@ import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockState; /** * Returns a {@link BlockStateHolder} for a given position. */ @Link(clazz = UtilityCommands.class, value = "patterns") -public interface Pattern{ - -// @Override -// default BaseBlock next(BlockVector3 position) { -// return new BaseBlock(apply(position)); -// } -// -// @Override -// default BaseBlock next(int x, int y, int z) { -// return new BaseBlock(apply(BlockVector3.at(x, y, z))); -// } +public interface Pattern { /** * Return a {@link BlockStateHolder} for the given position. diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RandomPattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RandomPattern.java index 083dbee10..852d8b816 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RandomPattern.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RandomPattern.java @@ -1,3 +1,22 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + package com.sk89q.worldedit.function.pattern; import com.boydti.fawe.object.collection.RandomCollection; @@ -39,12 +58,12 @@ public class RandomPattern extends AbstractPattern { /** * Add a pattern to the weight list of patterns. - *

+ * *

The probability for the pattern added is chance / max where max is * the sum of the probabilities of all added patterns.

* * @param pattern the pattern - * @param chance the chance, which can be any positive number + * @param chance the chance, which can be any positive number */ public void add(Pattern pattern, double chance) { checkNotNull(pattern); @@ -75,4 +94,4 @@ public class RandomPattern extends AbstractPattern { -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RepeatingExtentPattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RepeatingExtentPattern.java index 61d52823d..0fbf830cc 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RepeatingExtentPattern.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RepeatingExtentPattern.java @@ -95,4 +95,5 @@ public class RepeatingExtentPattern extends AbstractExtentPattern { int z = (Math.abs((p.getZ() + offset.getZ())) % size.getBlockZ()) + origin.getZ(); return getExtent().getFullBlock(mutable.setComponents(x, y, z)); } + } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/BreadthFirstSearch.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/BreadthFirstSearch.java index 859110b77..d40417762 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/BreadthFirstSearch.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/BreadthFirstSearch.java @@ -1,3 +1,22 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + package com.sk89q.worldedit.function.visitor; import com.boydti.fawe.config.BBC; @@ -7,25 +26,20 @@ import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.HasFaweQueue; import com.boydti.fawe.object.IntegerTrio; import com.boydti.fawe.object.collection.BlockVectorSet; -import static com.google.common.base.Preconditions.checkNotNull; - import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.RunContext; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.MutableBlockVector3; -import com.sk89q.worldedit.math.Vector3; +import com.sk89q.worldedit.util.Direction; -import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; -import java.util.Queue; -import java.util.Set; /** * Performs a breadth-first search starting from points added with @@ -63,26 +77,26 @@ public abstract class BreadthFirstSearch implements Operation { } } } - Collections.sort(list, new Comparator() { - @Override - public int compare(BlockVector3 o1, BlockVector3 o2) { - return (int) Math.signum(o1.lengthSq() - o2.lengthSq()); - } - }); + list.sort((o1, o2) -> (int) Math.signum(o1.lengthSq() - o2.lengthSq())); DIAGONAL_DIRECTIONS = list.toArray(new BlockVector3[list.size()]); } private final RegionFunction function; - private List directions = new ArrayList<>(); private BlockVectorSet visited; private final MappedFaweQueue mFaweQueue; private BlockVectorSet queue; private int currentDepth = 0; private final int maxDepth; + private List directions = new ArrayList<>(); private int affected = 0; private int maxBranch = Integer.MAX_VALUE; - public BreadthFirstSearch(final RegionFunction function) { + /** + * Create a new instance. + * + * @param function the function to apply to visited blocks + */ + public BreadthFirstSearch(RegionFunction function) { this(function, Integer.MAX_VALUE); } @@ -133,29 +147,44 @@ public abstract class BreadthFirstSearch implements Operation { * Add the directions along the axes as directions to visit. */ protected void addAxes() { - directions.add(BlockVector3.at(0, -1, 0)); - directions.add(BlockVector3.at(0, 1, 0)); - directions.add(BlockVector3.at(-1, 0, 0)); - directions.add(BlockVector3.at(1, 0, 0)); - directions.add(BlockVector3.at(0, 0, -1)); - directions.add(BlockVector3.at(0, 0, 1)); + directions.add(BlockVector3.UNIT_MINUS_Y); + directions.add(BlockVector3.UNIT_Y); + directions.add(BlockVector3.UNIT_MINUS_X); + directions.add(BlockVector3.UNIT_X); + directions.add(BlockVector3.UNIT_MINUS_Z); + directions.add(BlockVector3.UNIT_Z); } /** * Add the diagonal directions as directions to visit. */ protected void addDiagonal() { - directions.add(BlockVector3.at(1, 0, 1)); - directions.add(BlockVector3.at(-1, 0, -1)); - directions.add(BlockVector3.at(1, 0, -1)); - directions.add(BlockVector3.at(-1, 0, 1)); + directions.add(Direction.NORTHEAST.toBlockVector()); + directions.add(Direction.SOUTHEAST.toBlockVector()); + directions.add(Direction.SOUTHWEST.toBlockVector()); + directions.add(Direction.NORTHWEST.toBlockVector()); } - public void visit(final BlockVector3 pos) { - if (!isVisited(pos)) { - isVisitable(pos, pos); // Ignore this, just to initialize mask on this point - queue.add(pos); - visited.add(pos); + /** + * Add the given location to the list of locations to visit, provided + * that it has not been visited. The position passed to this method + * will still be visited even if it fails + * {@link #isVisitable(BlockVector3, BlockVector3)}. + * + *

This method should be used before the search begins, because if + * the position does fail the test, and the search has already + * visited it (because it is connected to another root point), + * the search will mark the position as "visited" and a call to this + * method will do nothing.

+ * + * @param position the position + */ + + public void visit(BlockVector3 position) { + if (!isVisited(position)) { + isVisitable(position, position); // Ignore this, just to initialize mask on this point + queue.add(position); + visited.add(position); } } @@ -217,9 +246,6 @@ public abstract class BreadthFirstSearch implements Operation { @Override public Operation resume(RunContext run) throws WorldEditException { - MutableBlockVector3 mutable = new MutableBlockVector3(); -// MutableBlockVector3 mutable2 = new MutableBlockVector3(); - boolean shouldTrim = false; IntegerTrio[] dirs = getIntDirections(); BlockVectorSet tempQueue = new BlockVectorSet(); BlockVectorSet chunkLoadSet = new BlockVectorSet(); @@ -268,7 +294,6 @@ public abstract class BreadthFirstSearch implements Operation { if (currentDepth == maxDepth) { break; } - int size = queue.size(); BlockVectorSet tmp = queue; queue = tempQueue; tmp.clear(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DownwardVisitor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DownwardVisitor.java index a3a8dac66..d20eb733d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DownwardVisitor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DownwardVisitor.java @@ -30,26 +30,23 @@ import com.sk89q.worldedit.math.BlockVector3; import java.util.Collection; - -import static com.google.common.base.Preconditions.checkNotNull; - /** * Visits adjacent points on the same X-Z plane as long as the points * pass the given mask, and then executes the provided region * function on the entire column. - *

+ * *

This is used by {@code //fill}.

*/ public class DownwardVisitor extends RecursiveVisitor { - private final int baseY; + private int baseY; /** * Create a new visitor. * - * @param mask the mask + * @param mask the mask * @param function the function - * @param baseY the base Y + * @param baseY the base Y */ public DownwardVisitor(Mask mask, RegionFunction function, int baseY) { this(mask, function, baseY, Integer.MAX_VALUE, null); @@ -58,15 +55,16 @@ public class DownwardVisitor extends RecursiveVisitor { public DownwardVisitor(Mask mask, RegionFunction function, int baseY, int depth, HasFaweQueue hasFaweQueue) { super(mask, function, depth, hasFaweQueue); checkNotNull(mask); + this.baseY = baseY; Collection directions = getDirections(); directions.clear(); - directions.add(BlockVector3.at(1, 0, 0)); - directions.add(BlockVector3.at(-1, 0, 0)); - directions.add(BlockVector3.at(0, 0, 1)); - directions.add(BlockVector3.at(0, 0, -1)); - directions.add(BlockVector3.at(0, -1, 0)); + directions.add(BlockVector3.UNIT_X); + directions.add(BlockVector3.UNIT_MINUS_X); + directions.add(BlockVector3.UNIT_Z); + directions.add(BlockVector3.UNIT_MINUS_Z); + directions.add(BlockVector3.UNIT_MINUS_Y); } @Override @@ -74,6 +72,4 @@ public class DownwardVisitor extends RecursiveVisitor { int fromY = from.getBlockY(); return (fromY == baseY || to.subtract(from).getBlockY() < 0) && super.isVisitable(from, to); } - - } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector3.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector3.java index f465f4142..b1f991009 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector3.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector3.java @@ -35,6 +35,9 @@ public class BlockVector3 { public static final BlockVector3 UNIT_X = new BlockVector3(1, 0, 0); public static final BlockVector3 UNIT_Y = new BlockVector3(0, 1, 0); public static final BlockVector3 UNIT_Z = new BlockVector3(0, 0, 1); + public static final BlockVector3 UNIT_MINUS_X = new BlockVector3(-1, 0, 0); + public static final BlockVector3 UNIT_MINUS_Y = new BlockVector3(0, -1, 0); + public static final BlockVector3 UNIT_MINUS_Z = new BlockVector3(0, 0, -1); public static final BlockVector3 ONE = new BlockVector3(1, 1, 1); public static BlockVector3 at(double x, double y, double z) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/convolution/HeightMap.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/convolution/HeightMap.java index 18767b4ca..2c74d2f73 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/convolution/HeightMap.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/convolution/HeightMap.java @@ -1,29 +1,44 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + package com.sk89q.worldedit.math.convolution; import com.boydti.fawe.object.visitor.Fast2DIterator; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; - -import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Regions; import com.sk89q.worldedit.registry.state.PropertyGroup; +import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockTypes; import java.util.Iterator; - import static com.google.common.base.Preconditions.checkNotNull; -import javax.annotation.Nullable; - /** * Allows applications of Kernels onto the region's height map. - *

+ * *

Currently only used for smoothing (with a GaussianKernel)

. */ public class HeightMap { @@ -41,7 +56,7 @@ public class HeightMap { * Constructs the HeightMap * * @param session an edit session - * @param region the region + * @param region the region */ public HeightMap(EditSession session, Region region) { this(session, region, (Mask) null, false); @@ -68,12 +83,12 @@ public class HeightMap { int minZ = region.getMinimumPoint().getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); + // Store current heightmap data data = new int[width * height]; invalid = new boolean[data.length]; if (layers) { BlockVector3 min = region.getMinimumPoint(); - BlockVector3 max = region.getMaximumPoint(); int bx = min.getBlockX(); int bz = min.getBlockZ(); Iterable flat = Regions.asFlatRegion(region).asFlatRegion(); @@ -128,11 +143,12 @@ public class HeightMap { /** * Apply the filter 'iterations' amount times. * - * @param filter the filter + * @param filter the filter * @param iterations the number of iterations * @return number of blocks affected * @throws MaxChangedBlocksException */ + public int applyFilter(HeightMapFilter filter, int iterations) throws MaxChangedBlocksException { checkNotNull(filter); @@ -155,11 +171,11 @@ public class HeightMap { int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); - BlockStateHolder fillerAir = EditSession.nullBlock; + BlockStateHolder fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; - BlockStateHolder tmpBlock = EditSession.nullBlock; + BlockStateHolder tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int maxY4 = maxY << 4; @@ -233,12 +249,11 @@ public class HeightMap { int originZ = minY.getBlockZ(); int maxY = region.getMaximumPoint().getBlockY(); - BlockStateHolder fillerAir = EditSession.nullBlock; + BlockState fillerAir = BlockTypes.AIR.getDefaultState(); int blocksChanged = 0; - BlockStateHolder tmpBlock = EditSession.nullBlock; - + BlockState tmpBlock = BlockTypes.AIR.getDefaultState(); // Apply heightmap int index = 0; for (int z = 0; z < height; ++z) { @@ -248,20 +263,20 @@ public class HeightMap { if (this.invalid != null && this.invalid[index]) continue; int newHeight = Math.min(maxY, data[index]); + // Offset x,z to be 'real' coordinates int xr = x + originX; // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) - BlockStateHolder existing = session.getBlock(xr, curHeight, zr); - + BlockState existing = session.getBlock(BlockVector3.at(xr, curHeight, zr)); // Skip water/lava - if (existing.getBlockType().getMaterial().isMovementBlocker()) { + if (existing.getBlockType() != BlockTypes.WATER && existing.getBlockType() != BlockTypes.LAVA) { int y0 = newHeight - 1; for (int setY = y0, getY = curHeight - 1; setY >= curHeight; setY--, getY--) { - BlockStateHolder get = session.getBlock(xr, getY, zr); - if (get != EditSession.nullBlock) tmpBlock = get; + BlockState get = session.getBlock(xr, getY, zr); + if (get != BlockTypes.AIR.getDefaultState()) tmpBlock = get; session.setBlock(xr, setY, zr, tmpBlock); ++blocksChanged; } @@ -282,9 +297,10 @@ public class HeightMap { } } } + + // Drop trees to the floor -- TODO + return blocksChanged; } - - } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/DirectionalProperty.java b/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/DirectionalProperty.java index bada26598..7d1676a0e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/DirectionalProperty.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/DirectionalProperty.java @@ -23,6 +23,7 @@ import com.sk89q.worldedit.util.Direction; import java.util.Arrays; import java.util.List; +import java.util.Locale; import javax.annotation.Nullable; @@ -63,7 +64,7 @@ public class DirectionalProperty extends AbstractProperty { @Nullable @Override public Direction getValueFor(final String string) { - Direction direction = Direction.valueOf(string.toUpperCase()); + Direction direction = Direction.valueOf(string.toUpperCase(Locale.ROOT)); if (!getValues().contains(direction)) { throw new IllegalArgumentException("Invalid direction value: " + string + ". Must be in " + getValues().toString()); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/IntegerProperty.java b/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/IntegerProperty.java index 74a187436..b2ced727c 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/IntegerProperty.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/IntegerProperty.java @@ -67,9 +67,9 @@ public class IntegerProperty extends AbstractProperty { public Integer getValueFor(String string) { try { int val = Integer.parseInt(string); -// if (!getValues().contains(val)) { -// throw new IllegalArgumentException("Invalid int value: " + string + ". Must be in " + getValues().toString()); -// } + if (!getValues().contains(val)) { + throw new IllegalArgumentException("Invalid int value: " + string + ". Must be in " + getValues().toString()); + } return val; } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid int value: " + string + ". Not an int."); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/Direction.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/Direction.java index 624fbc5aa..fa1d4d1a1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/Direction.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/Direction.java @@ -64,9 +64,11 @@ public enum Direction { ; private final Vector3 direction; - private final BlockVector3 blockVector; - private final int flags, left, right; - + private final int flags; + private final int left; + private final int right; + private final BlockVector3 blockPoint; + private static HashMap map = new HashMap<>(); static { @@ -77,15 +79,15 @@ public enum Direction { } Direction(Vector3 vector, int flags, int left, int right) { + this.blockPoint = vector.toBlockPoint(); this.direction = vector.normalize(); - this.blockVector = BlockVector3.at(Math.signum(vector.getX()), Math.signum(vector.getY()), Math.signum(vector.getZ())); this.flags = flags; this.left = left; this.right = right; } public static Direction get(CharSequence sequence) { - return map.get(sequence); + return map.get((String)sequence); } public Direction getLeft() { @@ -96,30 +98,6 @@ public enum Direction { return right != -1 ? values()[right] : null; } - public double getX() { - return direction.getX(); - } - - public double getY() { - return direction.getY(); - } - - public double getZ() { - return direction.getZ(); - } - - public int getBlockX() { - return blockVector.getBlockX(); - } - - public int getBlockY() { - return blockVector.getBlockY(); - } - - public int getBlockZ() { - return blockVector.getBlockZ(); - } - /** * Return true if the direction is of a cardinal direction (north, west * east, and south). @@ -177,7 +155,7 @@ public enum Direction { * @return the vector */ public BlockVector3 toBlockVector() { - return direction.toBlockPoint(); + return blockPoint; } /** @@ -332,3 +310,4 @@ public enum Direction { } } + diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/TargetBlock.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/TargetBlock.java index 3de20a41e..820d813d3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/TargetBlock.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/TargetBlock.java @@ -20,10 +20,15 @@ package com.sk89q.worldedit.util; import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.function.mask.ExistingBlockMask; +import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.function.mask.SolidBlockMask; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.world.World; +import javax.annotation.Nullable; + /** * This class uses an inefficient method to figure out what block a player * is looking towards. @@ -33,7 +38,8 @@ import com.sk89q.worldedit.world.World; */ public class TargetBlock { - private World world; + private final World world; + private int maxDistance; private double checkDistance, curDistance; private BlockVector3 targetPos = BlockVector3.ZERO; @@ -41,6 +47,11 @@ public class TargetBlock { private BlockVector3 prevPos = BlockVector3.ZERO; private Vector3 offset = Vector3.ZERO; + // the mask which dictates when to stop a trace - defaults to stopping at non-air blocks + private Mask stopMask; + // the mask which dictates when to stop a solid block trace - default to BlockMaterial#isMovementBlocker + private Mask solidMask; + /** * Constructor requiring a player, uses default values * @@ -48,7 +59,10 @@ public class TargetBlock { */ public TargetBlock(Player player) { this.world = player.getWorld(); - this.setValues(player.getLocation(), player.getLocation().getYaw(), player.getLocation().getPitch(), 300, 1.65, 0.2); + this.setValues(player.getLocation().toVector(), player.getLocation().getYaw(), player.getLocation().getPitch(), + 300, 1.65, 0.2); + this.stopMask = new ExistingBlockMask(world); + this.solidMask = new SolidBlockMask(world); } /** @@ -60,7 +74,37 @@ public class TargetBlock { */ public TargetBlock(Player player, int maxDistance, double checkDistance) { this.world = player.getWorld(); - this.setValues(player.getLocation(), player.getLocation().getYaw(), player.getLocation().getPitch(), maxDistance, 1.65, checkDistance); + this.setValues(player.getLocation().toVector(), player.getLocation().getYaw(), player.getLocation().getPitch(), maxDistance, 1.65, checkDistance); + this.stopMask = new ExistingBlockMask(world); + this.solidMask = new SolidBlockMask(world); + } + + /** + * Set the mask used for determine where to stop traces. + * Setting to null will restore the default. + * + * @param stopMask the mask used to stop traces + */ + public void setStopMask(@Nullable Mask stopMask) { + if (stopMask == null) { + this.stopMask = new ExistingBlockMask(world); + } else { + this.stopMask = stopMask; + } + } + + /** + * Set the mask used for determine where to stop solid block traces. + * Setting to null will restore the default. + * + * @param solidMask the mask used to stop solid block traces + */ + public void setSolidMask(@Nullable Mask solidMask) { + if (solidMask == null) { + this.solidMask = new SolidBlockMask(world); + } else { + this.solidMask = solidMask; + } } /** @@ -78,7 +122,7 @@ public class TargetBlock { this.checkDistance = checkDistance; this.curDistance = 0; xRotation = (xRotation + 90) % 360; - yRotation = yRotation * -1; + yRotation *= -1; double h = (checkDistance * Math.cos(Math.toRadians(yRotation))); @@ -101,15 +145,15 @@ public class TargetBlock { boolean searchForLastBlock = true; Location lastBlock = null; while (getNextBlock() != null) { - if (world.getBlock(targetPos).getBlockType().getMaterial().isAir()) { + if (stopMask.test(targetPos)) { + break; + } else { if (searchForLastBlock) { lastBlock = getCurrentBlock(); if (lastBlock.getBlockY() <= 0 || lastBlock.getBlockY() >= world.getMaxY()) { searchForLastBlock = false; } } - } else { - break; } } Location currentBlock = getCurrentBlock(); @@ -123,7 +167,8 @@ public class TargetBlock { * @return Block */ public Location getTargetBlock() { - while (getNextBlock() != null && world.getBlock(targetPos).getBlockType().getMaterial().isAir()) ; + //noinspection StatementWithEmptyBody + while (getNextBlock() != null && !stopMask.test(targetPos)) ; return getCurrentBlock(); } @@ -134,7 +179,8 @@ public class TargetBlock { * @return Block */ public Location getSolidTargetBlock() { - while (getNextBlock() != null && !world.getBlock(targetPos).getBlockType().getMaterial().isMovementBlocker()) ; + //noinspection StatementWithEmptyBody + while (getNextBlock() != null && !solidMask.test(targetPos)) ; return getCurrentBlock(); } @@ -149,8 +195,8 @@ public class TargetBlock { curDistance += checkDistance; targetPosDouble = offset.add(targetPosDouble.getX(), - targetPosDouble.getY(), - targetPosDouble.getZ()); + targetPosDouble.getY(), + targetPosDouble.getZ()); targetPos = targetPosDouble.toBlockPoint(); } while (curDistance <= maxDistance && targetPos.getBlockX() == prevPos.getBlockX() @@ -188,12 +234,17 @@ public class TargetBlock { public Location getAnyTargetBlockFace() { getAnyTargetBlock(); - return getCurrentBlock().setDirection(getCurrentBlock().subtract(getPreviousBlock())); + Location current = getCurrentBlock(); + if (current != null) + return current.setDirection(current.toVector().subtract(getPreviousBlock().toVector())); + else + return new Location(world, targetPos.toVector3(), Float.NaN, Float.NaN); } public Location getTargetBlockFace() { - getAnyTargetBlock(); - return getCurrentBlock().setDirection(getCurrentBlock().subtract(getPreviousBlock())); + getTargetBlock(); + if (getCurrentBlock() == null) return null; + return getCurrentBlock().setDirection(getCurrentBlock().toVector().subtract(getPreviousBlock().toVector())); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/TreeGenerator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/TreeGenerator.java index 0faf766e8..ad9b798b1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/TreeGenerator.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/TreeGenerator.java @@ -19,6 +19,7 @@ package com.sk89q.worldedit.util; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; @@ -30,6 +31,7 @@ import com.sk89q.worldedit.world.block.BlockTypes; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; @@ -64,8 +66,8 @@ public class TreeGenerator { } }, JUNGLE("Jungle tree", "jungle"), - SMALL_JUNGLE("Small jungle tree", "shortjungle", "smalljungle"), - SHORT_JUNGLE("Short jungle tree") { + SMALL_JUNGLE("Small jungle tree", "smalljungle"), + SHORT_JUNGLE("Short jungle tree", "shortjungle") { @Override public boolean generate(EditSession editSession, BlockVector3 pos) throws MaxChangedBlocksException { return SMALL_JUNGLE.generate(editSession, pos); @@ -113,22 +115,22 @@ public class TreeGenerator { private static final Set primaryAliases = Sets.newHashSet(); private final String name; - private final String[] lookupKeys; + public final ImmutableList lookupKeys; static { for (TreeType type : EnumSet.allOf(TreeType.class)) { for (String key : type.lookupKeys) { lookup.put(key, type); } - if (type.lookupKeys.length > 0) { - primaryAliases.add(type.lookupKeys[0]); + if (type.lookupKeys.size() > 0) { + primaryAliases.add(type.lookupKeys.get(0)); } } } TreeType(String name, String... lookupKeys) { this.name = name; - this.lookupKeys = lookupKeys; + this.lookupKeys = ImmutableList.copyOf(lookupKeys); } public static Set getAliases() { @@ -160,7 +162,7 @@ public class TreeGenerator { */ @Nullable public static TreeType lookup(String name) { - return lookup.get(name.toLowerCase()); + return lookup.get(name.toLowerCase(Locale.ROOT)); } } @@ -179,8 +181,8 @@ public class TreeGenerator { int trunkHeight = (int) Math.floor(Math.random() * 2) + 3; int height = (int) Math.floor(Math.random() * 5) + 8; - BlockStateHolder logBlock = BlockTypes.OAK_LOG.getDefaultState(); - BlockStateHolder leavesBlock = BlockTypes.OAK_LEAVES.getDefaultState(); + BlockState logBlock = BlockTypes.OAK_LOG.getDefaultState(); + BlockState leavesBlock = BlockTypes.OAK_LEAVES.getDefaultState(); // Create trunk for (int i = 0; i < trunkHeight; ++i) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/function/LevenshteinDistance.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/function/LevenshteinDistance.java index 1020d92cd..12f7492ec 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/function/LevenshteinDistance.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/function/LevenshteinDistance.java @@ -23,6 +23,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Function; +import java.util.Locale; import java.util.regex.Pattern; import javax.annotation.Nullable; @@ -60,7 +61,7 @@ public class LevenshteinDistance implements Function { checkNotNull(baseString); this.caseSensitive = caseSensitive; this.replacePattern = replacePattern; - baseString = caseSensitive ? baseString : baseString.toLowerCase(); + baseString = caseSensitive ? baseString : baseString.toLowerCase(Locale.ROOT); baseString = replacePattern != null ? replacePattern.matcher(baseString).replaceAll("") : baseString; this.baseString = baseString; } @@ -79,7 +80,7 @@ public class LevenshteinDistance implements Function { if (caseSensitive) { return distance(baseString, input); } else { - return distance(baseString, input.toLowerCase()); + return distance(baseString, input.toLowerCase(Locale.ROOT)); } } @@ -189,5 +190,5 @@ public class LevenshteinDistance implements Function { // actually has the most recent cost counts return p[n]; } - + } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/logging/DynamicStreamHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/logging/DynamicStreamHandler.java index 500b77aef..0c9e89c8c 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/logging/DynamicStreamHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/logging/DynamicStreamHandler.java @@ -19,9 +19,15 @@ package com.sk89q.worldedit.util.logging; -import javax.annotation.Nullable; import java.io.UnsupportedEncodingException; -import java.util.logging.*; +import java.util.logging.Filter; +import java.util.logging.Formatter; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.SimpleFormatter; +import java.util.logging.StreamHandler; + +import javax.annotation.Nullable; /** * A {@link StreamHandler} delegate that allows for the swap and disable of diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/EngineHubPaste.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/EngineHubPaste.java index da6b701fd..915e6bb97 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/EngineHubPaste.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/EngineHubPaste.java @@ -39,7 +39,7 @@ public class EngineHubPaste implements Paster { return Pasters.getExecutor().submit(new PasteTask(content)); } - private final class PasteTask implements Callable { + private static final class PasteTask implements Callable { private final String content; private PasteTask(String content) { @@ -50,7 +50,7 @@ public class EngineHubPaste implements Paster { public URL call() throws IOException, InterruptedException { HttpRequest.Form form = HttpRequest.Form.create(); form.add("content", content); - form.add("from", "worldguard"); + form.add("from", "enginehub"); URL url = HttpRequest.url("http://paste.enginehub.org/paste"); String result = HttpRequest.post(url) diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/Report.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/Report.java index 5c08e51d1..877bf2b83 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/Report.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/Report.java @@ -21,7 +21,6 @@ package com.sk89q.worldedit.util.report; public interface Report { - String getTitle(); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockState.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockState.java index 81e73df94..7db9875be 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockState.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockState.java @@ -38,10 +38,7 @@ import com.sk89q.worldedit.registry.state.PropertyKey; import com.sk89q.worldedit.world.registry.BlockMaterial; import javax.annotation.Nullable; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -124,7 +121,7 @@ public class BlockState implements BlockStateHolder, FawePattern { String input = key.toString(); throw new SuggestInputParseException("Does not match a valid block type: " + input, input, () -> Stream.of(BlockTypes.values) .filter(b -> StringMan.blockStateMatches(input, b.getId())) - .map(e1 -> e1.getId()) + .map(BlockType::getId) .sorted(StringMan.blockStateComparator(input)) .collect(Collectors.toList()) ); @@ -181,12 +178,12 @@ public class BlockState implements BlockStateHolder, FawePattern { BlockType finalType = type; throw new SuggestInputParseException("Invalid property " + charSequence + ":" + input + " for type " + type, input, () -> finalType.getProperties().stream() - .map(p -> p.getName()) + .map(Property::getName) .filter(p -> StringMan.blockStateMatches(input, p)) .sorted(StringMan.blockStateComparator(input)) .collect(Collectors.toList())); } else { - throw new SuggestInputParseException("No operator for " + state, "", () -> Arrays.asList("=")); + throw new SuggestInputParseException("No operator for " + state, "", () -> Collections.singletonList("=")); } } property = null; @@ -211,6 +208,11 @@ public class BlockState implements BlockStateHolder, FawePattern { return getBlockType().withPropertyId(propertyId); } + + @Override + public BlockType getBlockType() { + return this.blockType; + } @Override public boolean apply(Extent extent, BlockVector3 get, BlockVector3 set) throws WorldEditException { return extent.setBlock(set, this); @@ -259,6 +261,14 @@ public class BlockState implements BlockStateHolder, FawePattern { } } + @Override + public final Map, Object> getStates() { + BlockType type = this.getBlockType(); + // Lazily initialize the map + Map map = Maps.asMap(type.getPropertiesSet(), (Function) this::getState); + return (Map, Object>) map; + } + @Override public final V getState(final Property property) { try { @@ -269,19 +279,9 @@ public class BlockState implements BlockStateHolder, FawePattern { } } - @Deprecated @Override - public final V getState(final PropertyKey key) { - return getState(getBlockType().getProperty(key)); - } - - @Override - @Deprecated - public final Map, Object> getStates() { - BlockType type = this.getBlockType(); - // Lazily initialize the map - Map map = Maps.asMap(type.getPropertiesSet(), (Function) input -> getState(input)); - return (Map, Object>) map; + public BlockState toImmutableState() { + return this; } @Override @@ -289,6 +289,12 @@ public class BlockState implements BlockStateHolder, FawePattern { return this.emptyBaseBlock; } + @Deprecated + @Override + public final V getState(final PropertyKey key) { + return getState(getBlockType().getProperty(key)); + } + @Override public BaseBlock toBaseBlock(CompoundTag compoundTag) { if (compoundTag == null) { @@ -296,11 +302,6 @@ public class BlockState implements BlockStateHolder, FawePattern { } return new BaseBlock(this, compoundTag); } - - @Override - public BlockType getBlockType() { - return this.blockType; - } @Override public boolean equalsFuzzy(BlockStateHolder o) { @@ -310,11 +311,6 @@ public class BlockState implements BlockStateHolder, FawePattern { return o.equalsFuzzy(this); } - @Override - public BlockState toImmutableState() { - return this; - } - @Override public int getInternalId() { return internalId; @@ -326,9 +322,7 @@ public class BlockState implements BlockStateHolder, FawePattern { if (blockType == BlockTypes.__RESERVED__) { return this.material = blockType.getMaterial(); } - if (this.material == null) { - this.material = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBlockRegistry().getMaterial(this); - } + this.material = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBlockRegistry().getMaterial(this); } return material; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypes.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypes.java index a157b2cbe..aeecbcd09 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypes.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypes.java @@ -19,41 +19,31 @@ package com.sk89q.worldedit.world.block; -import static com.google.common.base.Preconditions.checkArgument; - -import com.boydti.fawe.Fawe; import com.boydti.fawe.command.SuggestInputParseException; import com.boydti.fawe.util.MathMan; import com.boydti.fawe.util.ReflectionUtils; import com.boydti.fawe.util.StringMan; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.platform.Capability; -import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.function.mask.Mask; -import com.sk89q.worldedit.function.mask.SingleBlockTypeMask; -import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.registry.state.AbstractProperty; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.registry.state.PropertyKey; -import com.sk89q.worldedit.util.Direction; -import com.sk89q.worldedit.world.item.ItemType; -import com.sk89q.worldedit.world.item.ItemTypes; import com.sk89q.worldedit.world.registry.BlockMaterial; -import com.sk89q.worldedit.world.registry.BundledBlockData; import com.sk89q.worldedit.world.registry.LegacyMapper; -import it.unimi.dsi.fastutil.ints.IntCollections; import javax.annotation.Nullable; import java.lang.reflect.Field; -import java.util.*; -import java.util.function.Function; -import java.util.function.IntPredicate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; -import java.util.stream.IntStream; import java.util.stream.Stream; /**