diff --git a/README.md b/README.md index 72bee092b..2ef4aa97f 100644 --- a/README.md +++ b/README.md @@ -1,48 +1,50 @@ -

- -

- ---- - -FAWE is a fork of WorldEdit that has huge speed and memory improvements and considerably more features - -## Links - -* [Spigot Page](https://www.spigotmc.org/threads/fast-async-worldedit.100104/) -* [Discord](https://discord.gg/KxkjDVg) -* [Wiki](https://wiki.intellectualsites.com/FastAsyncWorldEdit/index) -* [Report Issue](https://github.com/IntellectualSites/FastAsyncWorldEdit/issues) -* [Crowdin](https://intellectualsites.crowdin.com/fastasyncworldedit) -* [JavaDocs](https://ci.athion.net/job/FastAsyncWorldEdit-1.16/javadoc/) - -## Downloads -### 1.15+ -* [Download](https://intellectualsites.github.io/download/fawe.html) -* [Jenkins](https://ci.athion.net/job/FastAsyncWorldEdit-1.16/) - - -## Building -FAWE uses gradle to build -You can safely ignore `gradlew setupDecompWorkspace` if you are not planning to work on the forge side of FAWE. - -``` -$ gradlew setupDecompWorkspace -$ gradlew build -``` - -The jar is located in `worldedit-bukkit/build/libs/FastAsyncWorldEdit-1.16-###.jar` - -## Contributing -Have an idea for an optimization, or a cool feature? - - We will accept most PR's - - Let us know what you've tested / what may need further testing - - If you need any help, create a ticket or discuss on [Discord](https://discord.gg/KxkjDVg) - -## YourKit - - - -
-Thank you to YourKit for supporting our product by providing us with their innovative and intelligent tools -for monitoring and profiling Java and .NET applications. -YourKit is the creator of YourKit Java Profiler, YourKit .NET Profiler, and YourKit YouMonitor +

+ +

+ +--- + +FAWE is a fork of WorldEdit that has huge speed and memory improvements and considerably more features + +## Links + +* [Spigot Page](https://www.spigotmc.org/threads/fast-async-worldedit.100104/) +* [Discord](https://discord.gg/KxkjDVg) +* [Wiki](https://wiki.intellectualsites.com/FastAsyncWorldEdit/index) +* [Report Issue](https://github.com/IntellectualSites/FastAsyncWorldEdit/issues) +* [Crowdin](https://intellectualsites.crowdin.com/fastasyncworldedit) +* [JavaDocs](https://ci.athion.net/job/FastAsyncWorldEdit-1.16/javadoc/) + +## Downloads +### 1.15+ +* [Download](https://www.spigotmc.org/resources/fast-async-worldedit.13932/) +* [Jenkins](https://ci.athion.net/job/FastAsyncWorldEdit-1.16/) + +Looking builds for older versions? Download them [here](https://intellectualsites.github.io/download/). + + +## Building +FAWE uses gradle to build +You can safely ignore `gradlew setupDecompWorkspace` if you are not planning to work on the forge side of FAWE. + +``` +$ gradlew setupDecompWorkspace +$ gradlew build +``` + +The jar is located in `worldedit-bukkit/build/libs/FastAsyncWorldEdit-1.16-###.jar` + +## Contributing +Have an idea for an optimization, or a cool feature? + - We will accept most PR's + - Let us know what you've tested / what may need further testing + - If you need any help, create a ticket or discuss on [Discord](https://discord.gg/KxkjDVg) + +## YourKit + + + +
+Thank you to YourKit for supporting our product by providing us with their innovative and intelligent tools +for monitoring and profiling Java and .NET applications. +YourKit is the creator of YourKit Java Profiler, YourKit .NET Profiler, and YourKit YouMonitor diff --git a/buildSrc/src/main/kotlin/PlatformConfig.kt b/buildSrc/src/main/kotlin/PlatformConfig.kt index 47db67011..662e1c150 100644 --- a/buildSrc/src/main/kotlin/PlatformConfig.kt +++ b/buildSrc/src/main/kotlin/PlatformConfig.kt @@ -19,6 +19,7 @@ import org.gradle.kotlin.dsl.withType fun Project.applyPlatformAndCoreConfiguration() { applyCommonConfiguration() apply(plugin = "java") + apply(plugin = "eclipse") apply(plugin = "idea") apply(plugin = "maven") // apply(plugin = "checkstyle") diff --git a/config/checkstyle/checkstyle-suppression.xml b/config/checkstyle/checkstyle-suppression.xml index a48ff1f81..6e77e27e7 100644 --- a/config/checkstyle/checkstyle-suppression.xml +++ b/config/checkstyle/checkstyle-suppression.xml @@ -10,4 +10,13 @@ + + + + + + + + + diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index d080f62ec..d024993f8 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -96,6 +96,7 @@ Checks based on Google Checks, modified for EngineHub. value="Member name ''{0}'' must match pattern ''{1}''."/> + @@ -106,6 +107,7 @@ Checks based on Google Checks, modified for EngineHub. value="Class type name ''{0}'' must match pattern ''{1}''."/> + @@ -186,6 +188,7 @@ Checks based on Google Checks, modified for EngineHub. + diff --git a/contrib/craftscripts/draw.js b/contrib/craftscripts/draw.js index fb7e4f050..b117d226e 100644 --- a/contrib/craftscripts/draw.js +++ b/contrib/craftscripts/draw.js @@ -83,7 +83,7 @@ var clothColorsOpt = [ ]; var clothColorsOptHD = [ makeColor(168, 168, 168), // White - makeColor(143, 59, 0), // Orange + makeColor(143, 59, 0), // Orange makeColor(152, 0, 67), // Magenta makeColor(0, 153, 153), // Light blue makeColor(150, 150, 0), // Yellow @@ -115,16 +115,16 @@ function colorDistance(c1, c2) { function findClosestWoolColor(col, clothColors) { var closestId = 0; var closestDistance = colorDistance(col, clothColors[0]); - - for(var i = 1; i < clothColors.length; i++) { + + for (var i = 1; i < clothColors.length; i++) { var dist = colorDistance(col, clothColors[i]); - - if(dist < closestDistance) { + + if (dist < closestDistance) { closestId = i; closestDistance = dist; } } - + return closestId; } @@ -135,10 +135,10 @@ var f = context.getSafeOpenFile("drawings", argv[1], "png", ["png", "jpg", "jpeg var sess = context.remember(); var upright = argv[2] == "v"; var colors = clothColors; -if(argv[3] == "opt") { +if (argv[3] == "opt") { colors = clothColorsOpt; player.print("Using optimized palette"); -} else if(argv[3] == "optHD") { +} else if (argv[3] == "optHD") { colors = clothColorsOptHD; player.print("Using optimized HD palette"); } diff --git a/contrib/craftscripts/roof.js b/contrib/craftscripts/roof.js index b1201ea3a..82564e7dc 100644 --- a/contrib/craftscripts/roof.js +++ b/contrib/craftscripts/roof.js @@ -31,7 +31,7 @@ var blocktype = context.getBlock(argv[1]); var cycles = region.getLength(); -if (region.getWidth() > cycles){ +if (region.getWidth() > cycles) { cycles = region.getWidth(); } @@ -50,4 +50,4 @@ for (var c = 0; c < cycles; c++) { } } } -} \ No newline at end of file +} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java index fd110b2e3..9357e693f 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java @@ -9,7 +9,7 @@ import com.boydti.fawe.bukkit.adapter.BukkitQueueHandler; import com.boydti.fawe.bukkit.listener.BrushListener; import com.boydti.fawe.bukkit.listener.BukkitImageListener; import com.boydti.fawe.bukkit.listener.CFIPacketListener; -import com.boydti.fawe.bukkit.listener.ChunkListener_9; +import com.boydti.fawe.bukkit.listener.ChunkListener9; import com.boydti.fawe.bukkit.listener.RenderListener; import com.boydti.fawe.bukkit.regions.FreeBuildRegion; import com.boydti.fawe.bukkit.regions.GriefPreventionFeature; @@ -95,7 +95,7 @@ public class FaweBukkit implements IFawe, Listener { Bukkit.getPluginManager().registerEvents(FaweBukkit.this, FaweBukkit.this.plugin); // The tick limiter - new ChunkListener_9(); + new ChunkListener9(); }); } @@ -142,7 +142,7 @@ public class FaweBukkit implements IFawe, Listener { this.imageListener = new BukkitImageListener(plugin); } return viewer; - } catch (Throwable ignore) { + } catch (Throwable ignored) { } return null; } @@ -252,7 +252,8 @@ public class FaweBukkit implements IFawe, Listener { private volatile boolean keepUnloaded; - @EventHandler(priority = EventPriority.MONITOR) public void onWorldLoad(WorldLoadEvent event) { + @EventHandler(priority = EventPriority.MONITOR) + public void onWorldLoad(WorldLoadEvent event) { if (keepUnloaded) { org.bukkit.World world = event.getWorld(); world.setKeepSpawnInMemory(false); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/BukkitQueueHandler.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/BukkitQueueHandler.java index 8550f02b7..c4a539179 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/BukkitQueueHandler.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/BukkitQueueHandler.java @@ -1,13 +1,14 @@ package com.boydti.fawe.bukkit.adapter; -import static org.slf4j.LoggerFactory.getLogger; - import co.aikar.timings.Timings; import com.boydti.fawe.beta.implementation.queue.QueueHandler; import com.boydti.fawe.bukkit.listener.ChunkListener; -import java.lang.reflect.Method; import org.spigotmc.AsyncCatcher; +import java.lang.reflect.Method; + +import static org.slf4j.LoggerFactory.getLogger; + public class BukkitQueueHandler extends QueueHandler { private volatile boolean timingsEnabled; private static boolean alertTimingsChange = true; @@ -17,7 +18,8 @@ public class BukkitQueueHandler extends QueueHandler { try { methodCheck = Class.forName("co.aikar.timings.TimingsManager").getDeclaredMethod("recheckEnabled"); methodCheck.setAccessible(true); - } catch (Throwable ignore){} + } catch (Throwable ignored) { + } } @Override diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BlockMaterial_1_15_2.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BlockMaterial_1_15_2.java index 7078d9f4d..086b6e776 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BlockMaterial_1_15_2.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BlockMaterial_1_15_2.java @@ -2,7 +2,13 @@ package com.boydti.fawe.bukkit.adapter.mc1_15_2; import com.sk89q.util.ReflectionUtil; import com.sk89q.worldedit.world.registry.BlockMaterial; -import net.minecraft.server.v1_15_R1.*; +import net.minecraft.server.v1_15_R1.Block; +import net.minecraft.server.v1_15_R1.BlockAccessAir; +import net.minecraft.server.v1_15_R1.BlockPosition; +import net.minecraft.server.v1_15_R1.EnumPistonReaction; +import net.minecraft.server.v1_15_R1.IBlockData; +import net.minecraft.server.v1_15_R1.ITileEntity; +import net.minecraft.server.v1_15_R1.Material; import org.bukkit.craftbukkit.v1_15_R1.block.data.CraftBlockData; public class BlockMaterial_1_15_2 implements BlockMaterial { diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BukkitAdapter_1_15_2.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BukkitAdapter_1_15_2.java index f81bfdd9e..8098145a1 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BukkitAdapter_1_15_2.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BukkitAdapter_1_15_2.java @@ -52,22 +52,22 @@ public final class BukkitAdapter_1_15_2 extends NMSAdapter { /* NMS fields */ - public final static Field fieldBits; - public final static Field fieldPalette; - public final static Field fieldSize; + public static final Field fieldBits; + public static final Field fieldPalette; + public static final Field fieldSize; - public final static Field fieldFluidCount; - public final static Field fieldTickingBlockCount; - public final static Field fieldNonEmptyBlockCount; + public static final Field fieldFluidCount; + public static final Field fieldTickingBlockCount; + public static final Field fieldNonEmptyBlockCount; - private final static Field fieldDirtyCount; - private final static Field fieldDirtyBits; + private static final Field fieldDirtyCount; + private static final Field fieldDirtyBits; private static final Field fieldBiomeArray; private final static MethodHandle methodGetVisibleChunk; - public final static MethodHandle methodSetLightNibbleArray; + public static final MethodHandle methodSetLightNibbleArray; private static final int CHUNKSECTION_BASE; private static final int CHUNKSECTION_SHIFT; @@ -114,8 +114,9 @@ public final class BukkitAdapter_1_15_2 extends NMSAdapter { Unsafe unsafe = UnsafeUtils.getUNSAFE(); CHUNKSECTION_BASE = unsafe.arrayBaseOffset(ChunkSection[].class); int scale = unsafe.arrayIndexScale(ChunkSection[].class); - if ((scale & (scale - 1)) != 0) + if ((scale & (scale - 1)) != 0) { throw new Error("data type scale not a power of two"); + } CHUNKSECTION_SHIFT = 31 - Integer.numberOfLeadingZeros(scale); } catch (RuntimeException e) { throw e; @@ -152,17 +153,17 @@ public final class BukkitAdapter_1_15_2 extends NMSAdapter { } } - public static Chunk ensureLoaded(World nmsWorld, int X, int Z) { - Chunk nmsChunk = nmsWorld.getChunkIfLoaded(X, Z); + public static Chunk ensureLoaded(World nmsWorld, int chunkX, int chunkZ) { + Chunk nmsChunk = nmsWorld.getChunkIfLoaded(chunkX, chunkZ); if (nmsChunk != null) { return nmsChunk; } if (Fawe.isMainThread()) { - return nmsWorld.getChunkAt(X, Z); + return nmsWorld.getChunkAt(chunkX, chunkZ); } if (PaperLib.isPaper()) { CraftWorld craftWorld = nmsWorld.getWorld(); - CompletableFuture future = craftWorld.getChunkAtAsync(X, Z, true); + CompletableFuture future = craftWorld.getChunkAtAsync(chunkX, chunkZ, true); try { CraftChunk chunk = (CraftChunk) future.get(); return chunk.getHandle(); @@ -171,20 +172,20 @@ public final class BukkitAdapter_1_15_2 extends NMSAdapter { } } // TODO optimize - return TaskManager.IMP.sync(() -> nmsWorld.getChunkAt(X, Z)); + return TaskManager.IMP.sync(() -> nmsWorld.getChunkAt(chunkX, chunkZ)); } public static PlayerChunk getPlayerChunk(WorldServer nmsWorld, final int cx, final int cz) { PlayerChunkMap chunkMap = nmsWorld.getChunkProvider().playerChunkMap; try { - return (PlayerChunk)methodGetVisibleChunk.invoke(chunkMap, ChunkCoordIntPair.pair(cx, cz)); + return (PlayerChunk) methodGetVisibleChunk.invoke(chunkMap, ChunkCoordIntPair.pair(cx, cz)); } catch (Throwable thr) { throw new RuntimeException(thr); } } - public static void sendChunk(WorldServer nmsWorld, int X, int Z, int mask, boolean lighting) { - PlayerChunk playerChunk = getPlayerChunk(nmsWorld, X, Z); + public static void sendChunk(WorldServer nmsWorld, int chunkX, int chunkZ, int mask, boolean lighting) { + PlayerChunk playerChunk = getPlayerChunk(nmsWorld, chunkX, chunkZ); if (playerChunk == null) { return; } @@ -205,7 +206,7 @@ public final class BukkitAdapter_1_15_2 extends NMSAdapter { fieldDirtyCount.set(playerChunk, 64); if (lighting) { - ChunkCoordIntPair chunkCoordIntPair = new ChunkCoordIntPair(X, Z); + ChunkCoordIntPair chunkCoordIntPair = new ChunkCoordIntPair(chunkX, chunkZ); PacketPlayOutLightUpdate packet = new PacketPlayOutLightUpdate(chunkCoordIntPair, nmsWorld.getChunkProvider().getLightEngine()); playerChunk.players.a(chunkCoordIntPair, false).forEach(p -> { p.playerConnection.sendPacket(packet); @@ -259,7 +260,9 @@ public final class BukkitAdapter_1_15_2 extends NMSAdapter { final int blockBitArrayEnd = (bitsPerEntry * 4096) >> 6; if (num_palette == 1) { - for (int i = 0; i < blockBitArrayEnd; i++) blockStates[i] = 0; + for (int i = 0; i < blockBitArrayEnd; i++) { + blockStates[i] = 0; + } } else { final BitArray bitArray = new BitArray(bitsPerEntry, 4096, blockStates); bitArray.fromRaw(blocksCopy); @@ -273,7 +276,6 @@ public final class BukkitAdapter_1_15_2 extends NMSAdapter { final long[] bits = Arrays.copyOfRange(blockStates, 0, blockBitArrayEnd); final DataBits nmsBits = new DataBits(bitsPerEntry, 4096, bits); final DataPalette palette; -// palette = new DataPaletteHash<>(Block.REGISTRY_ID, bitsPerEntry, dataPaletteBlocks, GameProfileSerializer::d, GameProfileSerializer::a); palette = new DataPaletteLinear<>(Block.REGISTRY_ID, bitsPerEntry, dataPaletteBlocks, GameProfileSerializer::d); // set palette diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BukkitGetBlocks_1_15_2.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BukkitGetBlocks_1_15_2.java index 504697b57..21e19e33e 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BukkitGetBlocks_1_15_2.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/BukkitGetBlocks_1_15_2.java @@ -58,7 +58,6 @@ import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nullable; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collection; @@ -72,6 +71,7 @@ import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.function.Function; +import javax.annotation.Nullable; import static org.slf4j.LoggerFactory.getLogger; @@ -80,24 +80,29 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { private static final Logger log = LoggerFactory.getLogger(BukkitGetBlocks_1_15_2.class); private static final Function posNms2We = v -> BlockVector3.at(v.getX(), v.getY(), v.getZ()); - private final static Function nmsTile2We = tileEntity -> new LazyCompoundTag_1_15_2(Suppliers.memoize(() -> tileEntity.save(new NBTTagCompound()))); + private static final Function nmsTile2We = tileEntity -> new LazyCompoundTag_1_15_2(Suppliers.memoize(() -> tileEntity.save(new NBTTagCompound()))); public ChunkSection[] sections; public Chunk nmsChunk; public WorldServer world; - public int X, Z; + public int chunkX; + public int chunkZ; public NibbleArray[] blockLight = new NibbleArray[16]; public NibbleArray[] skyLight = new NibbleArray[16]; private boolean createCopy = false; private BukkitGetBlocks_1_15_2_Copy copy = null; - public BukkitGetBlocks_1_15_2(World world, int X, int Z) { - this(((CraftWorld) world).getHandle(), X, Z); + public BukkitGetBlocks_1_15_2(World world, int chunkX, int chunkZ) { + this(((CraftWorld) world).getHandle(), chunkX, chunkZ); } - public BukkitGetBlocks_1_15_2(WorldServer world, int X, int Z) { + public BukkitGetBlocks_1_15_2(WorldServer world, int chunkX, int chunkZ) { this.world = world; - this.X = X; - this.Z = Z; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + } + + public int getChunkX() { + return chunkX; } @Override @@ -115,12 +120,8 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { return copy; } - public int getX() { - return X; - } - - public int getZ() { - return Z; + public int getChunkZ() { + return chunkZ; } @Override @@ -130,7 +131,9 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { if (y == -1) { for (y = 0; y < FaweCache.IMP.WORLD_HEIGHT; y++) { base = index.getBiome(x >> 2, y >> 2, z >> 2); - if (base != null) break; + if (base != null) { + break; + } } } else { base = index.getBiome(x >> 2, y >> 2, z >> 2); @@ -140,7 +143,8 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { @Override public CompoundTag getTile(int x, int y, int z) { - TileEntity tileEntity = getChunk().getTileEntity(new BlockPosition((x & 15) + (X << 4), y, (z & 15) + (Z << 4))); + TileEntity tileEntity = getChunk().getTileEntity(new BlockPosition((x & 15) + ( + chunkX << 4), y, (z & 15) + (chunkZ << 4))); if (tileEntity == null) { return null; } @@ -164,11 +168,11 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { NibbleArray nibbleArray = world.getChunkProvider().getLightEngine().a(EnumSkyBlock.SKY).a(sectionPosition); // If the server hasn't generated the section's NibbleArray yet, it will be null if (nibbleArray == null) { - byte[] a = new byte[2048]; - // Safe enough to assume if it's not created, it's under the sky. Unlikely to be created before lighting is fixed anyway. - Arrays.fill(a, (byte) 15); - nibbleArray = new NibbleArray(a); - ((LightEngine) world.getChunkProvider().getLightEngine()).a(EnumSkyBlock.SKY, sectionPosition, nibbleArray); + byte[] a = new byte[2048]; + // Safe enough to assume if it's not created, it's under the sky. Unlikely to be created before lighting is fixed anyway. + Arrays.fill(a, (byte) 15); + nibbleArray = new NibbleArray(a); + ((LightEngine) world.getChunkProvider().getLightEngine()).a(EnumSkyBlock.SKY, sectionPosition, nibbleArray); } skyLight[layer] = nibbleArray; } @@ -227,7 +231,9 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { List[] slices = getChunk().getEntitySlices(); int size = 0; for (List slice : slices) { - if (slice != null) size += slice.size(); + if (slice != null) { + size += slice.size(); + } } if (slices.length == 0) { return Collections.emptySet(); @@ -304,16 +310,16 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { entity.die(); } - public Chunk ensureLoaded(net.minecraft.server.v1_15_R1.World nmsWorld, int X, int Z) { - return BukkitAdapter_1_15_2.ensureLoaded(nmsWorld, X, Z); + public Chunk ensureLoaded(net.minecraft.server.v1_15_R1.World nmsWorld, int chunkX, int chunkZ) { + return BukkitAdapter_1_15_2.ensureLoaded(nmsWorld, chunkX, chunkZ); } @Override public > T call(IChunkSet set, Runnable finalizer) { - copy = createCopy ? new BukkitGetBlocks_1_15_2_Copy(world, getX(), getZ()) : null; + copy = createCopy ? new BukkitGetBlocks_1_15_2_Copy(world, getChunkX(), getChunkZ()) : null; try { WorldServer nmsWorld = world; - Chunk nmsChunk = ensureLoaded(nmsWorld, X, Z); + Chunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ); boolean fastmode = set.isFastMode() && Settings.IMP.QUEUE.NO_TICK_FASTMODE; // Remove existing tiles @@ -348,7 +354,7 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { ChunkSection[] sections = nmsChunk.getSections(); for (int layer = 0; layer < 16; layer++) { - if (!set.hasSection(layer)){ + if (!set.hasSection(layer)) { continue; } if (createCopy) { @@ -368,7 +374,8 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { } else { existingSection = sections[layer]; if (existingSection == null) { - log.error("Skipping invalid null section. chunk:" + X + "," + Z + " layer: " + layer); + log.error("Skipping invalid null section. chunk:" + chunkX + "," + + chunkZ + " layer: " + layer); continue; } } @@ -395,7 +402,7 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { } newSection = BukkitAdapter_1_15_2.newChunkSection(layer, this::load, setArr, fastmode); if (!BukkitAdapter_1_15_2.setSectionAtomic(sections, existingSection, newSection, layer)) { - log.error("Failed to set chunk section:" + X + "," + Z + " layer: " + layer); + log.error("Failed to set chunk section:" + chunkX + "," + chunkZ + " layer: " + layer); continue; } else { updateGet(this, nmsChunk, sections, newSection, setArr, layer); @@ -458,12 +465,14 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { Runnable[] syncTasks = null; - int bx = X << 4; - int bz = Z << 4; + int bx = chunkX << 4; + int bz = chunkZ << 4; Set entityRemoves = set.getEntityRemoves(); if (entityRemoves != null && !entityRemoves.isEmpty()) { - if (syncTasks == null) syncTasks = new Runnable[3]; + if (syncTasks == null) { + syncTasks = new Runnable[3]; + } syncTasks[2] = () -> { final List[] entities = nmsChunk.getEntitySlices(); @@ -488,7 +497,9 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { Set entities = set.getEntities(); if (entities != null && !entities.isEmpty()) { - if (syncTasks == null) syncTasks = new Runnable[2]; + if (syncTasks == null) { + syncTasks = new Runnable[2]; + } syncTasks[1] = () -> { for (final CompoundTag nativeTag : entities) { @@ -516,7 +527,7 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { for (final String name : Constants.NO_COPY_ENTITY_NBT_FIELDS) { tag.remove(name); } - + entity.f(tag); entity.setLocation(x, y, z, yaw, pitch); nmsWorld.addEntity(entity, CreatureSpawnEvent.SpawnReason.CUSTOM); @@ -530,7 +541,9 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { // set tiles Map tiles = set.getTiles(); if (tiles != null && !tiles.isEmpty()) { - if (syncTasks == null) syncTasks = new Runnable[1]; + if (syncTasks == null) { + syncTasks = new Runnable[1]; + } syncTasks[0] = () -> { for (final Map.Entry entry : tiles.entrySet()) { @@ -572,8 +585,10 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { nmsChunk.mustNotSave = false; nmsChunk.markDirty(); // send to player - BukkitAdapter_1_15_2.sendChunk(nmsWorld, X, Z, finalMask, finalLightUpdate); - if (finalizer != null) finalizer.run(); + BukkitAdapter_1_15_2.sendChunk(nmsWorld, chunkX, chunkZ, finalMask, finalLightUpdate); + if (finalizer != null) { + finalizer.run(); + } }; } if (syncTasks != null) { @@ -590,7 +605,9 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { } } if (callback == null) { - if (finalizer != null) finalizer.run(); + if (finalizer != null) { + finalizer.run(); + } return null; } else { return queueHandler.async(callback, null); @@ -603,7 +620,9 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { return (T) (Future) queueHandler.sync(chain); } else { if (callback == null) { - if (finalizer != null) finalizer.run(); + if (finalizer != null) { + finalizer.run(); + } } else { callback.run(); } @@ -753,7 +772,7 @@ public class BukkitGetBlocks_1_15_2 extends CharGetBlocks { synchronized (this) { tmp = nmsChunk; if (tmp == null) { - nmsChunk = tmp = ensureLoaded(this.world, X, Z); + nmsChunk = tmp = ensureLoaded(this.world, chunkX, chunkZ); } } } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/FAWEWorldNativeAccess_1_15_2.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/FAWEWorldNativeAccess_1_15_2.java index 9ce24d789..bd3767b9a 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/FAWEWorldNativeAccess_1_15_2.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_15_2/FAWEWorldNativeAccess_1_15_2.java @@ -25,12 +25,13 @@ import org.bukkit.craftbukkit.v1_15_R1.CraftWorld; import org.bukkit.craftbukkit.v1_15_R1.block.data.CraftBlockData; import org.bukkit.event.block.BlockPhysicsEvent; -import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.Objects; +import javax.annotation.Nullable; public class FAWEWorldNativeAccess_1_15_2 implements WorldNativeAccess { - private static final int UPDATE = 1, NOTIFY = 2; + private static final int UPDATE = 1; + private static final int NOTIFY = 2; private final FAWE_Spigot_v1_15_R2 adapter; private final WeakReference world; @@ -170,4 +171,4 @@ public class FAWEWorldNativeAccess_1_15_2 implements WorldNativeAccess> boolean setBlock(BlockVector3 position, B block, SideEffectSet sideEffects) throws WorldEditException { return this.adapter.setBlock(this.getChunk(position.getBlockX() >> 4, position.getBlockZ() >> 4).bukkitChunk, position.getBlockX(), position.getBlockY(), position.getBlockZ(), block, sideEffectSet.shouldApply(SideEffect.LIGHTING)); } -} \ No newline at end of file +} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BlockMaterial_1_16_1.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BlockMaterial_1_16_1.java index 207cb6e60..4c64a66ff 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BlockMaterial_1_16_1.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BlockMaterial_1_16_1.java @@ -2,7 +2,14 @@ package com.boydti.fawe.bukkit.adapter.mc1_16_1; import com.sk89q.util.ReflectionUtil; import com.sk89q.worldedit.world.registry.BlockMaterial; -import net.minecraft.server.v1_16_R1.*; +import net.minecraft.server.v1_16_R1.Block; +import net.minecraft.server.v1_16_R1.BlockAccessAir; +import net.minecraft.server.v1_16_R1.BlockBase; +import net.minecraft.server.v1_16_R1.BlockPosition; +import net.minecraft.server.v1_16_R1.EnumPistonReaction; +import net.minecraft.server.v1_16_R1.IBlockData; +import net.minecraft.server.v1_16_R1.ITileEntity; +import net.minecraft.server.v1_16_R1.Material; import org.bukkit.craftbukkit.v1_16_R1.block.data.CraftBlockData; public class BlockMaterial_1_16_1 implements BlockMaterial { diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BukkitAdapter_1_16_1.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BukkitAdapter_1_16_1.java index 37e6eb9af..d148d8e81 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BukkitAdapter_1_16_1.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BukkitAdapter_1_16_1.java @@ -14,7 +14,23 @@ import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockTypesCache; import io.papermc.lib.PaperLib; import net.jpountz.util.UnsafeUtils; -import net.minecraft.server.v1_16_R1.*; +import net.minecraft.server.v1_16_R1.BiomeBase; +import net.minecraft.server.v1_16_R1.BiomeStorage; +import net.minecraft.server.v1_16_R1.Block; +import net.minecraft.server.v1_16_R1.Chunk; +import net.minecraft.server.v1_16_R1.ChunkCoordIntPair; +import net.minecraft.server.v1_16_R1.ChunkSection; +import net.minecraft.server.v1_16_R1.DataBits; +import net.minecraft.server.v1_16_R1.DataPalette; +import net.minecraft.server.v1_16_R1.DataPaletteBlock; +import net.minecraft.server.v1_16_R1.DataPaletteLinear; +import net.minecraft.server.v1_16_R1.GameProfileSerializer; +import net.minecraft.server.v1_16_R1.IBlockData; +import net.minecraft.server.v1_16_R1.PacketPlayOutLightUpdate; +import net.minecraft.server.v1_16_R1.PlayerChunk; +import net.minecraft.server.v1_16_R1.PlayerChunkMap; +import net.minecraft.server.v1_16_R1.World; +import net.minecraft.server.v1_16_R1.WorldServer; import org.bukkit.craftbukkit.v1_16_R1.CraftChunk; import org.bukkit.craftbukkit.v1_16_R1.CraftWorld; import sun.misc.Unsafe; @@ -34,18 +50,18 @@ public final class BukkitAdapter_1_16_1 extends NMSAdapter { /* NMS fields */ - public final static Field fieldBits; - public final static Field fieldPalette; - public final static Field fieldSize; + public static final Field fieldBits; + public static final Field fieldPalette; + public static final Field fieldSize; - public final static Field fieldBitsPerEntry; + public static final Field fieldBitsPerEntry; - public final static Field fieldFluidCount; - public final static Field fieldTickingBlockCount; - public final static Field fieldNonEmptyBlockCount; + public static final Field fieldFluidCount; + public static final Field fieldTickingBlockCount; + public static final Field fieldNonEmptyBlockCount; - private final static Field fieldDirtyCount; - private final static Field fieldDirtyBits; + private static final Field fieldDirtyCount; + private static final Field fieldDirtyBits; private static final Field fieldBiomeArray; @@ -95,8 +111,9 @@ public final class BukkitAdapter_1_16_1 extends NMSAdapter { Unsafe unsafe = UnsafeUtils.getUNSAFE(); CHUNKSECTION_BASE = unsafe.arrayBaseOffset(ChunkSection[].class); int scale = unsafe.arrayIndexScale(ChunkSection[].class); - if ((scale & (scale - 1)) != 0) + if ((scale & (scale - 1)) != 0) { throw new Error("data type scale not a power of two"); + } CHUNKSECTION_SHIFT = 31 - Integer.numberOfLeadingZeros(scale); } catch (RuntimeException e) { throw e; @@ -133,17 +150,17 @@ public final class BukkitAdapter_1_16_1 extends NMSAdapter { } } - public static Chunk ensureLoaded(World nmsWorld, int X, int Z) { - Chunk nmsChunk = nmsWorld.getChunkProvider().getChunkAt(X, Z, false); + public static Chunk ensureLoaded(World nmsWorld, int chunkX, int chunkZ) { + Chunk nmsChunk = nmsWorld.getChunkProvider().getChunkAt(chunkX, chunkZ, false); if (nmsChunk != null) { return nmsChunk; } if (Fawe.isMainThread()) { - return nmsWorld.getChunkAt(X, Z); + return nmsWorld.getChunkAt(chunkX, chunkZ); } if (PaperLib.isPaper()) { CraftWorld craftWorld = nmsWorld.getWorld(); - CompletableFuture future = craftWorld.getChunkAtAsync(X, Z, true); + CompletableFuture future = craftWorld.getChunkAtAsync(chunkX, chunkZ, true); try { CraftChunk chunk = (CraftChunk) future.get(); return chunk.getHandle(); @@ -152,20 +169,20 @@ public final class BukkitAdapter_1_16_1 extends NMSAdapter { } } // TODO optimize - return TaskManager.IMP.sync(() -> nmsWorld.getChunkAt(X, Z)); + return TaskManager.IMP.sync(() -> nmsWorld.getChunkAt(chunkX, chunkZ)); } public static PlayerChunk getPlayerChunk(WorldServer nmsWorld, final int cx, final int cz) { PlayerChunkMap chunkMap = nmsWorld.getChunkProvider().playerChunkMap; try { - return (PlayerChunk)methodGetVisibleChunk.invoke(chunkMap, ChunkCoordIntPair.pair(cx, cz)); + return (PlayerChunk) methodGetVisibleChunk.invoke(chunkMap, ChunkCoordIntPair.pair(cx, cz)); } catch (Throwable thr) { throw new RuntimeException(thr); } } - public static void sendChunk(WorldServer nmsWorld, int X, int Z, int mask, boolean lighting) { - PlayerChunk playerChunk = getPlayerChunk(nmsWorld, X, Z); + public static void sendChunk(WorldServer nmsWorld, int chunkX, int chunkZ, int mask, boolean lighting) { + PlayerChunk playerChunk = getPlayerChunk(nmsWorld, chunkX, chunkZ); if (playerChunk == null) { return; } @@ -186,7 +203,7 @@ public final class BukkitAdapter_1_16_1 extends NMSAdapter { fieldDirtyCount.set(playerChunk, 64); if (lighting) { - ChunkCoordIntPair chunkCoordIntPair = new ChunkCoordIntPair(X, Z); + ChunkCoordIntPair chunkCoordIntPair = new ChunkCoordIntPair(chunkX, chunkZ); boolean trustEdges = false; //Added in 1.16.1 Not sure what it does. PacketPlayOutLightUpdate packet = new PacketPlayOutLightUpdate(chunkCoordIntPair, nmsWorld.getChunkProvider().getLightEngine(), trustEdges); playerChunk.players.a(chunkCoordIntPair, false).forEach(p -> { @@ -241,7 +258,9 @@ public final class BukkitAdapter_1_16_1 extends NMSAdapter { final int blockBitArrayEnd = MathMan.ceilZero((float) 4096 / blocksPerLong); if (num_palette == 1) { - for (int i = 0; i < blockBitArrayEnd; i++) blockStates[i] = 0; + for (int i = 0; i < blockBitArrayEnd; i++) { + blockStates[i] = 0; + } } else { final BitArrayUnstretched bitArray = new BitArrayUnstretched(bitsPerEntry, 4096, blockStates); bitArray.fromRaw(blocksCopy); @@ -255,7 +274,6 @@ public final class BukkitAdapter_1_16_1 extends NMSAdapter { final long[] bits = Arrays.copyOfRange(blockStates, 0, blockBitArrayEnd); final DataBits nmsBits = new DataBits(bitsPerEntry, 4096, bits); final DataPalette palette; -// palette = new DataPaletteHash<>(Block.REGISTRY_ID, bitsPerEntry, dataPaletteBlocks, GameProfileSerializer::d, GameProfileSerializer::a); palette = new DataPaletteLinear<>(Block.REGISTRY_ID, bitsPerEntry, dataPaletteBlocks, GameProfileSerializer::c); // set palette diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BukkitGetBlocks_1_16_1.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BukkitGetBlocks_1_16_1.java index 5bd3fb709..a4d4c1227 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BukkitGetBlocks_1_16_1.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/BukkitGetBlocks_1_16_1.java @@ -15,8 +15,10 @@ import com.boydti.fawe.object.collection.AdaptedMap; import com.boydti.fawe.object.collection.BitArrayUnstretched; import com.google.common.base.Suppliers; import com.google.common.collect.Iterables; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.ListTag; +import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; -import com.sk89q.jnbt.*; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; @@ -25,7 +27,28 @@ import com.sk89q.worldedit.internal.Constants; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BlockTypes; -import net.minecraft.server.v1_16_R1.*; +import net.minecraft.server.v1_16_R1.BiomeBase; +import net.minecraft.server.v1_16_R1.BiomeStorage; +import net.minecraft.server.v1_16_R1.BlockPosition; +import net.minecraft.server.v1_16_R1.Chunk; +import net.minecraft.server.v1_16_R1.ChunkSection; +import net.minecraft.server.v1_16_R1.DataBits; +import net.minecraft.server.v1_16_R1.DataPalette; +import net.minecraft.server.v1_16_R1.DataPaletteBlock; +import net.minecraft.server.v1_16_R1.DataPaletteHash; +import net.minecraft.server.v1_16_R1.DataPaletteLinear; +import net.minecraft.server.v1_16_R1.Entity; +import net.minecraft.server.v1_16_R1.EntityTypes; +import net.minecraft.server.v1_16_R1.EnumSkyBlock; +import net.minecraft.server.v1_16_R1.HeightMap; +import net.minecraft.server.v1_16_R1.IBlockData; +import net.minecraft.server.v1_16_R1.LightEngine; +import net.minecraft.server.v1_16_R1.NBTTagCompound; +import net.minecraft.server.v1_16_R1.NBTTagInt; +import net.minecraft.server.v1_16_R1.NibbleArray; +import net.minecraft.server.v1_16_R1.SectionPosition; +import net.minecraft.server.v1_16_R1.TileEntity; +import net.minecraft.server.v1_16_R1.WorldServer; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.craftbukkit.v1_16_R1.CraftWorld; @@ -35,11 +58,20 @@ import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nullable; -import java.util.*; +import java.util.AbstractSet; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.function.Function; +import javax.annotation.Nullable; import static org.slf4j.LoggerFactory.getLogger; @@ -48,24 +80,30 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { private static final Logger log = LoggerFactory.getLogger(BukkitGetBlocks_1_16_1.class); private static final Function posNms2We = v -> BlockVector3.at(v.getX(), v.getY(), v.getZ()); - private final static Function nmsTile2We = tileEntity -> new LazyCompoundTag_1_16_1(Suppliers.memoize(() -> tileEntity.save(new NBTTagCompound()))); + private static final Function nmsTile2We = tileEntity -> new LazyCompoundTag_1_16_1(Suppliers.memoize(() -> tileEntity.save(new NBTTagCompound()))); public ChunkSection[] sections; public Chunk nmsChunk; public WorldServer world; - public int X, Z; + public int chunkX; + public int chunkZ; public NibbleArray[] blockLight = new NibbleArray[16]; public NibbleArray[] skyLight = new NibbleArray[16]; private boolean createCopy = false; private BukkitGetBlocks_1_16_1_Copy copy = null; - public BukkitGetBlocks_1_16_1(World world, int X, int Z) { - this(((CraftWorld) world).getHandle(), X, Z); + public BukkitGetBlocks_1_16_1(World world, int chunkX, int chunkZ) { + this(((CraftWorld) world).getHandle(), chunkX, chunkZ); } - public BukkitGetBlocks_1_16_1(WorldServer world, int X, int Z) { + public BukkitGetBlocks_1_16_1(WorldServer world, int chunkX, int chunkZ) { this.world = world; - this.X = X; - this.Z = Z; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + } + + + public int getChunkX() { + return chunkX; } @Override @@ -83,12 +121,8 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { return copy; } - public int getX() { - return X; - } - - public int getZ() { - return Z; + public int getChunkZ() { + return chunkZ; } @Override @@ -98,7 +132,9 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { if (y == -1) { for (y = 0; y < FaweCache.IMP.WORLD_HEIGHT; y++) { base = index.getBiome(x >> 2, y >> 2, z >> 2); - if (base != null) break; + if (base != null) { + break; + } } } else { base = index.getBiome(x >> 2, y >> 2, z >> 2); @@ -108,7 +144,9 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { @Override public CompoundTag getTile(int x, int y, int z) { - TileEntity tileEntity = getChunk().getTileEntity(new BlockPosition((x & 15) + (X << 4), y, (z & 15) + (Z << 4))); + TileEntity tileEntity = getChunk().getTileEntity(new BlockPosition((x & 15) + ( + chunkX << 4), y, (z & 15) + ( + chunkZ << 4))); if (tileEntity == null) { return null; } @@ -193,7 +231,9 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { List[] slices = getChunk().getEntitySlices(); int size = 0; for (List slice : slices) { - if (slice != null) size += slice.size(); + if (slice != null) { + size += slice.size(); + } } if (slices.length == 0) { return Collections.emptySet(); @@ -270,16 +310,16 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { entity.die(); } - public Chunk ensureLoaded(net.minecraft.server.v1_16_R1.World nmsWorld, int X, int Z) { - return BukkitAdapter_1_16_1.ensureLoaded(nmsWorld, X, Z); + public Chunk ensureLoaded(net.minecraft.server.v1_16_R1.World nmsWorld, int chunkX, int chunkZ) { + return BukkitAdapter_1_16_1.ensureLoaded(nmsWorld, chunkX, chunkZ); } @Override public > T call(IChunkSet set, Runnable finalizer) { - copy = createCopy ? new BukkitGetBlocks_1_16_1_Copy(world, getX(), getZ()) : null; + copy = createCopy ? new BukkitGetBlocks_1_16_1_Copy(world, getChunkX(), getChunkZ()) : null; try { WorldServer nmsWorld = world; - Chunk nmsChunk = ensureLoaded(nmsWorld, X, Z); + Chunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ); boolean fastmode = set.isFastMode() && Settings.IMP.QUEUE.NO_TICK_FASTMODE; // Remove existing tiles @@ -314,7 +354,7 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { ChunkSection[] sections = nmsChunk.getSections(); for (int layer = 0; layer < 16; layer++) { - if (!set.hasSection(layer)){ + if (!set.hasSection(layer)) { continue; } if (createCopy) { @@ -334,7 +374,8 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { } else { existingSection = sections[layer]; if (existingSection == null) { - log.error("Skipping invalid null section. chunk:" + X + "," + Z + " layer: " + layer); + log.error("Skipping invalid null section. chunk:" + chunkX + "," + + chunkZ + " layer: " + layer); continue; } } @@ -363,7 +404,7 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { .newChunkSection(layer, this::load, setArr, fastmode); if (!BukkitAdapter_1_16_1 .setSectionAtomic(sections, existingSection, newSection, layer)) { - log.error("Failed to set chunk section:" + X + "," + Z + " layer: " + layer); + log.error("Failed to set chunk section:" + chunkX + "," + chunkZ + " layer: " + layer); continue; } else { updateGet(this, nmsChunk, sections, newSection, setArr, layer); @@ -426,12 +467,14 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { Runnable[] syncTasks = null; - int bx = X << 4; - int bz = Z << 4; + int bx = chunkX << 4; + int bz = chunkZ << 4; Set entityRemoves = set.getEntityRemoves(); if (entityRemoves != null && !entityRemoves.isEmpty()) { - if (syncTasks == null) syncTasks = new Runnable[3]; + if (syncTasks == null) { + syncTasks = new Runnable[3]; + } syncTasks[2] = () -> { final List[] entities = nmsChunk.getEntitySlices(); @@ -456,7 +499,9 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { Set entities = set.getEntities(); if (entities != null && !entities.isEmpty()) { - if (syncTasks == null) syncTasks = new Runnable[2]; + if (syncTasks == null) { + syncTasks = new Runnable[2]; + } syncTasks[1] = () -> { for (final CompoundTag nativeTag : entities) { @@ -498,7 +543,9 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { // set tiles Map tiles = set.getTiles(); if (tiles != null && !tiles.isEmpty()) { - if (syncTasks == null) syncTasks = new Runnable[1]; + if (syncTasks == null) { + syncTasks = new Runnable[1]; + } syncTasks[0] = () -> { for (final Map.Entry entry : tiles.entrySet()) { @@ -540,8 +587,10 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { nmsChunk.mustNotSave = false; nmsChunk.markDirty(); // send to player - BukkitAdapter_1_16_1.sendChunk(nmsWorld, X, Z, finalMask, finalLightUpdate); - if (finalizer != null) finalizer.run(); + BukkitAdapter_1_16_1.sendChunk(nmsWorld, chunkX, chunkZ, finalMask, finalLightUpdate); + if (finalizer != null) { + finalizer.run(); + } }; } if (syncTasks != null) { @@ -558,7 +607,9 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { } } if (callback == null) { - if (finalizer != null) finalizer.run(); + if (finalizer != null) { + finalizer.run(); + } return null; } else { return queueHandler.async(callback, null); @@ -571,7 +622,9 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { return (T) (Future) queueHandler.sync(chain); } else { if (callback == null) { - if (finalizer != null) finalizer.run(); + if (finalizer != null) { + finalizer.run(); + } } else { callback.run(); } @@ -721,7 +774,7 @@ public class BukkitGetBlocks_1_16_1 extends CharGetBlocks { synchronized (this) { tmp = nmsChunk; if (tmp == null) { - nmsChunk = tmp = ensureLoaded(this.world, X, Z); + nmsChunk = tmp = ensureLoaded(this.world, chunkX, chunkZ); } } } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/FAWEWorldNativeAccess_1_16.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/FAWEWorldNativeAccess_1_16.java index 6b68ae95d..d3a3072e8 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/FAWEWorldNativeAccess_1_16.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_1/FAWEWorldNativeAccess_1_16.java @@ -26,12 +26,13 @@ import org.bukkit.craftbukkit.v1_16_R1.CraftWorld; import org.bukkit.craftbukkit.v1_16_R1.block.data.CraftBlockData; import org.bukkit.event.block.BlockPhysicsEvent; -import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.Objects; +import javax.annotation.Nullable; public class FAWEWorldNativeAccess_1_16 implements WorldNativeAccess { - private static final int UPDATE = 1, NOTIFY = 2; + private static final int UPDATE = 1; + private static final int NOTIFY = 2; private final FAWE_Spigot_v1_16_R1 adapter; private final WeakReference world; @@ -171,4 +172,4 @@ public class FAWEWorldNativeAccess_1_16 implements WorldNativeAccess> boolean setBlock(BlockVector3 position, B block, SideEffectSet sideEffects) throws WorldEditException { return this.adapter.setBlock(this.getChunk(position.getBlockX() >> 4, position.getBlockZ() >> 4).bukkitChunk, position.getBlockX(), position.getBlockY(), position.getBlockZ(), block, sideEffectSet.shouldApply(SideEffect.LIGHTING)); } -} \ No newline at end of file +} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BlockMaterial_1_16_2.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BlockMaterial_1_16_2.java index a0632695f..1b72cc954 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BlockMaterial_1_16_2.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BlockMaterial_1_16_2.java @@ -2,7 +2,14 @@ package com.boydti.fawe.bukkit.adapter.mc1_16_2; import com.sk89q.util.ReflectionUtil; import com.sk89q.worldedit.world.registry.BlockMaterial; -import net.minecraft.server.v1_16_R2.*; +import net.minecraft.server.v1_16_R2.Block; +import net.minecraft.server.v1_16_R2.BlockAccessAir; +import net.minecraft.server.v1_16_R2.BlockBase; +import net.minecraft.server.v1_16_R2.BlockPosition; +import net.minecraft.server.v1_16_R2.EnumPistonReaction; +import net.minecraft.server.v1_16_R2.IBlockData; +import net.minecraft.server.v1_16_R2.ITileEntity; +import net.minecraft.server.v1_16_R2.Material; import org.bukkit.craftbukkit.v1_16_R2.block.data.CraftBlockData; public class BlockMaterial_1_16_2 implements BlockMaterial { diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BukkitAdapter_1_16_2.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BukkitAdapter_1_16_2.java index 9ce2e25f1..d0c5fb2cd 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BukkitAdapter_1_16_2.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BukkitAdapter_1_16_2.java @@ -114,14 +114,15 @@ public final class BukkitAdapter_1_16_2 extends NMSAdapter { Unsafe unsafe = UnsafeUtils.getUNSAFE(); CHUNKSECTION_BASE = unsafe.arrayBaseOffset(ChunkSection[].class); int scale = unsafe.arrayIndexScale(ChunkSection[].class); - if ((scale & (scale - 1)) != 0) + if ((scale & (scale - 1)) != 0) { throw new Error("data type scale not a power of two"); + } CHUNKSECTION_SHIFT = 31 - Integer.numberOfLeadingZeros(scale); - Class clsShortArraySet; + Class clsShortArraySet; try { //paper clsShortArraySet = Class.forName(new String(new char[]{'i', 't', '.', 'u', 'n', 'i', 'm', 'i', '.', 'd', 's', 'i', '.', 'f', 'a', 's', 't', 'u', 't', 'i', 'l', '.', 's', 'h', 'o', 'r', 't', 's', '.', 'S', 'h', 'o', 'r', 't', 'A', 'r', 'r', 'a', 'y', 'S', 'e', 't'})); - } catch (Throwable t) {// still using spigot boooo + } catch (Throwable t) { // still using spigot boo clsShortArraySet = Class.forName(new String(new char[]{'o', 'r', 'g', '.', 'b', 'u', 'k', 'k', 'i', 't', '.', 'c', 'r', 'a', 'f', 't', 'b', 'u', 'k', 'k', 'i', 't', '.', 'l', 'i', 'b', 's', '.', 'i', 't', '.', 'u', 'n', 'i', 'm', 'i', '.', 'd', 's', 'i', '.', 'f', 'a', 's', 't', 'u', 't', 'i', 'l', '.', 's', 'h', 'o', 'r', 't', 's', '.', 'S', 'h', 'o', 'r', 't', 'A', 'r', 'r', 'a', 'y', 'S', 'e', 't'})); } } catch (RuntimeException e) { @@ -184,7 +185,7 @@ public final class BukkitAdapter_1_16_2 extends NMSAdapter { public static PlayerChunk getPlayerChunk(WorldServer nmsWorld, final int chunkX, final int chunkZ) { PlayerChunkMap chunkMap = nmsWorld.getChunkProvider().playerChunkMap; try { - return (PlayerChunk)methodGetVisibleChunk.invoke(chunkMap, ChunkCoordIntPair.pair(chunkX, chunkZ)); + return (PlayerChunk) methodGetVisibleChunk.invoke(chunkMap, ChunkCoordIntPair.pair(chunkX, chunkZ)); } catch (Throwable thr) { throw new RuntimeException(thr); } @@ -207,7 +208,6 @@ public final class BukkitAdapter_1_16_2 extends NMSAdapter { } if (lighting) { -// ChunkCoordIntPair chunkCoordIntPair = new ChunkCoordIntPair(chunkX, chunkZ); boolean trustEdges = true; //This needs to be true otherwise Minecraft will update lighting from/at the chunk edges (bad) PacketPlayOutLightUpdate packet = new PacketPlayOutLightUpdate(chunkCoordIntPair, nmsWorld.getChunkProvider().getLightEngine(), trustEdges); playerChunk.players.a(chunkCoordIntPair, false).forEach(p -> { @@ -258,7 +258,9 @@ public final class BukkitAdapter_1_16_2 extends NMSAdapter { final int blockBitArrayEnd = MathMan.ceilZero((float) 4096 / blocksPerLong); if (num_palette == 1) { - for (int i = 0; i < blockBitArrayEnd; i++) blockStates[i] = 0; + for (int i = 0; i < blockBitArrayEnd; i++) { + blockStates[i] = 0; + } } else { final BitArrayUnstretched bitArray = new BitArrayUnstretched(bitsPerEntry, 4096, blockStates); bitArray.fromRaw(blocksCopy); @@ -272,7 +274,6 @@ public final class BukkitAdapter_1_16_2 extends NMSAdapter { final long[] bits = Arrays.copyOfRange(blockStates, 0, blockBitArrayEnd); final DataBits nmsBits = new DataBits(bitsPerEntry, 4096, bits); final DataPalette palette; -// palette = new DataPaletteHash<>(Block.REGISTRY_ID, bitsPerEntry, dataPaletteBlocks, GameProfileSerializer::d, GameProfileSerializer::a); palette = new DataPaletteLinear<>(Block.REGISTRY_ID, bitsPerEntry, dataPaletteBlocks, GameProfileSerializer::c); // set palette diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BukkitGetBlocks_1_16_2.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BukkitGetBlocks_1_16_2.java index 1965b2830..e61453ddf 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BukkitGetBlocks_1_16_2.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/BukkitGetBlocks_1_16_2.java @@ -15,8 +15,10 @@ import com.boydti.fawe.object.collection.AdaptedMap; import com.boydti.fawe.object.collection.BitArrayUnstretched; import com.google.common.base.Suppliers; import com.google.common.collect.Iterables; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.ListTag; +import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; -import com.sk89q.jnbt.*; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; @@ -25,7 +27,29 @@ import com.sk89q.worldedit.internal.Constants; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BlockTypes; -import net.minecraft.server.v1_16_R2.*; +import net.minecraft.server.v1_16_R2.BiomeBase; +import net.minecraft.server.v1_16_R2.BiomeStorage; +import net.minecraft.server.v1_16_R2.BlockPosition; +import net.minecraft.server.v1_16_R2.Chunk; +import net.minecraft.server.v1_16_R2.ChunkSection; +import net.minecraft.server.v1_16_R2.DataBits; +import net.minecraft.server.v1_16_R2.DataPalette; +import net.minecraft.server.v1_16_R2.DataPaletteBlock; +import net.minecraft.server.v1_16_R2.DataPaletteHash; +import net.minecraft.server.v1_16_R2.DataPaletteLinear; +import net.minecraft.server.v1_16_R2.Entity; +import net.minecraft.server.v1_16_R2.EntityTypes; +import net.minecraft.server.v1_16_R2.EnumSkyBlock; +import net.minecraft.server.v1_16_R2.HeightMap; +import net.minecraft.server.v1_16_R2.IBlockData; +import net.minecraft.server.v1_16_R2.IRegistry; +import net.minecraft.server.v1_16_R2.LightEngine; +import net.minecraft.server.v1_16_R2.NBTTagCompound; +import net.minecraft.server.v1_16_R2.NBTTagInt; +import net.minecraft.server.v1_16_R2.NibbleArray; +import net.minecraft.server.v1_16_R2.SectionPosition; +import net.minecraft.server.v1_16_R2.TileEntity; +import net.minecraft.server.v1_16_R2.WorldServer; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.craftbukkit.v1_16_R2.CraftWorld; @@ -35,11 +59,20 @@ import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nullable; -import java.util.*; +import java.util.AbstractSet; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.function.Function; +import javax.annotation.Nullable; import static org.slf4j.LoggerFactory.getLogger; @@ -48,24 +81,29 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { private static final Logger log = LoggerFactory.getLogger(BukkitGetBlocks_1_16_2.class); private static final Function posNms2We = v -> BlockVector3.at(v.getX(), v.getY(), v.getZ()); - private final static Function nmsTile2We = tileEntity -> new LazyCompoundTag_1_16_2(Suppliers.memoize(() -> tileEntity.save(new NBTTagCompound()))); + private static final Function nmsTile2We = tileEntity -> new LazyCompoundTag_1_16_2(Suppliers.memoize(() -> tileEntity.save(new NBTTagCompound()))); public ChunkSection[] sections; public Chunk nmsChunk; public WorldServer world; - public int X, Z; + public int chunkX; + public int chunkZ; public NibbleArray[] blockLight = new NibbleArray[16]; public NibbleArray[] skyLight = new NibbleArray[16]; private boolean createCopy = false; private BukkitGetBlocks_1_16_2_Copy copy = null; - public BukkitGetBlocks_1_16_2(World world, int X, int Z) { - this(((CraftWorld) world).getHandle(), X, Z); + public BukkitGetBlocks_1_16_2(World world, int chunkX, int chunkZ) { + this(((CraftWorld) world).getHandle(), chunkX, chunkZ); } - public BukkitGetBlocks_1_16_2(WorldServer world, int X, int Z) { + public BukkitGetBlocks_1_16_2(WorldServer world, int chunkX, int chunkZ) { this.world = world; - this.X = X; - this.Z = Z; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + } + + public int getChunkX() { + return chunkX; } @Override @@ -83,12 +121,8 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { return copy; } - public int getX() { - return X; - } - - public int getZ() { - return Z; + public int getChunkZ() { + return chunkZ; } @Override @@ -98,7 +132,9 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { if (y == -1) { for (y = 0; y < FaweCache.IMP.WORLD_HEIGHT; y++) { base = index.getBiome(x >> 2, y >> 2, z >> 2); - if (base != null) break; + if (base != null) { + break; + } } } else { base = index.getBiome(x >> 2, y >> 2, z >> 2); @@ -108,7 +144,9 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { @Override public CompoundTag getTile(int x, int y, int z) { - TileEntity tileEntity = getChunk().getTileEntity(new BlockPosition((x & 15) + (X << 4), y, (z & 15) + (Z << 4))); + TileEntity tileEntity = getChunk().getTileEntity(new BlockPosition((x & 15) + ( + chunkX << 4), y, (z & 15) + ( + chunkZ << 4))); if (tileEntity == null) { return null; } @@ -196,7 +234,9 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { List[] slices = getChunk().getEntitySlices(); int size = 0; for (List slice : slices) { - if (slice != null) size += slice.size(); + if (slice != null) { + size += slice.size(); + } } if (slices.length == 0) { return Collections.emptySet(); @@ -273,16 +313,16 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { entity.die(); } - public Chunk ensureLoaded(net.minecraft.server.v1_16_R2.World nmsWorld, int X, int Z) { - return BukkitAdapter_1_16_2.ensureLoaded(nmsWorld, X, Z); + public Chunk ensureLoaded(net.minecraft.server.v1_16_R2.World nmsWorld, int chunkX, int chunkZ) { + return BukkitAdapter_1_16_2.ensureLoaded(nmsWorld, chunkX, chunkZ); } @Override public > T call(IChunkSet set, Runnable finalizer) { - copy = createCopy ? new BukkitGetBlocks_1_16_2_Copy(world, getX(), getZ()) : null; + copy = createCopy ? new BukkitGetBlocks_1_16_2_Copy(world, getChunkX(), getChunkZ()) : null; try { WorldServer nmsWorld = world; - Chunk nmsChunk = ensureLoaded(nmsWorld, X, Z); + Chunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ); boolean fastmode = set.isFastMode() && Settings.IMP.QUEUE.NO_TICK_FASTMODE; // Remove existing tiles @@ -317,7 +357,7 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { ChunkSection[] sections = nmsChunk.getSections(); for (int layer = 0; layer < 16; layer++) { - if (!set.hasSection(layer)){ + if (!set.hasSection(layer)) { continue; } if (createCopy) { @@ -337,7 +377,8 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { } else { existingSection = sections[layer]; if (existingSection == null) { - log.error("Skipping invalid null section. chunk:" + X + "," + Z + " layer: " + layer); + log.error("Skipping invalid null section. chunk:" + chunkX + "," + + chunkZ + " layer: " + layer); continue; } } @@ -366,7 +407,7 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { .newChunkSection(layer, this::load, setArr, fastmode); if (!BukkitAdapter_1_16_2 .setSectionAtomic(sections, existingSection, newSection, layer)) { - log.error("Failed to set chunk section:" + X + "," + Z + " layer: " + layer); + log.error("Failed to set chunk section:" + chunkX + "," + chunkZ + " layer: " + layer); continue; } else { updateGet(this, nmsChunk, sections, newSection, setArr, layer); @@ -429,12 +470,14 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { Runnable[] syncTasks = null; - int bx = X << 4; - int bz = Z << 4; + int bx = chunkX << 4; + int bz = chunkZ << 4; Set entityRemoves = set.getEntityRemoves(); if (entityRemoves != null && !entityRemoves.isEmpty()) { - if (syncTasks == null) syncTasks = new Runnable[3]; + if (syncTasks == null) { + syncTasks = new Runnable[3]; + } syncTasks[2] = () -> { final List[] entities = nmsChunk.getEntitySlices(); @@ -459,7 +502,9 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { Set entities = set.getEntities(); if (entities != null && !entities.isEmpty()) { - if (syncTasks == null) syncTasks = new Runnable[2]; + if (syncTasks == null) { + syncTasks = new Runnable[2]; + } syncTasks[1] = () -> { for (final CompoundTag nativeTag : entities) { @@ -501,7 +546,9 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { // set tiles Map tiles = set.getTiles(); if (tiles != null && !tiles.isEmpty()) { - if (syncTasks == null) syncTasks = new Runnable[1]; + if (syncTasks == null) { + syncTasks = new Runnable[1]; + } syncTasks[0] = () -> { for (final Map.Entry entry : tiles.entrySet()) { @@ -543,8 +590,10 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { nmsChunk.mustNotSave = false; nmsChunk.markDirty(); // send to player - BukkitAdapter_1_16_2.sendChunk(nmsWorld, X, Z, finalMask, finalLightUpdate); - if (finalizer != null) finalizer.run(); + BukkitAdapter_1_16_2.sendChunk(nmsWorld, chunkX, chunkZ, finalMask, finalLightUpdate); + if (finalizer != null) { + finalizer.run(); + } }; } if (syncTasks != null) { @@ -561,7 +610,9 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { } } if (callback == null) { - if (finalizer != null) finalizer.run(); + if (finalizer != null) { + finalizer.run(); + } return null; } else { return queueHandler.async(callback, null); @@ -574,7 +625,9 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { return (T) (Future) queueHandler.sync(chain); } else { if (callback == null) { - if (finalizer != null) finalizer.run(); + if (finalizer != null) { + finalizer.run(); + } } else { callback.run(); } @@ -724,7 +777,7 @@ public class BukkitGetBlocks_1_16_2 extends CharGetBlocks { synchronized (this) { tmp = nmsChunk; if (tmp == null) { - nmsChunk = tmp = ensureLoaded(this.world, X, Z); + nmsChunk = tmp = ensureLoaded(this.world, chunkX, chunkZ); } } } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/FAWEWorldNativeAccess_1_16.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/FAWEWorldNativeAccess_1_16.java index 4d7c9f5ca..664fd0609 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/FAWEWorldNativeAccess_1_16.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/mc1_16_2/FAWEWorldNativeAccess_1_16.java @@ -26,12 +26,13 @@ import org.bukkit.craftbukkit.v1_16_R2.CraftWorld; import org.bukkit.craftbukkit.v1_16_R2.block.data.CraftBlockData; import org.bukkit.event.block.BlockPhysicsEvent; -import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.Objects; +import javax.annotation.Nullable; public class FAWEWorldNativeAccess_1_16 implements WorldNativeAccess { - private static final int UPDATE = 1, NOTIFY = 2; + private static final int UPDATE = 1; + private static final int NOTIFY = 2; private final FAWE_Spigot_v1_16_R2 adapter; private final WeakReference world; @@ -171,4 +172,4 @@ public class FAWEWorldNativeAccess_1_16 implements WorldNativeAccess> boolean setBlock(BlockVector3 position, B block, SideEffectSet sideEffects) throws WorldEditException { return this.adapter.setBlock(this.getChunk(position.getBlockX() >> 4, position.getBlockZ() >> 4).bukkitChunk, position.getBlockX(), position.getBlockY(), position.getBlockZ(), block, sideEffectSet.shouldApply(SideEffect.LIGHTING)); } -} \ No newline at end of file +} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/filter/WorldGuardFilter.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/filter/WorldGuardFilter.java index 0212cdbc8..678270aba 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/filter/WorldGuardFilter.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/filter/WorldGuardFilter.java @@ -1,8 +1,5 @@ package com.boydti.fawe.bukkit.filter; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.slf4j.LoggerFactory.getLogger; - import com.boydti.fawe.Fawe; import com.boydti.fawe.regions.general.CuboidRegionFilter; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -14,6 +11,9 @@ import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import org.bukkit.World; +import static com.google.common.base.Preconditions.checkNotNull; +import static org.slf4j.LoggerFactory.getLogger; + public class WorldGuardFilter extends CuboidRegionFilter { private final World world; private boolean large; @@ -23,6 +23,7 @@ public class WorldGuardFilter extends CuboidRegionFilter { checkNotNull(world); this.world = world; } + @Override public void calculateRegions() { Fawe.get().getQueueHandler().sync(() -> { @@ -43,7 +44,9 @@ public class WorldGuardFilter extends CuboidRegionFilter { @Override public boolean containsChunk(int chunkX, int chunkZ) { - if (!large) return super.containsChunk(chunkX, chunkZ); + if (!large) { + return super.containsChunk(chunkX, chunkZ); + } BlockVector3 pos1 = BlockVector3.at(chunkX << 4, 0, chunkZ << 4); BlockVector3 pos2 = BlockVector3.at(pos1.getBlockX() + 15, 255, pos1.getBlockZ() + 15); ProtectedCuboidRegion chunkRegion = new ProtectedCuboidRegion("unimportant", pos1, pos2); @@ -53,7 +56,9 @@ public class WorldGuardFilter extends CuboidRegionFilter { @Override public boolean containsRegion(int mcaX, int mcaZ) { - if (!large) return super.containsRegion(mcaX, mcaZ); + if (!large) { + return super.containsRegion(mcaX, mcaZ); + } BlockVector3 pos1 = BlockVector3.at(mcaX << 9, 0, mcaZ << 9); BlockVector3 pos2 = BlockVector3.at(pos1.getBlockX() + 511, 255, pos1.getBlockZ() + 511); ProtectedCuboidRegion regionRegion = new ProtectedCuboidRegion("unimportant", pos1, pos2); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/BukkitImageListener.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/BukkitImageListener.java index 507594edf..176167e36 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/BukkitImageListener.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/BukkitImageListener.java @@ -1,39 +1,17 @@ package com.boydti.fawe.bukkit.listener; -import com.boydti.fawe.beta.IQueueExtent; import com.boydti.fawe.bukkit.util.image.BukkitImageViewer; -import com.boydti.fawe.object.brush.BrushSettings; import com.boydti.fawe.object.brush.visualization.cfi.HeightMapMCAGenerator; -import com.boydti.fawe.util.EditSessionBuilder; -import com.boydti.fawe.util.ExtentTraverser; -import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.image.ImageViewer; -import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.BukkitPlayer; -import com.sk89q.worldedit.command.tool.BrushTool; -import com.sk89q.worldedit.command.tool.InvalidToolBindException; -import com.sk89q.worldedit.command.tool.brush.Brush; -import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.math.BlockVector3; -import java.util.ArrayDeque; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.Location; -import org.bukkit.Rotation; import org.bukkit.World; import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.bukkit.entity.ItemFrame; import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -41,13 +19,15 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.hanging.HangingBreakByEntityEvent; -import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.plugin.Plugin; +import java.util.Collection; +import java.util.List; + public class BukkitImageListener implements Listener { private Location mutable = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); @@ -57,31 +37,32 @@ public class BukkitImageListener implements Listener { } //TODO Fix along with CFI code 2020-02-04 -// @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) -// public void onPlayerInteractEntity(AsyncPlayerChatEvent event) { -// Set recipients = event.getRecipients(); -// Iterator iter = recipients.iterator(); -// while (iter.hasNext()) { -// Player player = iter.next(); -// BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player); -// CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings"); -// if (player.equals(event.getPlayer()) || !bukkitPlayer.hasMeta() || settings == null || !settings.hasGenerator()) { -// continue; -// } -// -// String name = player.getName().toLowerCase(); -// if (!event.getMessage().toLowerCase().contains(name)) { -// ArrayDeque buffered = bukkitPlayer.getMeta("CFIBufferedMessages"); -// if (buffered == null) { -// bukkitPlayer.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque<>()); -// } -// String full = String.format(event.getFormat(), event.getPlayer().getDisplayName(), -// event.getMessage()); -// buffered.add(full); -// iter.remove(); -// } -// } -// } + /* + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onPlayerInteractEntity(AsyncPlayerChatEvent event) { + Set recipients = event.getRecipients(); + Iterator iter = recipients.iterator(); + while (iter.hasNext()) { + Player player = iter.next(); + BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player); + CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings"); + if (player.equals(event.getPlayer()) || !bukkitPlayer.hasMeta() || settings == null || !settings.hasGenerator()) { + continue; + } + + String name = player.getName().toLowerCase(Locale.ROOT); + if (!event.getMessage().toLowerCase(Locale.ROOT).contains(name)) { + ArrayDeque buffered = bukkitPlayer.getMeta("CFIBufferedMessages"); + if (buffered == null) { + bukkitPlayer.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque<>()); + } + String full = String.format(event.getFormat(), event.getPlayer().getDisplayName(), + event.getMessage()); + buffered.add(full); + iter.remove(); + } + } + }*/ @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) public void onHangingBreakByEntity(HangingBreakByEntityEvent event) { @@ -185,126 +166,127 @@ public class BukkitImageListener implements Listener { private void handleInteract(Event event, Player player, Entity entity, boolean primary) { //todo fix with cfi code 2020-02-04 -// if (!(entity instanceof ItemFrame)) { -// return; -// } -// ItemFrame itemFrame = (ItemFrame) entity; -// -// BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player); -// CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings"); -// HeightMapMCAGenerator generator = settings == null ? null : settings.getGenerator(); -// BukkitImageViewer viewer = get(generator); -// if (viewer == null) { -// return; -// } -// -// if (itemFrame.getRotation() != Rotation.NONE) { -// itemFrame.setRotation(Rotation.NONE); -// } -// -// LocalSession session = bukkitPlayer.getSession(); -// BrushTool tool; -// try { -// tool = session.getBrushTool(bukkitPlayer, false); -// } catch (InvalidToolBindException e) { -// return; -// } -// -// ItemFrame[][] frames = viewer.getItemFrames(); -// if (frames == null || tool == null) { -// viewer.selectFrame(itemFrame); -// player.updateInventory(); -// TaskManager.IMP.laterAsync(() -> viewer.view(generator), 1); -// return; -// } -// -// BrushSettings context = primary ? tool.getPrimary() : tool.getSecondary(); -// Brush brush = context.getBrush(); -// if (brush == null) { -// return; -// } -// tool.setContext(context); -// -// if (event instanceof Cancellable) { -// ((Cancellable) event).setCancelled(true); -// } -// -// Location target = itemFrame.getLocation(); -// Location source = player.getLocation(); -// -// double yawRad = Math.toRadians(source.getYaw() + 90d); -// double pitchRad = Math.toRadians(-source.getPitch()); -// -// double a = Math.cos(pitchRad); -// double xRat = Math.cos(yawRad) * a; -// double zRat = Math.sin(yawRad) * a; -// -// BlockFace facing = itemFrame.getFacing(); -// double thickness = 1 / 32D + 1 / 128D; -// double modX = facing.getModX(); -// double modZ = facing.getModZ(); -// double dx = source.getX() - target.getX() - modX * thickness; -// double dy = source.getY() + player.getEyeHeight() - target.getY(); -// double dz = source.getZ() - target.getZ() - modZ * thickness; -// -// double offset; -// double localX; -// if (modX != 0) { -// offset = dx / xRat; -// localX = (-modX) * (dz - offset * zRat); -// } else { -// offset = dz / zRat; -// localX = (modZ) * (dx - offset * xRat); -// } -// double localY = dy - offset * Math.sin(pitchRad); -// int localPixelX = (int) ((localX + 0.5) * 128); -// int localPixelY = (int) ((localY + 0.5) * 128); -// -// UUID uuid = itemFrame.getUniqueId(); -// for (int blockX = 0; blockX < frames.length; blockX++) { -// for (int blockY = 0; blockY < frames[0].length; blockY++) { -// if (uuid.equals(frames[blockX][blockY].getUniqueId())) { -// int pixelX = localPixelX + blockX * 128; -// int pixelY = (128 * frames[0].length) - (localPixelY + blockY * 128 + 1); -// -// int width = generator.getWidth(); -// int length = generator.getLength(); -// int worldX = (int) (pixelX * width / (frames.length * 128d)); -// int worldZ = (int) (pixelY * length / (frames[0].length * 128d)); -// -// if (worldX < 0 || worldX > width || worldZ < 0 || worldZ > length) { -// return; -// } -// -// bukkitPlayer.runAction(() -> { -// BlockVector3 wPos = BlockVector3.at(worldX, 0, worldZ); -// viewer.refresh(); -// int topY = generator -// .getNearestSurfaceTerrainBlock(wPos.getBlockX(), wPos.getBlockZ(), 255, -// 0, 255); -// wPos = wPos.withY(topY); -// -// EditSession es = new EditSessionBuilder(bukkitPlayer.getWorld()).player(bukkitPlayer) -// .combineStages(false).autoQueue(false).blockBag(null).limitUnlimited() -// .build(); -// ExtentTraverser last = new ExtentTraverser(es.getExtent()).last(); -// Extent extent = last.get(); -// if (extent instanceof IQueueExtent) { -// last = last.previous(); -// } -// last.setNext(generator); -// try { -// brush.build(es, wPos, context.getMaterial(), context.getSize()); -// } catch (WorldEditException e) { -// e.printStackTrace(); -// } -// es.flushQueue(); -// viewer.view(generator); -// }, true, true); -// -// return; -// } -// } -// } + /* + if (!(entity instanceof ItemFrame)) { + return; + } + ItemFrame itemFrame = (ItemFrame) entity; + + BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player); + CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings"); + HeightMapMCAGenerator generator = settings == null ? null : settings.getGenerator(); + BukkitImageViewer viewer = get(generator); + if (viewer == null) { + return; + } + + if (itemFrame.getRotation() != Rotation.NONE) { + itemFrame.setRotation(Rotation.NONE); + } + + LocalSession session = bukkitPlayer.getSession(); + BrushTool tool; + try { + tool = session.getBrushTool(bukkitPlayer, false); + } catch (InvalidToolBindException e) { + return; + } + + ItemFrame[][] frames = viewer.getItemFrames(); + if (frames == null || tool == null) { + viewer.selectFrame(itemFrame); + player.updateInventory(); + TaskManager.IMP.laterAsync(() -> viewer.view(generator), 1); + return; + } + + BrushSettings context = primary ? tool.getPrimary() : tool.getSecondary(); + Brush brush = context.getBrush(); + if (brush == null) { + return; + } + tool.setContext(context); + + if (event instanceof Cancellable) { + ((Cancellable) event).setCancelled(true); + } + + Location target = itemFrame.getLocation(); + Location source = player.getLocation(); + + double yawRad = Math.toRadians(source.getYaw() + 90d); + double pitchRad = Math.toRadians(-source.getPitch()); + + double a = Math.cos(pitchRad); + double xRat = Math.cos(yawRad) * a; + double zRat = Math.sin(yawRad) * a; + + BlockFace facing = itemFrame.getFacing(); + double thickness = 1 / 32D + 1 / 128D; + double modX = facing.getModX(); + double modZ = facing.getModZ(); + double dx = source.getX() - target.getX() - modX * thickness; + double dy = source.getY() + player.getEyeHeight() - target.getY(); + double dz = source.getZ() - target.getZ() - modZ * thickness; + + double offset; + double localX; + if (modX != 0) { + offset = dx / xRat; + localX = (-modX) * (dz - offset * zRat); + } else { + offset = dz / zRat; + localX = (modZ) * (dx - offset * xRat); + } + double localY = dy - offset * Math.sin(pitchRad); + int localPixelX = (int) ((localX + 0.5) * 128); + int localPixelY = (int) ((localY + 0.5) * 128); + + UUID uuid = itemFrame.getUniqueId(); + for (int blockX = 0; blockX < frames.length; blockX++) { + for (int blockY = 0; blockY < frames[0].length; blockY++) { + if (uuid.equals(frames[blockX][blockY].getUniqueId())) { + int pixelX = localPixelX + blockX * 128; + int pixelY = (128 * frames[0].length) - (localPixelY + blockY * 128 + 1); + + int width = generator.getWidth(); + int length = generator.getLength(); + int worldX = (int) (pixelX * width / (frames.length * 128d)); + int worldZ = (int) (pixelY * length / (frames[0].length * 128d)); + + if (worldX < 0 || worldX > width || worldZ < 0 || worldZ > length) { + return; + } + + bukkitPlayer.runAction(() -> { + BlockVector3 wPos = BlockVector3.at(worldX, 0, worldZ); + viewer.refresh(); + int topY = generator + .getNearestSurfaceTerrainBlock(wPos.getBlockX(), wPos.getBlockZ(), 255, + 0, 255); + wPos = wPos.withY(topY); + + EditSession es = new EditSessionBuilder(bukkitPlayer.getWorld()).player(bukkitPlayer) + .combineStages(false).autoQueue(false).blockBag(null).limitUnlimited() + .build(); + ExtentTraverser last = new ExtentTraverser(es.getExtent()).last(); + Extent extent = last.get(); + if (extent instanceof IQueueExtent) { + last = last.previous(); + } + last.setNext(generator); + try { + brush.build(es, wPos, context.getMaterial(), context.getSize()); + } catch (WorldEditException e) { + e.printStackTrace(); + } + es.flushQueue(); + viewer.view(generator); + }, true, true); + + return; + } + } + }*/ } } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/CFIPacketListener.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/CFIPacketListener.java index 6d2679df3..59f391fbd 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/CFIPacketListener.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/CFIPacketListener.java @@ -22,17 +22,10 @@ import com.sk89q.worldedit.event.platform.BlockInteractEvent; import com.sk89q.worldedit.event.platform.Interaction; import com.sk89q.worldedit.extension.platform.PlatformManager; import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.world.block.BlockState; -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.util.List; - -import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -40,13 +33,17 @@ import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; /** - * The CFIPacketListener handles packets for editing the VirtualWorld - * The generator is a virtual world which only the creator can see - * - The virtual world is displayed inside the current world - * - Block/Chunk/Movement packets need to be handled properly + * The CFIPacketListener handles packets for editing the {@link VirtualWorld}. + * + *

+ * The virtual world will be displayed inside the current world. Block/Chunk/Movement packets + * need to be handled properly. + *

*/ public class CFIPacketListener implements Listener { @@ -122,7 +119,9 @@ public class CFIPacketListener implements Listener { protocolmanager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.NORMAL, PacketType.Play.Server.MAP_CHUNK) { @Override public void onPacketSending(PacketEvent event) { - if (!event.isServerPacket() || FaweCache.IMP.CHUNK_FLAG.get().get()) return; + if (!event.isServerPacket() || FaweCache.IMP.CHUNK_FLAG.get().get()) { + return; + } VirtualWorld gen = getGenerator(event); if (gen != null) { BlockVector3 origin = gen.getOrigin().toBlockPoint(); @@ -147,7 +146,9 @@ public class CFIPacketListener implements Listener { protocolmanager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.NORMAL, PacketType.Play.Server.ENTITY_VELOCITY) { @Override public void onPacketSending(PacketEvent event) { - if (!event.isServerPacket()) return; + if (!event.isServerPacket()) { + return; + } Player player = event.getPlayer(); Location pos = player.getLocation(); @@ -172,7 +173,9 @@ public class CFIPacketListener implements Listener { protocolmanager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.NORMAL, PacketType.Play.Server.POSITION) { @Override public void onPacketSending(PacketEvent event) { - if (!event.isServerPacket()) return; + if (!event.isServerPacket()) { + return; + } Player player = event.getPlayer(); Location pos = player.getLocation(); @@ -202,7 +205,9 @@ public class CFIPacketListener implements Listener { protocolmanager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.NORMAL, PacketType.Play.Server.MULTI_BLOCK_CHANGE) { @Override public void onPacketSending(PacketEvent event) { - if (!event.isServerPacket()) return; + if (!event.isServerPacket()) { + return; + } VirtualWorld gen = getGenerator(event); if (gen != null) { @@ -260,11 +265,13 @@ public class CFIPacketListener implements Listener { private VirtualWorld getGenerator(Player player) { BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player); VirtualWorld vw = bukkitPlayer.getSession().getVirtualWorld(); - if (vw != null) return vw; + if (vw != null) { + return vw; + } // CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings"); -// if (settings != null && settings.hasGenerator() && settings.getGenerator().hasPacketViewer()) { -// return settings.getGenerator(); -// } + // if (settings != null && settings.hasGenerator() && settings.getGenerator().hasPacketViewer()) { + // return settings.getGenerator(); + // } return null; } @@ -272,7 +279,9 @@ public class CFIPacketListener implements Listener { PacketContainer packet = event.getPacket(); StructureModifier position = packet.getBlockPositionModifier(); BlockPosition loc = position.readSafely(0); - if (loc == null) return null; + if (loc == null) { + return null; + } BlockVector3 origin = generator.getOrigin().toBlockPoint(); return BlockVector3.at(loc.getX() - origin.getBlockX(), loc.getY() - origin.getBlockY(), loc.getZ() - origin.getBlockZ()); } @@ -282,7 +291,9 @@ public class CFIPacketListener implements Listener { if (gen != null) { BlockVector3 pt = getRelPos(event, gen); if (pt != null) { - if (relative) pt = getRelative(event, pt); + if (relative) { + pt = getRelative(event, pt); + } if (gen.contains(pt)) { event.setCancelled(true); task.run(event, gen, pt); @@ -295,7 +306,9 @@ public class CFIPacketListener implements Listener { protocolmanager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.NORMAL, type) { @Override public void onPacketReceiving(final PacketEvent event) { - if (type.isClient() || event.isServerPacket()) handleBlockEvent(event, relative, task); + if (type.isClient() || event.isServerPacket()) { + handleBlockEvent(event, relative, task); + } } @Override @@ -309,7 +322,9 @@ public class CFIPacketListener implements Listener { PacketContainer packet = container.getPacket(); StructureModifier dirs = packet.getDirections(); EnumWrappers.Direction dir = dirs.readSafely(0); - if (dir == null) return pt; + if (dir == null) { + return pt; + } switch (dir.ordinal()) { case 0: return pt.add(0, -1, 0); case 1: return pt.add(0, 1, 0); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener.java index d9b20df0c..4c597c5bf 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener.java @@ -1,7 +1,5 @@ package com.boydti.fawe.bukkit.listener; -import static org.slf4j.LoggerFactory.getLogger; - import com.boydti.fawe.Fawe; import com.boydti.fawe.bukkit.FaweBukkit; import com.boydti.fawe.config.Settings; @@ -25,6 +23,7 @@ import org.bukkit.event.block.BlockCanBuildEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockDispenseEvent; import org.bukkit.event.block.BlockExpEvent; +import org.bukkit.event.block.BlockExplodeEvent; import org.bukkit.event.block.BlockFadeEvent; import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockGrowEvent; @@ -45,6 +44,8 @@ import org.bukkit.plugin.PluginManager; import org.bukkit.util.Vector; import org.slf4j.Logger; +import static org.slf4j.LoggerFactory.getLogger; + public abstract class ChunkListener implements Listener { private final Logger logger = getLogger(ChunkListener.class); @@ -58,10 +59,6 @@ public abstract class ChunkListener implements Listener { PluginManager plm = Bukkit.getPluginManager(); Plugin plugin = Fawe.imp().getPlugin(); plm.registerEvents(this, plugin); - try { - plm.registerEvents(new ChunkListener_8Plus(this), plugin); - } catch (Throwable ignore) { - } TaskManager.IMP.repeat(() -> { Location tmpLoc = lastCancelPos; if (tmpLoc != null) { @@ -98,7 +95,8 @@ public abstract class ChunkListener implements Listener { protected final Long2ObjectOpenHashMap badChunks = new Long2ObjectOpenHashMap<>(); private Long2ObjectOpenHashMap counter = new Long2ObjectOpenHashMap<>(); - private int lastX = Integer.MIN_VALUE, lastZ = Integer.MIN_VALUE; + private int lastX = Integer.MIN_VALUE; + private int lastZ = Integer.MIN_VALUE; private int[] lastCount; public int[] getCount(int cx, int cz) { @@ -138,6 +136,11 @@ public abstract class ChunkListener implements Listener { physCancel = false; } + @EventHandler(priority = EventPriority.LOWEST) + public void event(BlockExplodeEvent event) { + reset(); + } + @EventHandler(priority = EventPriority.LOWEST) public void event(BlockBurnEvent event) { reset(); @@ -250,14 +253,6 @@ public abstract class ChunkListener implements Listener { return; } } -// switch (event.getChangedType()) { -// case AIR: -// case CAVE_AIR: -// case VOID_AIR: -// break; -// case REDSTONE_WIRE:: -// return; -// } Exception e = new Exception(); int depth = getDepth(e); if (depth >= 256) { @@ -354,9 +349,7 @@ public abstract class ChunkListener implements Listener { } /** - * Prevent FireWorks from loading chunks - * - * @param event + * Prevent firework from loading chunks. */ @EventHandler(priority = EventPriority.LOWEST) public void onChunkLoad(ChunkLoadEvent event) { diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener_9.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener9.java similarity index 96% rename from worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener_9.java rename to worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener9.java index 2c582b7d2..adaa01cd6 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener_9.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener9.java @@ -9,12 +9,12 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockPhysicsEvent; -public class ChunkListener_9 extends ChunkListener { +public class ChunkListener9 extends ChunkListener { private Exception exception; private StackTraceElement[] elements; - public ChunkListener_9() { + public ChunkListener9() { super(); } @@ -64,7 +64,6 @@ public class ChunkListener_9 extends ChunkListener { cancelNearby(cx, cz); event.setCancelled(true); physCancel = true; - return; } } } @@ -87,4 +86,4 @@ public class ChunkListener_9 extends ChunkListener { StackTraceElement[] elems = getElements(ex); return elems.length > i ? elems[i] : null; } -} \ No newline at end of file +} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener_8Plus.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener_8Plus.java deleted file mode 100644 index 35e37e5a5..000000000 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/ChunkListener_8Plus.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.boydti.fawe.bukkit.listener; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockExplodeEvent; - -public class ChunkListener_8Plus implements Listener{ - private final ChunkListener listener; - - public ChunkListener_8Plus(ChunkListener listener) { - this.listener = listener; - } - @EventHandler(priority = EventPriority.LOWEST) - public void event(BlockExplodeEvent event) { - listener.reset(); - } -} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/RenderListener.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/RenderListener.java index e89b90745..a50593081 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/RenderListener.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/listener/RenderListener.java @@ -3,10 +3,6 @@ package com.boydti.fawe.bukkit.listener; import com.boydti.fawe.Fawe; import com.boydti.fawe.config.Settings; import com.boydti.fawe.util.TaskManager; -import java.util.Iterator; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; @@ -19,6 +15,11 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.plugin.Plugin; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + public class RenderListener implements Listener { private final Map views = new ConcurrentHashMap<>(); @@ -32,7 +33,9 @@ public class RenderListener implements Listener { @Override public void run() { - if (views.isEmpty()) return; + if (views.isEmpty()) { + return; + } long now = System.currentTimeMillis(); int tps32 = (int) (Math.round(Fawe.get().getTimer().getTPS()) * 32); @@ -64,8 +67,9 @@ public class RenderListener implements Listener { setViewDistance(player, Math.max(4, value[0] + 1)); long spent = System.currentTimeMillis() - now; if (spent > 5) { - if (spent > 10) + if (spent > 10) { value[1] = nowTick + 20; + } return; } } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/preloader/PluginPreloader.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/preloader/PluginPreloader.java index dcc98dc26..05fbb2f5f 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/preloader/PluginPreloader.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/preloader/PluginPreloader.java @@ -77,7 +77,9 @@ public class PluginPreloader extends PluginBase { loaded = region.getChunks(); Iterator iter = loaded.iterator(); - if (!invalidator.get()) return; + if (!invalidator.get()) { + return; + } Fawe.get().getQueueHandler().syncWhenFree(() -> { for (; iter.hasNext() && invalidator.get();index++) { BlockVector2 chunk = iter.next(); @@ -95,22 +97,26 @@ public class PluginPreloader extends PluginBase { } @Override - public @NotNull File getDataFolder() { + @NotNull + public File getDataFolder() { return null; } @Override - public @NotNull PluginDescriptionFile getDescription() { + @NotNull + public PluginDescriptionFile getDescription() { return null; } @Override - public @NotNull FileConfiguration getConfig() { + @NotNull + public FileConfiguration getConfig() { return null; } @Override - public @Nullable InputStream getResource(@NotNull String filename) { + @Nullable + public InputStream getResource(@NotNull String filename) { return null; } @@ -135,12 +141,14 @@ public class PluginPreloader extends PluginBase { } @Override - public @NotNull PluginLoader getPluginLoader() { + @NotNull + public PluginLoader getPluginLoader() { return null; } @Override - public @NotNull Server getServer() { + @NotNull + public Server getServer() { return null; } @@ -175,12 +183,14 @@ public class PluginPreloader extends PluginBase { } @Override - public @Nullable ChunkGenerator getDefaultWorldGenerator(@NotNull String worldName, @Nullable String id) { + @Nullable + public ChunkGenerator getDefaultWorldGenerator(@NotNull String worldName, @Nullable String id) { return null; } @Override - public @NotNull Logger getLogger() { + @NotNull + public Logger getLogger() { return null; } @@ -190,7 +200,8 @@ public class PluginPreloader extends PluginBase { } @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { + @Nullable + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { return null; } } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/FreeBuildRegion.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/FreeBuildRegion.java index aeb6ffb9f..134c8c270 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/FreeBuildRegion.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/FreeBuildRegion.java @@ -9,7 +9,6 @@ import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; -import java.util.ArrayList; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.event.EventException; @@ -17,6 +16,9 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.plugin.RegisteredListener; +import java.util.ArrayList; +import java.util.Locale; + public class FreeBuildRegion extends BukkitMaskManager { private final ArrayList listeners; @@ -25,8 +27,12 @@ public class FreeBuildRegion extends BukkitMaskManager { this.listeners = new ArrayList<>(); RegisteredListener[] listeners = BlockBreakEvent.getHandlerList().getRegisteredListeners(); for (RegisteredListener listener : listeners) { - if (listener.getPriority() == EventPriority.MONITOR) continue; - if (!listener.isIgnoringCancelled()) continue; + if (listener.getPriority() == EventPriority.MONITOR) { + continue; + } + if (!listener.isIgnoringCancelled()) { + continue; + } this.listeners.add(listener); } } @@ -38,14 +44,20 @@ public class FreeBuildRegion extends BukkitMaskManager { @Override public FaweMask getMask(Player player, MaskType type) { - if (type != MaskType.MEMBER) return null; + if (type != MaskType.MEMBER) { + return null; + } ArrayList currRegList = new ArrayList<>(); for (RegisteredListener listener : this.listeners) { String name = listener.getPlugin().getName(); - if (!player.hasPermission("fawe.freebuild." + name.toLowerCase())) continue; + if (!player.hasPermission("fawe.freebuild." + name.toLowerCase(Locale.ROOT))) { + continue; + } currRegList.add(listener); } - if (currRegList.isEmpty()) return null; + if (currRegList.isEmpty()) { + return null; + } RegisteredListener[] listeners = currRegList.toArray(new RegisteredListener[0]); World bukkitWorld = BukkitAdapter.adapt(player.getWorld()); @@ -73,12 +85,15 @@ public class FreeBuildRegion extends BukkitMaskManager { return contains(x, 127, z); } - private int lastX = Integer.MIN_VALUE, lastZ = Integer.MIN_VALUE; + private int lastX = Integer.MIN_VALUE; + private int lastZ = Integer.MIN_VALUE; private boolean lastResult; @Override public boolean contains(int x, int y, int z) { - if (x == lastX && z == lastZ) return lastResult; + if (x == lastX && z == lastZ) { + return lastResult; + } lastX = x; lastZ = z; event.setCancelled(false); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/ResidenceFeature.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/ResidenceFeature.java index c20f7ca43..eb89edfdd 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/ResidenceFeature.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/ResidenceFeature.java @@ -43,7 +43,7 @@ public class ResidenceFeature extends BukkitMaskManager implements Listener { final Location pos2 = area.getHighLoc(); final ClaimedResidence finalResidence = residence; return new FaweMask(new CuboidRegion(BukkitAdapter.asBlockVector(pos1), BukkitAdapter.asBlockVector(pos2))) { - @Override + @Override public boolean isValid(com.sk89q.worldedit.entity.Player player, MaskType type) { return isAllowed(BukkitAdapter.adapt(player), finalResidence, type); } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/TownyFeature.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/TownyFeature.java index 3cb636bee..554be7c7e 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/TownyFeature.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/TownyFeature.java @@ -38,7 +38,8 @@ public class TownyFeature extends BukkitMaskManager implements Listener { if (block.getResident().equals(resident)) { return true; } - } catch (NotRegisteredException ignore) {} + } catch (NotRegisteredException ignored) { + } Town town = block.getTown(); if (town.isMayor(resident)) { return true; @@ -54,7 +55,8 @@ public class TownyFeature extends BukkitMaskManager implements Listener { return true; } } - } catch (NotRegisteredException ignore) {} + } catch (NotRegisteredException ignored) { + } return false; } @@ -87,7 +89,8 @@ public class TownyFeature extends BukkitMaskManager implements Listener { } }; } - } catch (Exception ignored) {} + } catch (Exception ignored) { + } return null; } } 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 ba25404bc..27425aa9d 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 @@ -27,6 +27,8 @@ import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; +import java.util.Locale; + public class Worldguard extends BukkitMaskManager implements Listener { private final WorldGuardPlugin worldguard; @@ -63,7 +65,7 @@ public class Worldguard extends BukkitMaskManager implements Listener { } final ApplicableRegionSet regions = manager.getApplicableRegions(BlockVector3.at(location.getX(), location.getY(), location.getZ())); //Merge WorldGuardFlag - if(player.hasPermission("fawe.worldguardflag") && !regions.testState(player, Flags.BUILD, Flags.BLOCK_PLACE, Flags.BLOCK_BREAK)){ + if (player.hasPermission("fawe.worldguardflag") && !regions.testState(player, Flags.BUILD, Flags.BLOCK_PLACE, Flags.BLOCK_BREAK)) { return null; } for (ProtectedRegion region : regions) { @@ -78,9 +80,9 @@ public class Worldguard extends BukkitMaskManager implements Listener { //Check if player is the owner of the region, the region's ID contains the player's name (why?), or if the region's owners contains "*". if (region.isOwner(localplayer) || region.isOwner(localplayer.getName())) { return true; - } else if (region.getId().toLowerCase().equals(localplayer.getName().toLowerCase())) { + } else if (region.getId().toLowerCase(Locale.ROOT).equals(localplayer.getName().toLowerCase(Locale.ROOT))) { return true; - } else if (region.getId().toLowerCase().contains(localplayer.getName().toLowerCase() + "//")) { + } else if (region.getId().toLowerCase(Locale.ROOT).contains(localplayer.getName().toLowerCase(Locale.ROOT) + "//")) { return true; } else if (region.isOwner("*")) { return true; @@ -90,8 +92,9 @@ public class Worldguard extends BukkitMaskManager implements Listener { if (localplayer.hasPermission("fawe.worldguard.member")) { if (region.isMember(localplayer) || region.isMember(localplayer.getName())) { return true; - } else + } else { return region.isMember("*"); + } } return false; } @@ -122,8 +125,7 @@ public class Worldguard extends BukkitMaskManager implements Listener { } } return new FaweMask(new CuboidRegion(pos1, pos2)) { - - @Override + @Override public boolean isValid(com.sk89q.worldedit.entity.Player player, MaskType type) { return isAllowed(worldguard.wrapPlayer(BukkitAdapter.adapt(player)), myregion); } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/FaweRegionManager.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/FaweRegionManager.java index d8f922ef0..f3aa053a9 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/FaweRegionManager.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/FaweRegionManager.java @@ -136,8 +136,8 @@ public class FaweRegionManager extends RegionManager { clipboard.setBlocks(fillingRegion, filling); clipboard.setBlocks(floorRegion, plotfloor); clipboard.setBlocks(airRegion, air); - for (int x = pos1.getX(); x <= pos2.getX(); x ++) { - for (int z = pos1.getZ(); z <= pos2.getZ(); z ++) { + for (int x = pos1.getX(); x <= pos2.getX(); x++) { + for (int z = pos1.getZ(); z <= pos2.getZ(); z++) { clipboard.setBiome(BlockVector2.at(x, z), biome); } } @@ -178,7 +178,7 @@ public class FaweRegionManager extends RegionManager { //todo because of the following code this should proably be in the Bukkit module World pos1World = BukkitAdapter.adapt(getWorld(pos1.getWorld())); World pos3World = BukkitAdapter.adapt(getWorld(pos3.getWorld())); - WorldEdit.getInstance().getEditSessionFactory().getEditSession(pos1World,-1); + WorldEdit.getInstance().getEditSessionFactory().getEditSession(pos1World, -1); EditSession sessionA = new EditSessionBuilder(pos1World).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); EditSession sessionB = new EditSessionBuilder(pos3World).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())); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/FaweSchematicHandler.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/FaweSchematicHandler.java index f8f1fe2c2..5704bb9e9 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/FaweSchematicHandler.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/FaweSchematicHandler.java @@ -1,7 +1,5 @@ package com.boydti.fawe.bukkit.regions.plotsquared; -import static org.bukkit.Bukkit.getWorld; - import com.boydti.fawe.FaweAPI; import com.boydti.fawe.FaweCache; import com.boydti.fawe.object.clipboard.ReadOnlyClipboard; @@ -29,6 +27,8 @@ import com.sk89q.worldedit.extent.clipboard.io.FastSchematicWriter; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; +import net.jpountz.lz4.LZ4BlockInputStream; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; @@ -39,7 +39,8 @@ import java.net.URL; import java.util.Map; import java.util.Set; import java.util.UUID; -import net.jpountz.lz4.LZ4BlockInputStream; + +import static org.bukkit.Bukkit.getWorld; public class FaweSchematicHandler extends SchematicHandler { @Override diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/MoveTo512.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/MoveTo512.java index b3ab082e0..437e0c58a 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/MoveTo512.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/MoveTo512.java @@ -62,7 +62,7 @@ public class MoveTo512 /*extends Command*/ { // if (yMax != 15) { // Arrays.fill(ids, yMax158 + 256, 4096, (byte) 0); // } -// } else if (layer == 0){ +// } else if (layer == 0) { // Arrays.fill(ids, 256, 4096, (byte) 3); // Arrays.fill(ids, 0, 256, (byte) 7); // } else { @@ -113,7 +113,7 @@ public class MoveTo512 /*extends Command*/ { // int yMax158 = yMax15 << 8; // Arrays.fill(ids, yMax158 + 256, 4096, (byte) 0); // } -// } else if (layer == 0){ +// } else if (layer == 0) { // Arrays.fill(ids, 256, 4096, (byte) hpw.ROAD_BLOCK.id); // Arrays.fill(ids, 0, 256, (byte) 7); // } else { diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotRegionFilter.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotRegionFilter.java index d0cfdf790..4c6be8306 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotRegionFilter.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotRegionFilter.java @@ -1,14 +1,15 @@ package com.boydti.fawe.bukkit.regions.plotsquared; -import static com.google.common.base.Preconditions.checkNotNull; - import com.boydti.fawe.regions.general.CuboidRegionFilter; import com.plotsquared.core.location.Location; import com.plotsquared.core.plot.Plot; import com.plotsquared.core.plot.PlotArea; import com.sk89q.worldedit.math.BlockVector2; + import java.util.ArrayList; +import static com.google.common.base.Preconditions.checkNotNull; + public class PlotRegionFilter extends CuboidRegionFilter { private final PlotArea area; @@ -16,6 +17,7 @@ public class PlotRegionFilter extends CuboidRegionFilter { checkNotNull(area); this.area = area; } + @Override public void calculateRegions() { ArrayList plots = new ArrayList<>(area.getPlots()); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotSetBiome.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotSetBiome.java index 30ed06ff2..0e5c93da7 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotSetBiome.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotSetBiome.java @@ -24,11 +24,12 @@ import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeTypes; import com.sk89q.worldedit.world.biome.Biomes; import com.sk89q.worldedit.world.registry.BiomeRegistry; +import org.bukkit.Bukkit; + import java.util.Collection; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadLocalRandom; -import org.bukkit.Bukkit; @CommandDeclaration( command = "generatebiome", diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotSquaredFeature.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotSquaredFeature.java index 36f4944a5..5b28a0c4a 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotSquaredFeature.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquared/PlotSquaredFeature.java @@ -23,13 +23,15 @@ import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionIntersection; import com.sk89q.worldedit.world.World; - -import java.util.ArrayList; -import java.util.Set; -import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + public class PlotSquaredFeature extends FaweMaskManager { private static final Logger log = LoggerFactory.getLogger(PlotSquaredFeature.class); @@ -46,15 +48,15 @@ public class PlotSquaredFeature extends FaweMaskManager { } catch (Throwable ignored) { log.debug("Please update PlotSquared: https://www.spigotmc.org/resources/plotsquared-v5.77506/"); } - if (Settings.PLATFORM.toLowerCase().startsWith("bukkit")) { + if (Settings.PLATFORM.toLowerCase(Locale.ROOT).startsWith("bukkit")) { new FaweTrim(); } if (MainCommand.getInstance().getCommand("generatebiome") == null) { new PlotSetBiome(); - } + } } -// TODO: revisit this later on -/* + // TODO: revisit this later on + /* try { if (Settings.Enabled_Components.WORLDS) { new ReplaceAll(); @@ -62,7 +64,7 @@ public class PlotSquaredFeature extends FaweMaskManager { } catch (Throwable e) { log.debug("You need to update PlotSquared to access the CFI and REPLACEALL commands"); } -*/ + */ } public static String getName(UUID uuid) { @@ -93,12 +95,9 @@ public class PlotSquaredFeature extends FaweMaskManager { return false; } UUID uid = player.getUniqueId(); - return !plot.getFlag(NoWorldeditFlag.class) && (plot.isOwner(uid) - || type == MaskType.MEMBER && (plot.getTrusted().contains(uid) || plot.getTrusted() - .contains(DBFunc.EVERYONE) - || (plot.getMembers().contains(uid) || plot.getMembers().contains(DBFunc.EVERYONE)) - && player.hasPermission("fawe.plotsquared.member")) || player - .hasPermission("fawe.plotsquared.admin")); + return !plot.getFlag(NoWorldeditFlag.class) && (plot.isOwner(uid) || type == MaskType.MEMBER && (plot.getTrusted().contains(uid) || plot + .getTrusted().contains(DBFunc.EVERYONE) || (plot.getMembers().contains(uid) || plot.getMembers().contains(DBFunc.EVERYONE)) && player + .hasPermission("fawe.plotsquared.member")) || player.hasPermission("fawe.plotsquared.admin")); } @Override @@ -111,7 +110,7 @@ public class PlotSquaredFeature extends FaweMaskManager { Plot plot = pp.getCurrentPlot(); if (isAllowed(player, plot, type)) { regions = plot.getRegions(); - } else { + } else { plot = null; regions = WEManager.getMask(pp); if (regions.size() == 1) { @@ -141,7 +140,10 @@ public class PlotSquaredFeature extends FaweMaskManager { maskedRegion = new CuboidRegion(pos1, pos2); } else { World world = FaweAPI.getWorld(area.getWorldName()); - maskedRegion = new RegionIntersection(world, new ArrayList<>(regions)); + List weRegions = regions.stream().map( + r -> new CuboidRegion(world, BlockVector3.at(r.getMinimumX(), r.getMinimumY(), r.getMinimumZ()), + BlockVector3.at(r.getMaximumX(), r.getMaximumY(), r.getMaximumZ()))).collect(Collectors.toList()); + maskedRegion = new RegionIntersection(world, weRegions); } return new FaweMask(maskedRegion) { @@ -158,7 +160,9 @@ public class PlotSquaredFeature extends FaweMaskManager { @Override public RegionFilter getFilter(String world) { PlotArea area = PlotSquared.get().getPlotArea(world, null); - if (area != null) return new PlotRegionFilter(area); + if (area != null) { + return new PlotRegionFilter(area); + } return null; } } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/FaweChunkManager.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/FaweChunkManager.java index 2d3e9b613..999a2224f 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/FaweChunkManager.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/FaweChunkManager.java @@ -1,7 +1,5 @@ package com.boydti.fawe.bukkit.regions.plotsquaredv4; -import static org.bukkit.Bukkit.getWorld; - import com.boydti.fawe.config.Settings; import com.boydti.fawe.util.EditSessionBuilder; import com.boydti.fawe.util.TaskManager; @@ -18,8 +16,11 @@ import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; + import java.util.concurrent.CompletableFuture; +import static org.bukkit.Bukkit.getWorld; + public class FaweChunkManager extends ChunkManager { private ChunkManager parent; diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/FaweSchematicHandler.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/FaweSchematicHandler.java index 40d0668f1..c0539e682 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/FaweSchematicHandler.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/FaweSchematicHandler.java @@ -1,7 +1,5 @@ package com.boydti.fawe.bukkit.regions.plotsquaredv4; -import static org.bukkit.Bukkit.getWorld; - import com.boydti.fawe.FaweAPI; import com.boydti.fawe.FaweCache; import com.boydti.fawe.object.clipboard.ReadOnlyClipboard; @@ -29,6 +27,8 @@ import com.sk89q.worldedit.extent.clipboard.io.FastSchematicWriter; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; +import net.jpountz.lz4.LZ4BlockInputStream; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; @@ -39,7 +39,8 @@ import java.net.URL; import java.util.Map; import java.util.Set; import java.util.UUID; -import net.jpountz.lz4.LZ4BlockInputStream; + +import static org.bukkit.Bukkit.getWorld; public class FaweSchematicHandler extends SchematicHandler { @Override diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/PlotRegionFilter.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/PlotRegionFilter.java index bf1408415..91ca83c74 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/PlotRegionFilter.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/PlotRegionFilter.java @@ -1,14 +1,15 @@ package com.boydti.fawe.bukkit.regions.plotsquaredv4; -import static com.google.common.base.Preconditions.checkNotNull; - import com.boydti.fawe.regions.general.CuboidRegionFilter; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; import com.sk89q.worldedit.math.BlockVector2; + import java.util.ArrayList; +import static com.google.common.base.Preconditions.checkNotNull; + public class PlotRegionFilter extends CuboidRegionFilter { private final PlotArea area; @@ -16,6 +17,7 @@ public class PlotRegionFilter extends CuboidRegionFilter { checkNotNull(area); this.area = area; } + @Override public void calculateRegions() { ArrayList plots = new ArrayList<>(area.getPlots()); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/PlotSquaredFeature.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/PlotSquaredFeature.java index 059fe87c8..e7b105bb1 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/PlotSquaredFeature.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/plotsquaredv4/PlotSquaredFeature.java @@ -10,7 +10,6 @@ import com.github.intellectualsites.plotsquared.plot.commands.MainCommand; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.flag.Flags; -import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotManager; import com.github.intellectualsites.plotsquared.plot.listener.WEManager; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; @@ -18,21 +17,21 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; -import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; -import com.github.intellectualsites.plotsquared.plot.util.block.QueueProvider; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionIntersection; import com.sk89q.worldedit.world.World; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.HashSet; import java.util.List; +import java.util.Locale; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class PlotSquaredFeature extends FaweMaskManager { @@ -48,17 +47,17 @@ public class PlotSquaredFeature extends FaweMaskManager { setupSchematicHandler(); setupChunkManager(); } catch (Throwable ignored) { - log.debug("Please update PlotSquared: http://ci.athion.net/job/PlotSquared/"); + log.debug("Please update PlotSquared: https://www.spigotmc.org/resources/77506/"); } - if (Settings.PLATFORM.toLowerCase().startsWith("bukkit")) { + if (Settings.PLATFORM.toLowerCase(Locale.ROOT).startsWith("bukkit")) { new FaweTrim(); } if (MainCommand.getInstance().getCommand("generatebiome") == null) { new PlotSetBiome(); - } + } } -// TODO: revisit this later on -/* + // TODO: revisit this later on + /* try { if (Settings.Enabled_Components.WORLDS) { new ReplaceAll(); @@ -66,7 +65,7 @@ public class PlotSquaredFeature extends FaweMaskManager { } catch (Throwable e) { log.debug("You need to update PlotSquared to access the CFI and REPLACEALL commands"); } -*/ + */ } public static String getName(UUID uuid) { @@ -115,7 +114,7 @@ public class PlotSquaredFeature extends FaweMaskManager { Plot plot = pp.getCurrentPlot(); if (isAllowed(player, plot, type)) { regions = plot.getRegions(); - } else { + } else { plot = null; regions = WEManager.getMask(pp); if (regions.size() == 1) { @@ -149,8 +148,8 @@ public class PlotSquaredFeature extends FaweMaskManager { } else { World world = FaweAPI.getWorld(area.worldname); List weRegions = regions.stream() - .map(r -> new CuboidRegion(world, BlockVector3.at(r.getMinimumX(), r.getMinimumY(), r.getMinimumZ()), BlockVector3.at(r.getMaximumX(), r.getMaximumY(), r.getMaximumZ()))) - .collect(Collectors.toList()); + .map(r -> new CuboidRegion(world, BlockVector3.at(r.getMinimumX(), r.getMinimumY(), r.getMinimumZ()), BlockVector3.at(r.getMaximumX(), r.getMaximumY(), r.getMaximumZ()))) + .collect(Collectors.toList()); maskedRegion = new RegionIntersection(world, weRegions); } @@ -168,7 +167,9 @@ public class PlotSquaredFeature extends FaweMaskManager { @Override public RegionFilter getFilter(String world) { PlotArea area = PlotSquared.get().getPlotArea(world, null); - if (area != null) return new PlotRegionFilter(area); + if (area != null) { + return new PlotRegionFilter(area); + } return null; } } 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 e3f890537..e79d06ec4 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 @@ -45,7 +45,9 @@ public class ItemUtil { public Object getNMSItem(ItemStack item) { try { Object nmsItem = fieldHandle.get(item); - if (nmsItem == null) nmsItem = methodAsNMSCopy.invoke(null, item); + if (nmsItem == null) { + nmsItem = methodAsNMSCopy.invoke(null, item); + } return nmsItem; } catch (Throwable e) { e.printStackTrace(); @@ -57,12 +59,18 @@ public class ItemUtil { public CompoundTag getNBT(ItemStack item) { try { - if (!item.hasItemMeta()) return null; + if (!item.hasItemMeta()) { + return null; + } Object nmsItem = fieldHandle.get(item); - if (nmsItem == null) nmsItem = methodAsNMSCopy.invoke(null, item); + if (nmsItem == null) { + nmsItem = methodAsNMSCopy.invoke(null, item); + } if (methodHasTag.invoke(nmsItem).equals(true)) { Object nmsTag = methodGetTag.invoke(nmsItem); - if (nmsTag == null) return null; + if (nmsTag == null) { + return null; + } Int2ObjectOpenHashMap> map = hashToNMSTag.get(); if (map == null) { @@ -72,7 +80,9 @@ public class ItemUtil { WeakReference nativeTagRef = map.get(nmsTag.hashCode()); if (nativeTagRef != null) { Tag nativeTag = nativeTagRef.get(); - if (nativeTag != null) return (CompoundTag) nativeTag; + if (nativeTag != null) { + return (CompoundTag) nativeTag; + } } Tag nativeTag = adapter.toNative(nmsTag); map.put(nmsTag.hashCode(), new WeakReference<>(nativeTag)); @@ -94,7 +104,9 @@ public class ItemUtil { } Object nmsTag = adapter.fromNative(tag); methodSetTag.invoke(nmsItem, nmsTag); - if (copy) return (ItemStack) methodAsBukkitCopy.invoke(null, nmsItem); + if (copy) { + return (ItemStack) methodAsBukkitCopy.invoke(null, nmsItem); + } return item; } catch (Throwable e) { e.printStackTrace(); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/image/BukkitImageViewer.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/image/BukkitImageViewer.java index d1bdf2731..d582e924f 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/image/BukkitImageViewer.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/image/BukkitImageViewer.java @@ -3,11 +3,6 @@ package com.boydti.fawe.bukkit.util.image; import com.boydti.fawe.util.image.Drawable; import com.boydti.fawe.util.image.ImageUtil; import com.boydti.fawe.util.image.ImageViewer; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.util.Collection; -import javax.annotation.Nullable; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -25,6 +20,12 @@ import org.inventivetalent.mapmanager.controller.MultiMapController; import org.inventivetalent.mapmanager.manager.MapManager; import org.inventivetalent.mapmanager.wrapper.MapWrapper; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.util.Collection; +import javax.annotation.Nullable; + public class BukkitImageViewer implements ImageViewer { private final MapManager mapManager; private final Player player; @@ -116,7 +117,9 @@ public class BukkitImageViewer implements ImageViewer { break; } } - if (!contains) return null; + if (!contains) { + return null; + } } } } @@ -133,11 +136,15 @@ public class BukkitImageViewer implements ImageViewer { } private void view(@Nullable BufferedImage image, @Nullable Drawable drawable) { - if (image == null && drawable == null) throw new IllegalArgumentException("An image or drawable must be provided. Both cannot be null"); + if (image == null && drawable == null) { + throw new IllegalArgumentException("An image or drawable must be provided. Both cannot be null"); + } boolean initializing = last == null; if (this.frames != null) { - if (image == null && drawable != null) image = drawable.draw(); + if (image == null && drawable != null) { + image = drawable.draw(); + } last = image; int width = frames.length; int height = frames[0].length; @@ -158,7 +165,9 @@ public class BukkitImageViewer implements ImageViewer { } else if (player.getInventory().getHeldItemSlot() != slot) { player.getInventory().setHeldItemSlot(slot); } - if (image == null && drawable != null) image = drawable.draw(); + if (image == null && drawable != null) { + image = drawable.draw(); + } last = image; BufferedImage scaled = ImageUtil.getScaledInstance(image, 128, 128, RenderingHints.VALUE_INTERPOLATION_BILINEAR, false); MapWrapper mapWrapper = mapManager.wrapImage(scaled); @@ -181,7 +190,9 @@ public class BukkitImageViewer implements ImageViewer { } public void refresh() { - if (last != null) view(last, null); + if (last != null) { + view(last, null); + } } @Override diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncBlock.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncBlock.java index a2c38dce8..1f5c73c05 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncBlock.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncBlock.java @@ -107,13 +107,13 @@ public class AsyncBlock implements Block { } @Deprecated - public boolean setCombinedId(int combinedId) { - return world.setBlock(x, y, z, BlockState.getFromInternalId(combinedId)); + public boolean setTypeIdAndPropertyId(int id, int propertyId) { + return setCombinedId(id + (propertyId << BlockTypesCache.BIT_OFFSET)); } @Deprecated - public boolean setTypeIdAndPropertyId(int id, int propertyId) { - return setCombinedId(id + (propertyId << BlockTypesCache.BIT_OFFSET)); + public boolean setCombinedId(int combinedId) { + return world.setBlock(x, y, z, BlockState.getFromInternalId(combinedId)); } @Deprecated @@ -361,6 +361,10 @@ public class AsyncBlock implements Block { return TaskManager.IMP.sync(() -> getUnsafeBlock().getDrops(tool)); } + public Collection getDrops(ItemStack tool, Entity entity) { + return Collections.emptyList(); //todo + } + @Override public void setMetadata(@NotNull String metadataKey, @NotNull MetadataValue newMetadataValue) { this.getUnsafeBlock().setMetadata(metadataKey, newMetadataValue); @@ -409,12 +413,9 @@ public class AsyncBlock implements Block { } @Override - public @NotNull BlockSoundGroup getSoundGroup() { + @NotNull + public BlockSoundGroup getSoundGroup() { return TaskManager.IMP.sync(() -> getUnsafeBlock().getSoundGroup()); } - public Collection getDrops(ItemStack tool, Entity entity) { - return Collections.emptyList(); //todo - } - } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncChunk.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncChunk.java index d2e3cb30b..e934d45ea 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncChunk.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncChunk.java @@ -106,7 +106,8 @@ public class AsyncChunk implements Chunk { } @Override - public @NotNull BlockState[] getTileEntities(boolean useSnapshot) { + @NotNull + public BlockState[] getTileEntities(boolean useSnapshot) { if (!isLoaded()) { return new BlockState[0]; } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncWorld.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncWorld.java index f6886b500..8b230cb44 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncWorld.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/AsyncWorld.java @@ -5,6 +5,7 @@ import com.boydti.fawe.object.RunnableVal; import com.boydti.fawe.util.StringMan; import com.boydti.fawe.util.TaskManager; import com.destroystokyo.paper.HeightmapType; +import com.google.common.annotations.Beta; import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; @@ -13,6 +14,7 @@ import com.sk89q.worldedit.extent.PassthroughExtent; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.block.BlockState; +import io.papermc.paper.world.MoonPhase; import org.bukkit.BlockChangeDelegate; import org.bukkit.Bukkit; import org.bukkit.Chunk; @@ -60,7 +62,6 @@ import org.bukkit.util.RayTraceResult; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import io.papermc.paper.world.MoonPhase; import java.io.File; import java.util.Collection; @@ -81,6 +82,7 @@ import java.util.function.Predicate; * @see #wrap(World) * @see #create(WorldCreator) */ +@SuppressWarnings("deprecation") public class AsyncWorld extends PassthroughExtent implements World { private World parent; @@ -93,9 +95,7 @@ public class AsyncWorld extends PassthroughExtent implements World { } /** - * @param parent Parent world - * @param autoQueue - * @deprecated use {@link #wrap(World)} instead + * An internal constructor for using a world asynchronously in FAWE. Do not use! */ @Deprecated public AsyncWorld(World parent, boolean autoQueue) { @@ -107,9 +107,7 @@ public class AsyncWorld extends PassthroughExtent implements World { } /** - * @param parent - * @param extent - * @deprecated use {@link #wrap(World)} instead + * An internal constructor for using a world asynchronously in FAWE. Do not use! */ @Deprecated public AsyncWorld(World parent, Extent extent) { @@ -120,9 +118,6 @@ public class AsyncWorld extends PassthroughExtent implements World { /** * Wrap a world for async usage. - * - * @param world - * @return */ public static AsyncWorld wrap(World world) { if (world instanceof AsyncWorld) { @@ -141,13 +136,11 @@ public class AsyncWorld extends PassthroughExtent implements World { } /** - * Create a world async (untested) - * - Only optimized for 1.10 - * - * @param creator - * @return + * Create a world async. This is not tested and may be removed in the future due to + * synchronization problems. */ - public synchronized static AsyncWorld create(final WorldCreator creator) { + @Beta + public static synchronized AsyncWorld create(final WorldCreator creator) { BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); @Nullable World world = adapter.createWorld(creator); return wrap(world); @@ -164,7 +157,8 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull WorldBorder getWorldBorder() { + @NotNull + public WorldBorder getWorldBorder() { return TaskManager.IMP.sync(() -> parent.getWorldBorder()); } @@ -238,12 +232,14 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull AsyncBlock getBlockAt(final int x, final int y, final int z) { + @NotNull + public AsyncBlock getBlockAt(final int x, final int y, final int z) { return new AsyncBlock(this, x, y, z); } @Override - public @NotNull AsyncBlock getBlockAt(Location loc) { + @NotNull + public AsyncBlock getBlockAt(Location loc) { return getBlockAt(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); } @@ -264,13 +260,15 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull AsyncBlock getHighestBlockAt(int x, int z) { + @NotNull + public AsyncBlock getHighestBlockAt(int x, int z) { int y = getHighestBlockYAt(x, z); return getBlockAt(x, y, z); } @Override - public @NotNull AsyncBlock getHighestBlockAt(Location loc) { + @NotNull + public AsyncBlock getHighestBlockAt(Location loc) { return getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()); } @@ -285,28 +283,33 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull Block getHighestBlockAt(int i, int i1, @NotNull HeightMap heightMap) { + @NotNull + public Block getHighestBlockAt(int i, int i1, @NotNull HeightMap heightMap) { return parent.getHighestBlockAt(i, i1, heightMap); } @Override - public @NotNull Block getHighestBlockAt(@NotNull Location location, - @NotNull HeightMap heightMap) { + @NotNull + public Block getHighestBlockAt(@NotNull Location location, + @NotNull HeightMap heightMap) { return parent.getHighestBlockAt(location, heightMap); } @Override - public @NotNull AsyncChunk getChunkAt(int x, int z) { + @NotNull + public AsyncChunk getChunkAt(int x, int z) { return new AsyncChunk(this, x, z); } @Override - public @NotNull AsyncChunk getChunkAt(Location location) { + @NotNull + public AsyncChunk getChunkAt(Location location) { return getChunkAt(location.getBlockX(), location.getBlockZ()); } @Override - public @NotNull AsyncChunk getChunkAt(Block block) { + @NotNull + public AsyncChunk getChunkAt(Block block) { return getChunkAt(block.getX(), block.getZ()); } @@ -320,6 +323,7 @@ public class AsyncWorld extends PassthroughExtent implements World { return chunk.isLoaded(); } + @NotNull @Override public Chunk[] getLoadedChunks() { return parent.getLoadedChunks(); @@ -357,6 +361,7 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override + @Deprecated public boolean isChunkInUse(int x, int z) { return parent.isChunkInUse(x, z); } @@ -411,6 +416,7 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override + @Deprecated public boolean regenerateChunk(final int x, final int z) { return TaskManager.IMP.sync(() -> parent.regenerateChunk(x, z)); } @@ -422,104 +428,148 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull Item dropItem(final @NotNull Location location, final @NotNull ItemStack item) { + @NotNull + public Item dropItem( + @NotNull + final Location location, @NotNull + final ItemStack item) { return TaskManager.IMP.sync(() -> parent.dropItem(location, item)); } @Override - public @NotNull Item dropItemNaturally(final @NotNull Location location, - final @NotNull ItemStack item) { + @NotNull + public Item dropItemNaturally( + @NotNull + final Location location, + @NotNull + final ItemStack item) { return TaskManager.IMP.sync(() -> parent.dropItemNaturally(location, item)); } @Override - public @NotNull Arrow spawnArrow(final @NotNull Location location, - final @NotNull Vector direction, final float speed, final float spread) { + @NotNull + public Arrow spawnArrow( + @NotNull + final Location location, + @NotNull + final Vector direction, final float speed, final float spread) { return TaskManager.IMP.sync(() -> parent.spawnArrow(location, direction, speed, spread)); } + @NotNull @Override - public @NotNull T spawnArrow(@NotNull Location location, + public T spawnArrow(@NotNull Location location, @NotNull Vector direction, float speed, float spread, @NotNull Class clazz) { return parent.spawnArrow(location, direction, speed, spread, clazz); } @Override - public boolean generateTree(final @NotNull Location location, final @NotNull TreeType type) { + public boolean generateTree( + @NotNull + final Location location, @NotNull + final TreeType type) { return TaskManager.IMP.sync(() -> parent.generateTree(location, type)); } @Override - public boolean generateTree(final @NotNull Location loc, final @NotNull TreeType type, - final @NotNull BlockChangeDelegate delegate) { + public boolean generateTree( + @NotNull + final Location loc, @NotNull + final TreeType type, + @NotNull + final BlockChangeDelegate delegate) { return TaskManager.IMP.sync(() -> parent.generateTree(loc, type, delegate)); } @Override - public @NotNull Entity spawnEntity(@NotNull Location loc, EntityType type) { + @NotNull + public Entity spawnEntity(@NotNull Location loc, EntityType type) { return spawn(loc, type.getEntityClass()); } @Override - public @NotNull LightningStrike strikeLightning(final @NotNull Location loc) { + @NotNull + public LightningStrike strikeLightning( + @NotNull + final Location loc) { return TaskManager.IMP.sync(() -> parent.strikeLightning(loc)); } @Override - public @NotNull LightningStrike strikeLightningEffect(final @NotNull Location loc) { + @NotNull + public LightningStrike strikeLightningEffect( + @NotNull + final Location loc) { return TaskManager.IMP.sync(() -> parent.strikeLightningEffect(loc)); } @Override - public @NotNull List getEntities() { + @NotNull + public List getEntities() { return TaskManager.IMP.sync(() -> parent.getEntities()); } @Override - public @NotNull List getLivingEntities() { + @NotNull + public List getLivingEntities() { return TaskManager.IMP.sync(() -> parent.getLivingEntities()); } + @NotNull @Override @Deprecated - public @NotNull Collection getEntitiesByClass(final Class... classes) { + public Collection getEntitiesByClass( + @NotNull + final Class... classes) { return TaskManager.IMP.sync(() -> parent.getEntitiesByClass(classes)); } + @NotNull @Override - public @NotNull Collection getEntitiesByClass( - final @NotNull Class cls) { + public Collection getEntitiesByClass( + @NotNull + final Class cls) { return TaskManager.IMP.sync(() -> parent.getEntitiesByClass(cls)); } @Override - public @NotNull Collection getEntitiesByClasses(final Class... classes) { + @NotNull + public Collection getEntitiesByClasses( + @NotNull + final Class... classes) { return TaskManager.IMP.sync(() -> parent.getEntitiesByClasses(classes)); } @Override - public @NotNull List getPlayers() { + @NotNull + public List getPlayers() { return TaskManager.IMP.sync(() -> parent.getPlayers()); } @Override - public @NotNull Collection getNearbyEntities(final @NotNull Location location, + @NotNull + public Collection getNearbyEntities( + @NotNull + final Location location, final double x, final double y, final double z) { return TaskManager.IMP.sync(() -> parent.getNearbyEntities(location, x, y, z)); } @Override - public @NotNull String getName() { + @NotNull + public String getName() { return parent.getName(); } @Override - public @NotNull UUID getUID() { + @NotNull + public UUID getUID() { return parent.getUID(); } @Override - public @NotNull Location getSpawnLocation() { + @NotNull + public Location getSpawnLocation() { return parent.getSpawnLocation(); } @@ -534,7 +584,8 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull MoonPhase getMoonPhase() { + @NotNull + public MoonPhase getMoonPhase() { return parent.getMoonPhase(); } @@ -669,45 +720,52 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull List getPopulators() { + @NotNull + public List getPopulators() { return parent.getPopulators(); } + @NotNull @Override - public @NotNull T spawn(final @NotNull Location location, - final @NotNull Class clazz) throws IllegalArgumentException { + public T spawn(@NotNull final Location location, @NotNull final Class clazz) throws IllegalArgumentException { return TaskManager.IMP.sync(() -> parent.spawn(location, clazz)); } + @NotNull @Override - public @NotNull T spawn(@NotNull Location location, @NotNull Class clazz, + public T spawn(@NotNull Location location, @NotNull Class clazz, Consumer function) throws IllegalArgumentException { return TaskManager.IMP.sync(() -> parent.spawn(location, clazz, function)); } + @NotNull @Override - public @NotNull T spawn(@NotNull Location location, @NotNull Class clazz, - @Nullable Consumer function, CreatureSpawnEvent.@NotNull SpawnReason reason) + public T spawn(@NotNull Location location, @NotNull Class clazz, + @Nullable Consumer function, @NotNull + CreatureSpawnEvent.SpawnReason reason) throws IllegalArgumentException { - return null; + return TaskManager.IMP.sync(() -> parent.spawn(location, clazz, function, reason)); } @Override - public @NotNull FallingBlock spawnFallingBlock(@NotNull Location location, - @NotNull MaterialData data) throws IllegalArgumentException { + @NotNull + public FallingBlock spawnFallingBlock(@NotNull Location location, + @NotNull MaterialData data) throws IllegalArgumentException { return TaskManager.IMP.sync(() -> parent.spawnFallingBlock(location, data)); } @Override @Deprecated - public @NotNull FallingBlock spawnFallingBlock(@NotNull Location location, - @NotNull Material material, byte data) throws IllegalArgumentException { + @NotNull + public FallingBlock spawnFallingBlock(@NotNull Location location, + @NotNull Material material, byte data) throws IllegalArgumentException { return TaskManager.IMP.sync(() -> parent.spawnFallingBlock(location, material, data)); } @Override - public @NotNull FallingBlock spawnFallingBlock(@NotNull Location location, - @NotNull BlockData blockData) throws IllegalArgumentException { + @NotNull + public FallingBlock spawnFallingBlock(@NotNull Location location, + @NotNull BlockData blockData) throws IllegalArgumentException { return TaskManager.IMP.sync(() -> parent.spawnFallingBlock(location, blockData)); } @@ -717,7 +775,10 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public void playEffect(final @NotNull Location location, final @NotNull Effect effect, + public void playEffect( + @NotNull + final Location location, @NotNull + final Effect effect, final int data, final int radius) { TaskManager.IMP.sync(new RunnableVal() { @Override @@ -733,7 +794,10 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public void playEffect(final @NotNull Location location, final @NotNull Effect effect, + public void playEffect( + @NotNull + final Location location, @NotNull + final Effect effect, final T data, final int radius) { TaskManager.IMP.sync(new RunnableVal() { @Override @@ -744,8 +808,9 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull ChunkSnapshot getEmptyChunkSnapshot(final int x, final int z, - final boolean includeBiome, final boolean includeBiomeTempRain) { + @NotNull + public ChunkSnapshot getEmptyChunkSnapshot(final int x, final int z, + final boolean includeBiome, final boolean includeBiomeTempRain) { return TaskManager.IMP .sync(() -> parent.getEmptyChunkSnapshot(x, z, includeBiome, includeBiomeTempRain)); } @@ -766,12 +831,14 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull Biome getBiome(int x, int z) { + @NotNull + public Biome getBiome(int x, int z) { return adapter.adapt(getExtent().getBiomeType(x, 0, z)); } @Override - public @NotNull Biome getBiome(int x, int y, int z) { + @NotNull + public Biome getBiome(int x, int y, int z) { return adapter.adapt(getExtent().getBiomeType(x, y, z)); } @@ -788,6 +855,7 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override + @Deprecated public double getTemperature(int x, int z) { return parent.getTemperature(x, z); } @@ -798,6 +866,7 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override + @Deprecated public double getHumidity(int x, int z) { return parent.getHumidity(x, z); } @@ -848,16 +917,19 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull Difficulty getDifficulty() { + @NotNull + public Difficulty getDifficulty() { return parent.getDifficulty(); } @Override - public @NotNull File getWorldFolder() { + @NotNull + public File getWorldFolder() { return parent.getWorldFolder(); } @Override + @Deprecated public WorldType getWorldType() { return parent.getWorldType(); } @@ -948,7 +1020,10 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public void playSound(final @NotNull Location location, final @NotNull Sound sound, + public void playSound( + @NotNull + final Location location, @NotNull + final Sound sound, final float volume, final float pitch) { TaskManager.IMP.sync(new RunnableVal() { @Override @@ -959,7 +1034,10 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public void playSound(final @NotNull Location location, final @NotNull String sound, + public void playSound( + @NotNull + final Location location, @NotNull + final String sound, final float volume, final float pitch) { TaskManager.IMP.sync(new RunnableVal() { @Override @@ -991,17 +1069,20 @@ public class AsyncWorld extends PassthroughExtent implements World { }); } + @NotNull @Override public String[] getGameRules() { return parent.getGameRules(); } @Override + @Deprecated public String getGameRuleValue(String rule) { return parent.getGameRuleValue(rule); } @Override + @Deprecated public boolean setGameRuleValue(@NotNull String rule, @NotNull String value) { return parent.setGameRuleValue(rule, value); } @@ -1012,6 +1093,7 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override + @Deprecated public T getGameRuleValue(@NotNull GameRule gameRule) { return parent.getGameRuleValue(gameRule); } @@ -1027,22 +1109,28 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull Spigot spigot() { + @NotNull + public Spigot spigot() { return parent.spigot(); } @Override - public @Nullable Raid locateNearestRaid(@NotNull Location location, int i) { + @Nullable + public Raid locateNearestRaid(@NotNull Location location, int i) { return parent.locateNearestRaid(location, i); } @Override - public @NotNull List getRaids() { + @NotNull + public List getRaids() { return parent.getRaids(); } @Override - public void setMetadata(final @NotNull String key, final @NotNull MetadataValue meta) { + public void setMetadata( + @NotNull + final String key, @NotNull + final MetadataValue meta) { TaskManager.IMP.sync(new RunnableVal() { @Override public void run(Object value) { @@ -1052,7 +1140,8 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull List getMetadata(@NotNull String key) { + @NotNull + public List getMetadata(@NotNull String key) { return parent.getMetadata(key); } @@ -1062,7 +1151,10 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public void removeMetadata(final @NotNull String key, final @NotNull Plugin plugin) { + public void removeMetadata( + @NotNull + final String key, @NotNull + final Plugin plugin) { TaskManager.IMP.sync(new RunnableVal() { @Override public void run(Object value) { @@ -1072,12 +1164,14 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public void sendPluginMessage(@NotNull Plugin source, @NotNull String channel, byte[] message) { + public void sendPluginMessage(@NotNull Plugin source, @NotNull String channel, @NotNull + byte[] message) { parent.sendPluginMessage(source, channel, message); } @Override - public @NotNull Set getListeningPluginChannels() { + @NotNull + public Set getListeningPluginChannels() { return parent.getListeningPluginChannels(); } @@ -1086,19 +1180,22 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull Collection getNearbyEntities(@NotNull BoundingBox arg0) { + @NotNull + public Collection getNearbyEntities(@NotNull BoundingBox arg0) { return parent.getNearbyEntities(arg0); } @Override - public @NotNull Collection getNearbyEntities(@NotNull BoundingBox arg0, - Predicate arg1) { + @NotNull + public Collection getNearbyEntities(@NotNull BoundingBox arg0, + Predicate arg1) { return parent.getNearbyEntities(arg0, arg1); } @Override - public @NotNull Collection getNearbyEntities(@NotNull Location arg0, double arg1, - double arg2, double arg3, Predicate arg4) { + @NotNull + public Collection getNearbyEntities(@NotNull Location arg0, double arg1, + double arg2, double arg3, Predicate arg4) { return parent.getNearbyEntities(arg0, arg1, arg2, arg3, arg4); } @@ -1196,7 +1293,8 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull Collection getForceLoadedChunks() { + @NotNull + public Collection getForceLoadedChunks() { return parent.getForceLoadedChunks(); } @@ -1216,18 +1314,22 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull Collection getPluginChunkTickets(int x, int z) { + @NotNull + public Collection getPluginChunkTickets(int x, int z) { return getBukkitWorld().getPluginChunkTickets(x, z); } @Override - public @NotNull Map> getPluginChunkTickets() { + @NotNull + public Map> getPluginChunkTickets() { return getBukkitWorld().getPluginChunkTickets(); } @Override + @Deprecated public int getHighestBlockYAt(int x, int z, - com.destroystokyo.paper.@NotNull HeightmapType heightmap) + @NotNull + com.destroystokyo.paper.HeightmapType heightmap) throws UnsupportedOperationException { return TaskManager.IMP.sync(() -> parent.getHighestBlockYAt(x, z, heightmap)); } @@ -1258,14 +1360,16 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override - public @NotNull CompletableFuture getChunkAtAsync(int arg0, int arg1, boolean arg2) { - return parent.getChunkAtAsync(arg0, arg1, arg2); + @NotNull + public CompletableFuture getChunkAtAsync(int x, int z, boolean gen) { + return parent.getChunkAtAsync(x, z, gen); } @Override - public @NotNull CompletableFuture getChunkAtAsync(int x, int z, boolean gen, - boolean urgent) { - return null; + @NotNull + public CompletableFuture getChunkAtAsync(int x, int z, boolean gen, + boolean urgent) { + return parent.getChunkAtAsync(x, z, gen, urgent); } @Override @@ -1274,16 +1378,19 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override + @Deprecated public void getChunkAtAsync(int x, int z, @NotNull ChunkLoadCallback cb) { parent.getChunkAtAsync(x, z, cb); } @Override + @Deprecated public void getChunkAtAsync(@NotNull Location location, @NotNull ChunkLoadCallback cb) { parent.getChunkAtAsync(location, cb); } @Override + @Deprecated public void getChunkAtAsync(@NotNull Block block, @NotNull ChunkLoadCallback cb) { parent.getChunkAtAsync(block, cb); } @@ -1343,20 +1450,25 @@ public class AsyncWorld extends PassthroughExtent implements World { } @Override + @Deprecated public int getHighestBlockYAt(@NotNull Location location, @NotNull HeightmapType heightmap) throws UnsupportedOperationException { return parent.getHighestBlockYAt(location, heightmap); } @Override - public @NotNull Block getHighestBlockAt(int x, int z, @NotNull HeightmapType heightmap) + @NotNull + @Deprecated + public Block getHighestBlockAt(int x, int z, @NotNull HeightmapType heightmap) throws UnsupportedOperationException { return parent.getHighestBlockAt(x, z, heightmap); } @Override - public @NotNull Block getHighestBlockAt(@NotNull Location location, - @NotNull HeightmapType heightmap) throws UnsupportedOperationException { + @NotNull + @Deprecated + public Block getHighestBlockAt(@NotNull Location location, + @NotNull HeightmapType heightmap) throws UnsupportedOperationException { return parent.getHighestBlockAt(location, heightmap); } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/state/AsyncDataContainer.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/state/AsyncDataContainer.java index f504932db..0e29f2f19 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/state/AsyncDataContainer.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/state/AsyncDataContainer.java @@ -3,6 +3,12 @@ package com.boydti.fawe.bukkit.wrapper.state; import com.boydti.fawe.FaweCache; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.Tag; +import org.apache.commons.lang.Validate; +import org.bukkit.NamespacedKey; +import org.bukkit.persistence.PersistentDataAdapterContext; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataType; +import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.HashMap; @@ -11,13 +17,6 @@ import java.util.Map; import java.util.Objects; import java.util.Set; -import org.apache.commons.lang.Validate; -import org.bukkit.NamespacedKey; -import org.bukkit.persistence.PersistentDataAdapterContext; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataType; -import org.jetbrains.annotations.NotNull; - public final class AsyncDataContainer implements PersistentDataContainer { private final CompoundTag root; @@ -38,7 +37,9 @@ public final class AsyncDataContainer implements PersistentDataContainer { CompoundTag tag = root(); Map raw; if (tag == null) { - if (!create) return Collections.emptyMap(); + if (!create) { + return Collections.emptyMap(); + } Map map = root.getValue(); map.put("PublicBukkitValues", new CompoundTag(raw = new HashMap<>())); } else { @@ -58,7 +59,9 @@ public final class AsyncDataContainer implements PersistentDataContainer { Validate.notNull(key, "The provided key for the custom value was null"); Validate.notNull(type, "The provided type for the custom value was null"); Tag value = get(false).get(key.toString()); - if (value == null) return type == null; + if (value == null) { + return type == null; + } return type.getPrimitiveType() == value.getValue().getClass(); } @@ -106,7 +109,7 @@ public final class AsyncDataContainer implements PersistentDataContainer { return false; } else { Map myRawMap = this.getRaw(); - Map theirRawMap = ((AsyncDataContainer)obj).getRaw(); + Map theirRawMap = ((AsyncDataContainer) obj).getRaw(); return Objects.equals(myRawMap, theirRawMap); } } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/state/AsyncSign.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/state/AsyncSign.java index c1e97f7e3..85d7960e5 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/state/AsyncSign.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/wrapper/state/AsyncSign.java @@ -8,15 +8,15 @@ import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.util.formatting.text.TextComponent; import com.sk89q.worldedit.util.formatting.text.serializer.gson.GsonComponentSerializer; import com.sk89q.worldedit.util.formatting.text.serializer.legacy.LegacyComponentSerializer; -import java.util.Map; - import com.sk89q.worldedit.world.block.BaseBlock; import org.bukkit.DyeColor; import org.bukkit.block.Sign; import org.bukkit.persistence.PersistentDataContainer; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; +import java.util.Locale; +import java.util.Map; public class AsyncSign extends AsyncBlockState implements Sign { public AsyncSign(AsyncBlock block, BaseBlock state) { @@ -38,12 +38,16 @@ public class AsyncSign extends AsyncBlockState implements Sign { } private String fromJson(String jsonInput) { - if (jsonInput == null || jsonInput.isEmpty()) return ""; + if (jsonInput == null || jsonInput.isEmpty()) { + return ""; + } return GsonComponentSerializer.INSTANCE.deserialize(jsonInput).toString(); } private String toJson(String oldInput) { - if (oldInput == null || oldInput.isEmpty()) return ""; + if (oldInput == null || oldInput.isEmpty()) { + return ""; + } return LegacyComponentSerializer.INSTANCE.serialize(TextComponent.of(oldInput)); } @@ -73,16 +77,20 @@ public class AsyncSign extends AsyncBlockState implements Sign { } @Override - public @NotNull PersistentDataContainer getPersistentDataContainer() { + @NotNull + public PersistentDataContainer getPersistentDataContainer() { return new AsyncDataContainer(getNbtData()); } @Override - public @Nullable DyeColor getColor() { + @Nullable + public DyeColor getColor() { CompoundTag nbt = getNbtData(); if (nbt != null) { - String color = nbt.getString("Color").toUpperCase(); - if (!color.isEmpty()) return DyeColor.valueOf(color); + String color = nbt.getString("Color").toUpperCase(Locale.ROOT); + if (!color.isEmpty()) { + return DyeColor.valueOf(color); + } } return DyeColor.BLACK; } @@ -92,7 +100,7 @@ public class AsyncSign extends AsyncBlockState implements Sign { CompoundTag nbt = getNbtData(); if (nbt != null) { Map map = nbt.getValue(); - map.put("Color", new StringTag(color.name().toLowerCase())); + map.put("Color", new StringTag(color.name().toLowerCase(Locale.ROOT))); } } } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitAdapter.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitAdapter.java index d881a4146..37064fc05 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitAdapter.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitAdapter.java @@ -19,8 +19,6 @@ package com.sk89q.worldedit.bukkit; -import static com.google.common.base.Preconditions.checkNotNull; - import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; @@ -42,9 +40,6 @@ import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.item.ItemType; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import org.bukkit.Material; import org.bukkit.block.Biome; @@ -55,6 +50,12 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; + +import static com.google.common.base.Preconditions.checkNotNull; + /** * Adapts between Bukkit and WorldEdit equivalent objects. */ @@ -83,7 +84,7 @@ public enum BukkitAdapter { } /** - * Checks equality between a WorldEdit BlockType and a Bukkit Material + * Checks equality between a WorldEdit BlockType and a Bukkit Material. * * @param blockType The WorldEdit BlockType * @param type The Bukkit Material @@ -117,7 +118,7 @@ public enum BukkitAdapter { } /** - * Create a WorldEdit Actor from a Bukkit CommandSender + * Create a WorldEdit Actor from a Bukkit CommandSender. * * @param sender The Bukkit CommandSender * @return The WorldEdit Actor @@ -284,7 +285,7 @@ public enum BukkitAdapter { } /** - * Create a Bukkit Material form a WorldEdit ItemType + * Create a Bukkit Material form a WorldEdit ItemType. * * @param itemType The WorldEdit ItemType * @return The Bukkit Material @@ -294,7 +295,7 @@ public enum BukkitAdapter { } /** - * Create a Bukkit Material form a WorldEdit BlockType + * Create a Bukkit Material form a WorldEdit BlockType. * * @param blockType The WorldEdit BlockType * @return The Bukkit Material @@ -345,7 +346,7 @@ public enum BukkitAdapter { private static EnumMap materialItemTypeCache = new EnumMap<>(Material.class); /** - * Converts a Material to a BlockType + * Converts a Material to a BlockType. * * @param material The material * @return The blocktype @@ -356,7 +357,7 @@ public enum BukkitAdapter { } /** - * Converts a Material to a ItemType + * Converts a Material to a ItemType. * * @param material The material * @return The itemtype @@ -370,7 +371,7 @@ public enum BukkitAdapter { private static Map blockStateStringCache = new HashMap<>(); /** - * Create a WorldEdit BlockState from a Bukkit BlockData + * Create a WorldEdit BlockState from a Bukkit BlockData. * * @param blockData The Bukkit BlockData * @return The WorldEdit BlockState @@ -382,7 +383,7 @@ public enum BukkitAdapter { private static Int2ObjectMap blockDataCache = new Int2ObjectOpenHashMap<>(); /** - * Create a Bukkit BlockData from a WorldEdit BlockStateHolder + * Create a Bukkit BlockData from a WorldEdit BlockStateHolder. * * @param block The WorldEdit BlockStateHolder * @return The Bukkit BlockData @@ -392,7 +393,7 @@ public enum BukkitAdapter { } /** - * Create a WorldEdit BlockState from a Bukkit ItemStack + * Create a WorldEdit BlockState from a Bukkit ItemStack. * * @param itemStack The Bukkit ItemStack * @return The WorldEdit BlockState @@ -402,7 +403,7 @@ public enum BukkitAdapter { } /** - * Create a WorldEdit BaseItemStack from a Bukkit ItemStack + * Create a WorldEdit BaseItemStack from a Bukkit ItemStack. * * @param itemStack The Bukkit ItemStack * @return The WorldEdit BaseItemStack @@ -412,7 +413,7 @@ public enum BukkitAdapter { } /** - * Create a Bukkit ItemStack from a WorldEdit BaseItemStack + * Create a Bukkit ItemStack from a WorldEdit BaseItemStack. * * @param item The WorldEdit BaseItemStack * @return The Bukkit ItemStack diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockCommandSender.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockCommandSender.java index 4ab6e3bca..80ca08f49 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockCommandSender.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockCommandSender.java @@ -94,6 +94,7 @@ public class BukkitBlockCommandSender extends AbstractNonPlayerActor implements print(TextComponent.of(part, TextColor.RED)); } } + @Override public void print(Component component) { TextAdapter.sendComponent(sender, WorldEditText.format(component, getLocale())); diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockRegistry.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockRegistry.java index 72325aedf..6decfd7f2 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockRegistry.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockRegistry.java @@ -23,18 +23,17 @@ import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockType; -import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.registry.BlockMaterial; import com.sk89q.worldedit.world.registry.BundledBlockRegistry; import com.sk89q.worldedit.world.registry.PassthroughBlockMaterial; import org.bukkit.Material; import org.bukkit.block.data.BlockData; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.OptionalInt; +import javax.annotation.Nullable; public class BukkitBlockRegistry extends BundledBlockRegistry { @@ -46,7 +45,9 @@ public class BukkitBlockRegistry extends BundledBlockRegistry { BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); if (adapter != null) { BlockMaterial result = adapter.getMaterial(blockType); - if (result != null) return result; + if (result != null) { + return result; + } } Material mat = BukkitAdapter.adapt(blockType); if (mat == null) { @@ -69,7 +70,9 @@ public class BukkitBlockRegistry extends BundledBlockRegistry { BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); if (adapter != null) { BlockMaterial result = adapter.getMaterial(state); - if (result != null) return result; + if (result != null) { + return result; + } } return super.getMaterial(state); } @@ -81,6 +84,7 @@ public class BukkitBlockRegistry extends BundledBlockRegistry { } return OptionalInt.empty(); } + @Nullable @Override public Map> getProperties(BlockType blockType) { diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandInspector.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandInspector.java index 0f4c0c213..8fbdbea5e 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandInspector.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandInspector.java @@ -19,13 +19,9 @@ package com.sk89q.worldedit.bukkit; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.sk89q.worldedit.util.formatting.WorldEditText.reduceToText; - import com.sk89q.bukkit.util.CommandInspector; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.extension.platform.Actor; -import java.util.Optional; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.enginehub.piston.CommandManager; @@ -33,10 +29,13 @@ import org.enginehub.piston.inject.InjectedValueStore; import org.enginehub.piston.inject.Key; import org.enginehub.piston.inject.MapBackedValueStore; import org.slf4j.Logger; - -import java.util.Locale; import org.slf4j.LoggerFactory; +import java.util.Optional; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.sk89q.worldedit.util.formatting.WorldEditText.reduceToText; + class BukkitCommandInspector implements CommandInspector { private static final Logger logger = LoggerFactory.getLogger(BukkitCommandInspector.class); diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandSender.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandSender.java index 5934ab7d3..fec26a990 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandSender.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitCommandSender.java @@ -19,25 +19,24 @@ package com.sk89q.worldedit.bukkit; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - import com.sk89q.worldedit.WorldEdit; - import com.sk89q.worldedit.extension.platform.AbstractNonPlayerActor; import com.sk89q.worldedit.session.SessionKey; import com.sk89q.worldedit.util.auth.AuthorizationException; import com.sk89q.worldedit.util.formatting.WorldEditText; import com.sk89q.worldedit.util.formatting.text.Component; import com.sk89q.worldedit.util.formatting.text.adapter.bukkit.TextAdapter; -import java.util.UUID; - -import java.util.Locale; -import javax.annotation.Nullable; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; +import java.util.Locale; +import java.util.UUID; +import javax.annotation.Nullable; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + public class BukkitCommandSender extends AbstractNonPlayerActor { /** @@ -45,8 +44,8 @@ public class BukkitCommandSender extends AbstractNonPlayerActor { */ private static final UUID DEFAULT_ID = UUID.fromString("a233eb4b-4cab-42cd-9fd9-7e7b9a3f74be"); - private CommandSender sender; - private WorldEditPlugin plugin; + private final CommandSender sender; + private final WorldEditPlugin plugin; public BukkitCommandSender(WorldEditPlugin plugin, CommandSender sender) { checkNotNull(plugin); @@ -68,6 +67,7 @@ public class BukkitCommandSender extends AbstractNonPlayerActor { } @Override + @Deprecated public void printRaw(String msg) { for (String part : msg.split("\n")) { sender.sendMessage(part); @@ -75,25 +75,29 @@ public class BukkitCommandSender extends AbstractNonPlayerActor { } @Override + @Deprecated public void print(String msg) { for (String part : msg.split("\n")) { - sender.sendMessage("\u00A7d" + part); + sender.sendMessage("§d" + part); } } @Override + @Deprecated public void printDebug(String msg) { for (String part : msg.split("\n")) { - sender.sendMessage("\u00A77" + part); + sender.sendMessage("§7" + part); } } @Override + @Deprecated public void printError(String msg) { for (String part : msg.split("\n")) { - sender.sendMessage("\u00A7c" + part); + sender.sendMessage("§c" + part); } } + @Override public void print(Component component) { TextAdapter.sendComponent(sender, WorldEditText.format(component, getLocale())); diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntityProperties.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntityProperties.java index abba07a63..f0ae173bb 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntityProperties.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntityProperties.java @@ -19,8 +19,6 @@ package com.sk89q.worldedit.bukkit; -import static com.google.common.base.Preconditions.checkNotNull; - import com.sk89q.worldedit.entity.metadata.EntityProperties; import org.bukkit.entity.Ambient; import org.bukkit.entity.Animals; @@ -44,6 +42,8 @@ import org.bukkit.entity.Tameable; import org.bukkit.entity.Villager; import org.bukkit.entity.minecart.ExplosiveMinecart; +import static com.google.common.base.Preconditions.checkNotNull; + class BukkitEntityProperties implements EntityProperties { private final Entity entity; diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntityRegistry.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntityRegistry.java index 4fba200f6..7fb77d1e4 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntityRegistry.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntityRegistry.java @@ -14,10 +14,12 @@ public class BukkitEntityRegistry implements EntityRegistry { for (EntityType type : EntityType.values()) { String name = type.getName(); if (name != null) { - if (name.indexOf(':') == -1) name = "minecraft:" + name; + if (name.indexOf(':') == -1) { + name = "minecraft:" + name; + } types.add(name); } } return types; } -} \ No newline at end of file +} diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitPlayer.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitPlayer.java index be5cdd301..e59bc0ae3 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitPlayer.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitPlayer.java @@ -62,12 +62,11 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.permissions.PermissionAttachment; -import java.util.concurrent.ConcurrentHashMap; import java.util.HashMap; -import java.util.Map; import java.util.Locale; +import java.util.Map; import java.util.UUID; - +import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nullable; public class BukkitPlayer extends AbstractPlayerActor { @@ -173,23 +172,24 @@ public class BukkitPlayer extends AbstractPlayerActor { @Override public void print(String msg) { for (String part : msg.split("\n")) { - player.sendMessage("\u00A7d" + part); + player.sendMessage("§d" + part); } } @Override public void printDebug(String msg) { for (String part : msg.split("\n")) { - player.sendMessage("\u00A77" + part); + player.sendMessage("§7" + part); } } @Override public void printError(String msg) { for (String part : msg.split("\n")) { - player.sendMessage("\u00A7c" + part); + player.sendMessage("§c" + part); } } + @Override public void print(Component component) { component = Caption.color(TranslatableComponent.of("prefix", component), getLocale()); diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditListener.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditListener.java index ed505c580..388310f3e 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditListener.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditListener.java @@ -44,14 +44,14 @@ import org.enginehub.piston.inject.MapBackedValueStore; import java.util.Optional; /** - * Handles all events thrown in relation to a Player + * Handles all events thrown in relation to a Player. */ public class WorldEditListener implements Listener { - private WorldEditPlugin plugin; + private final WorldEditPlugin plugin; /** - * Construct the object; + * Construct the object. * * @param plugin the plugin */ @@ -84,7 +84,7 @@ public class WorldEditListener implements Listener { } /** - * Called when a player interacts + * Called when a player interacts. * * @param event Relevant event details */ diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplAdapter.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplAdapter.java index 8597175f2..f94dc5e12 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplAdapter.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplAdapter.java @@ -42,10 +42,6 @@ import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.registry.BlockMaterial; -import java.util.Map; -import java.util.OptionalInt; -import java.util.Set; -import javax.annotation.Nullable; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.WorldCreator; @@ -55,6 +51,11 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import java.util.Map; +import java.util.OptionalInt; +import java.util.Set; +import javax.annotation.Nullable; + /** * An interface for adapters of various Bukkit implementations. */ @@ -68,7 +69,7 @@ public interface BukkitImplAdapter extends IBukkitAdapter { int getDataVersion(); /** - * Get a data fixer, or null if not supported + * Get a data fixer, or null if not supported. * * @return the data fixer */ @@ -76,6 +77,8 @@ public interface BukkitImplAdapter extends IBukkitAdapter { DataFixer getDataFixer(); /** + * Check if this adapter supports the watchdog. + * * @return {@code true} if {@link #tickWatchdog()} is implemented */ default boolean supportsWatchdog() { @@ -217,14 +220,13 @@ public interface BukkitImplAdapter extends IBukkitAdapter { return null; } - default @Nullable World createWorld(WorldCreator creator) { + @Nullable + default World createWorld(WorldCreator creator) { return ((FaweBukkit) Fawe.imp()).createWorldUnloaded(creator::createWorld); } /** - * Send a fake chunk packet to a player - * @param player - * @param packet + * Send a fake chunk packet to a player. */ default void sendFakeChunk(org.bukkit.World world, Player player, ChunkPacket packet) { throw new UnsupportedOperationException("Cannot send fake chunks"); diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/CachedBukkitAdapter.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/CachedBukkitAdapter.java index 43beef3b7..8b0af1f65 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/CachedBukkitAdapter.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/CachedBukkitAdapter.java @@ -1,7 +1,5 @@ package com.sk89q.worldedit.bukkit.adapter; -import static com.google.common.base.Preconditions.checkNotNull; - import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockType; @@ -9,11 +7,14 @@ import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypesCache; import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemTypes; -import java.util.List; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.block.data.BlockData; +import java.util.List; + +import static com.google.common.base.Preconditions.checkNotNull; + public abstract class CachedBukkitAdapter implements IBukkitAdapter { private int[] itemTypes; private int[] blockTypes; @@ -25,7 +26,9 @@ public abstract class CachedBukkitAdapter implements IBukkitAdapter { blockTypes = new int[materials.length]; for (int i = 0; i < materials.length; i++) { Material material = materials[i]; - if (material.isLegacy()) continue; + if (material.isLegacy()) { + continue; + } NamespacedKey key = material.getKey(); String id = key.getNamespace() + ":" + key.getKey(); if (material.isBlock()) { @@ -41,7 +44,7 @@ public abstract class CachedBukkitAdapter implements IBukkitAdapter { } /** - * Converts a Material to a ItemType + * Converts a Material to a ItemType. * * @param material The material * @return The itemtype @@ -51,7 +54,9 @@ public abstract class CachedBukkitAdapter implements IBukkitAdapter { try { return ItemTypes.get(itemTypes[material.ordinal()]); } catch (NullPointerException e) { - if (init()) return asItemType(material); + if (init()) { + return asItemType(material); + } return ItemTypes.get(itemTypes[material.ordinal()]); } } @@ -61,13 +66,15 @@ public abstract class CachedBukkitAdapter implements IBukkitAdapter { try { return BlockTypesCache.values[blockTypes[material.ordinal()]]; } catch (NullPointerException e) { - if (init()) return asBlockType(material); + if (init()) { + return asBlockType(material); + } throw e; } } /** - * Create a WorldEdit BlockStateHolder from a Bukkit BlockData + * Create a WorldEdit BlockStateHolder from a Bukkit BlockData. * * @param blockData The Bukkit BlockData * @return The WorldEdit BlockState @@ -79,11 +86,15 @@ public abstract class CachedBukkitAdapter implements IBukkitAdapter { Material material = blockData.getMaterial(); BlockType type = BlockTypes.getFromStateId(blockTypes[material.ordinal()]); List propList = type.getProperties(); - if (propList.size() == 0) return type.getDefaultState(); + if (propList.size() == 0) { + return type.getDefaultState(); + } String properties = blockData.getAsString(); return BlockState.get(type, properties, type.getDefaultState()); } catch (NullPointerException e) { - if (init()) return adapt(blockData); + if (init()) { + return adapt(blockData); + } throw e; } } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/IBukkitAdapter.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/IBukkitAdapter.java index bdb6b8048..9e756d684 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/IBukkitAdapter.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/IBukkitAdapter.java @@ -93,7 +93,7 @@ public interface IBukkitAdapter { position.getX(), position.getY(), position.getZ()); } - default org.bukkit.Location adapt(org.bukkit.World world, BlockVector3 position){ + default org.bukkit.Location adapt(org.bukkit.World world, BlockVector3 position) { return adapt(world, position.toVector3()); } @@ -254,7 +254,9 @@ public interface IBukkitAdapter { */ default ItemStack adapt(BaseItemStack item) { checkNotNull(item); - if (item instanceof BukkitItemStack) return ((BukkitItemStack) item).getBukkitItemStack(); + if (item instanceof BukkitItemStack) { + return ((BukkitItemStack) item).getBukkitItemStack(); + } return new ItemStack(adapt(item.getType()), item.getAmount()); } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/SimpleBukkitAdapter.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/SimpleBukkitAdapter.java index f51ffea35..e197f60ce 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/SimpleBukkitAdapter.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/SimpleBukkitAdapter.java @@ -13,7 +13,9 @@ public class SimpleBukkitAdapter extends CachedBukkitAdapter { private BlockData[][] blockDataCache; private boolean init() { - if (blockDataCache != null) return false; + if (blockDataCache != null) { + return false; + } this.blockDataCache = new BlockData[BlockTypes.size()][]; blockDataCache[0] = new BlockData[] {Material.AIR.createBlockData()}; return true; @@ -42,7 +44,9 @@ public class SimpleBukkitAdapter extends CachedBukkitAdapter { } return blockData; } catch (NullPointerException e) { - if (init()) return adapt(block); + if (init()) { + return adapt(block); + } throw e; } } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_15_R2.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_15_R2.java index e2ad78cc5..363dd3a83 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_15_R2.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_15_R2.java @@ -26,10 +26,15 @@ import com.boydti.fawe.beta.IQueueChunk; import com.boydti.fawe.beta.IQueueExtent; import com.boydti.fawe.beta.implementation.packet.ChunkPacket; import com.boydti.fawe.beta.implementation.queue.SingleThreadQueueExtent; -import com.boydti.fawe.bukkit.adapter.mc1_15_2.*; +import com.boydti.fawe.bukkit.adapter.mc1_15_2.BlockMaterial_1_15_2; +import com.boydti.fawe.bukkit.adapter.mc1_15_2.BukkitAdapter_1_15_2; +import com.boydti.fawe.bukkit.adapter.mc1_15_2.BukkitGetBlocks_1_15_2; +import com.boydti.fawe.bukkit.adapter.mc1_15_2.FAWEWorldNativeAccess_1_15_2; +import com.boydti.fawe.bukkit.adapter.mc1_15_2.MapChunkUtil_1_15_2; import com.boydti.fawe.bukkit.adapter.mc1_15_2.nbt.LazyCompoundTag_1_15_2; import com.google.common.io.Files; import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; @@ -48,11 +53,39 @@ import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.util.SideEffect; import com.sk89q.worldedit.util.SideEffectSet; 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.*; +import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.world.block.BlockTypesCache; import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.registry.BlockMaterial; -import net.minecraft.server.v1_15_R1.*; +import net.minecraft.server.v1_15_R1.BiomeBase; +import net.minecraft.server.v1_15_R1.Block; +import net.minecraft.server.v1_15_R1.BlockPosition; +import net.minecraft.server.v1_15_R1.Chunk; +import net.minecraft.server.v1_15_R1.ChunkCoordIntPair; +import net.minecraft.server.v1_15_R1.ChunkProviderServer; +import net.minecraft.server.v1_15_R1.ChunkSection; +import net.minecraft.server.v1_15_R1.Entity; +import net.minecraft.server.v1_15_R1.EntityPlayer; +import net.minecraft.server.v1_15_R1.EntityTypes; +import net.minecraft.server.v1_15_R1.IBlockData; +import net.minecraft.server.v1_15_R1.IRegistry; +import net.minecraft.server.v1_15_R1.ItemStack; +import net.minecraft.server.v1_15_R1.MinecraftKey; +import net.minecraft.server.v1_15_R1.MinecraftServer; +import net.minecraft.server.v1_15_R1.NBTBase; +import net.minecraft.server.v1_15_R1.NBTTagCompound; +import net.minecraft.server.v1_15_R1.NBTTagInt; +import net.minecraft.server.v1_15_R1.PacketPlayOutMapChunk; +import net.minecraft.server.v1_15_R1.PlayerChunk; +import net.minecraft.server.v1_15_R1.TileEntity; +import net.minecraft.server.v1_15_R1.World; +import net.minecraft.server.v1_15_R1.WorldData; +import net.minecraft.server.v1_15_R1.WorldNBTStorage; +import net.minecraft.server.v1_15_R1.WorldServer; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World.Environment; @@ -67,7 +100,6 @@ import org.bukkit.craftbukkit.v1_15_R1.inventory.CraftItemStack; import org.bukkit.entity.Player; import org.bukkit.generator.ChunkGenerator; -import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.lang.ref.WeakReference; @@ -79,9 +111,9 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.function.Supplier; import java.util.stream.Stream; +import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.jnbt.StringTag; public final class FAWE_Spigot_v1_15_R2 extends CachedBukkitAdapter implements IDelegateBukkitImplAdapter { private final Spigot_v1_15_R2 parent; @@ -101,7 +133,9 @@ public final class FAWE_Spigot_v1_15_R2 extends CachedBukkitAdapter implements I } private synchronized boolean init() { - if (ibdToStateOrdinal != null && ibdToStateOrdinal[1] != 0) return false; + if (ibdToStateOrdinal != null && ibdToStateOrdinal[1] != 0) { + return false; + } ibdToStateOrdinal = new char[Block.REGISTRY_ID.a()]; // size for (int i = 0; i < ibdToStateOrdinal.length; i++) { BlockState state = BlockTypesCache.states[i]; @@ -202,9 +236,13 @@ public final class FAWE_Spigot_v1_15_R2 extends CachedBukkitAdapter implements I } } } else { - if (existing == blockData) return true; + if (existing == blockData) { + return true; + } if (section == null) { - if (blockData.isAir()) return true; + if (blockData.isAir()) { + return true; + } sections[y4] = section = new ChunkSection(y4 << 4); } nmsChunk.setType(blockPos, blockData, false); @@ -300,7 +338,7 @@ public final class FAWE_Spigot_v1_15_R2 extends CachedBukkitAdapter implements I } catch (NullPointerException e) { init(); return adaptToChar(ibd); - } catch(ArrayIndexOutOfBoundsException e1){ + } catch (ArrayIndexOutOfBoundsException e1) { Fawe.debug("Attempted to convert " + ibd.getBlock() + " with ID " + Block.REGISTRY_ID.getId(ibd) + " to char. ibdToStateOrdinal length: " + ibdToStateOrdinal.length + ". Defaulting to air!"); return 0; } @@ -406,7 +444,7 @@ public final class FAWE_Spigot_v1_15_R2 extends CachedBukkitAdapter implements I originalWorld.getMethodProfiler(), server.worldLoadListenerFactory.create(11), env, - gen){ + gen) { @Override public boolean addEntityChunk(net.minecraft.server.v1_15_R1.Entity entity) { //Fixes #320; Prevent adding entities so we aren't attempting to spawn them asynchronously @@ -421,10 +459,12 @@ public final class FAWE_Spigot_v1_15_R2 extends CachedBukkitAdapter implements I IQueueExtent extent = new SingleThreadQueueExtent(); extent.init(null, (x, z) -> new BukkitGetBlocks_1_15_2(freshWorld, x, z) { @Override - public Chunk ensureLoaded(World nmsWorld, int X, int Z) { - Chunk cached = nmsWorld.getChunkIfLoaded(X, Z); - if (cached != null) return cached; - Future future = Fawe.get().getQueueHandler().sync((Supplier) () -> freshWorld.getChunkAt(X, Z)); + public Chunk ensureLoaded(World nmsWorld, int chunkX, int chunkZ) { + Chunk cached = nmsWorld.getChunkIfLoaded(chunkX, chunkZ); + if (cached != null) { + return cached; + } + Future future = Fawe.get().getQueueHandler().sync((Supplier) () -> freshWorld.getChunkAt(chunkX, chunkZ)); while (!future.isDone()) { // this feels so dirty freshWorld.getChunkProvider().runTasks(); diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_16_R1.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_16_R1.java index 3dc1cc104..8272d3b29 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_16_R1.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_16_R1.java @@ -88,7 +88,9 @@ public final class FAWE_Spigot_v1_16_R1 extends CachedBukkitAdapter implements I } private synchronized boolean init() { - if (ibdToStateOrdinal != null && ibdToStateOrdinal[1] != 0) return false; + if (ibdToStateOrdinal != null && ibdToStateOrdinal[1] != 0) { + return false; + } ibdToStateOrdinal = new char[Block.REGISTRY_ID.a()]; // size for (int i = 0; i < ibdToStateOrdinal.length; i++) { BlockState state = BlockTypesCache.states[i]; @@ -189,9 +191,13 @@ public final class FAWE_Spigot_v1_16_R1 extends CachedBukkitAdapter implements I } } } else { - if (existing == blockData) return true; + if (existing == blockData) { + return true; + } if (section == null) { - if (blockData.isAir()) return true; + if (blockData.isAir()) { + return true; + } sections[y4] = section = new ChunkSection(y4 << 4); } nmsChunk.setType(blockPos, blockData, false); @@ -287,7 +293,7 @@ public final class FAWE_Spigot_v1_16_R1 extends CachedBukkitAdapter implements I } catch (NullPointerException e) { init(); return adaptToChar(ibd); - } catch(ArrayIndexOutOfBoundsException e1){ + } catch (ArrayIndexOutOfBoundsException e1) { Fawe.debug("Attempted to convert " + ibd.getBlock() + " with ID " + Block.REGISTRY_ID.getId(ibd) + " to char. ibdToStateOrdinal length: " + ibdToStateOrdinal.length + ". Defaulting to air!"); return 0; } @@ -393,7 +399,7 @@ public final class FAWE_Spigot_v1_16_R1 extends CachedBukkitAdapter implements I // originalWorld.getMethodProfiler(), // server.worldLoadListenerFactory.create(11), // env, -// gen){ +// gen) { // @Override // public boolean addEntityChunk(Entity entity) { // //Fixes #320; Prevent adding entities so we aren't attempting to spawn them asynchronously diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_16_R2.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_16_R2.java index 0258f1c54..9a9c0fbe2 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_16_R2.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/FAWE_Spigot_v1_16_R2.java @@ -23,9 +23,14 @@ import com.boydti.fawe.Fawe; import com.boydti.fawe.FaweCache; import com.boydti.fawe.beta.IChunkGet; import com.boydti.fawe.beta.implementation.packet.ChunkPacket; -import com.boydti.fawe.bukkit.adapter.mc1_16_2.*; +import com.boydti.fawe.bukkit.adapter.mc1_16_2.BlockMaterial_1_16_2; +import com.boydti.fawe.bukkit.adapter.mc1_16_2.BukkitAdapter_1_16_2; +import com.boydti.fawe.bukkit.adapter.mc1_16_2.BukkitGetBlocks_1_16_2; +import com.boydti.fawe.bukkit.adapter.mc1_16_2.FAWEWorldNativeAccess_1_16; +import com.boydti.fawe.bukkit.adapter.mc1_16_2.MapChunkUtil_1_16_2; import com.boydti.fawe.bukkit.adapter.mc1_16_2.nbt.LazyCompoundTag_1_16_2; import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.blocks.BaseItemStack; @@ -42,14 +47,38 @@ import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.util.SideEffect; import com.sk89q.worldedit.util.SideEffectSet; 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.*; +import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.world.block.BlockTypesCache; import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.registry.BlockMaterial; -import net.minecraft.server.v1_16_R2.*; +import net.minecraft.server.v1_16_R2.BiomeBase; +import net.minecraft.server.v1_16_R2.Block; +import net.minecraft.server.v1_16_R2.BlockPosition; +import net.minecraft.server.v1_16_R2.Chunk; +import net.minecraft.server.v1_16_R2.ChunkCoordIntPair; +import net.minecraft.server.v1_16_R2.ChunkSection; +import net.minecraft.server.v1_16_R2.Entity; +import net.minecraft.server.v1_16_R2.EntityPlayer; +import net.minecraft.server.v1_16_R2.EntityTypes; +import net.minecraft.server.v1_16_R2.IBlockData; +import net.minecraft.server.v1_16_R2.IRegistry; +import net.minecraft.server.v1_16_R2.ItemStack; +import net.minecraft.server.v1_16_R2.MinecraftKey; +import net.minecraft.server.v1_16_R2.MinecraftServer; +import net.minecraft.server.v1_16_R2.NBTBase; +import net.minecraft.server.v1_16_R2.NBTTagCompound; +import net.minecraft.server.v1_16_R2.NBTTagInt; +import net.minecraft.server.v1_16_R2.PacketPlayOutMapChunk; +import net.minecraft.server.v1_16_R2.PlayerChunk; +import net.minecraft.server.v1_16_R2.TileEntity; +import net.minecraft.server.v1_16_R2.World; +import net.minecraft.server.v1_16_R2.WorldServer; import org.bukkit.Bukkit; import org.bukkit.Location; -import org.bukkit.Server; import org.bukkit.block.data.BlockData; import org.bukkit.craftbukkit.v1_16_R2.CraftChunk; import org.bukkit.craftbukkit.v1_16_R2.CraftWorld; @@ -60,16 +89,15 @@ import org.bukkit.craftbukkit.v1_16_R2.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_16_R2.inventory.CraftItemStack; import org.bukkit.entity.Player; -import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.Map; import java.util.OptionalInt; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Stream; +import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.jnbt.StringTag; public final class FAWE_Spigot_v1_16_R2 extends CachedBukkitAdapter implements IDelegateBukkitImplAdapter { private final Spigot_v1_16_R2 parent; @@ -89,7 +117,9 @@ public final class FAWE_Spigot_v1_16_R2 extends CachedBukkitAdapter implements I } private synchronized boolean init() { - if (ibdToStateOrdinal != null && ibdToStateOrdinal[1] != 0) return false; + if (ibdToStateOrdinal != null && ibdToStateOrdinal[1] != 0) { + return false; + } ibdToStateOrdinal = new char[Block.REGISTRY_ID.a()]; // size for (int i = 0; i < ibdToStateOrdinal.length; i++) { BlockState state = BlockTypesCache.states[i]; @@ -188,9 +218,13 @@ public final class FAWE_Spigot_v1_16_R2 extends CachedBukkitAdapter implements I } } } else { - if (existing == blockData) return true; + if (existing == blockData) { + return true; + } if (section == null) { - if (blockData.isAir()) return true; + if (blockData.isAir()) { + return true; + } sections[y4] = section = new ChunkSection(y4 << 4); } nmsChunk.setType(blockPos, blockData, false); @@ -231,7 +265,7 @@ public final class FAWE_Spigot_v1_16_R2 extends CachedBukkitAdapter implements I Supplier saveTag = () -> { NBTTagCompound tag = new NBTTagCompound(); readEntityIntoTag(mcEntity, tag); - + //add Id for AbstractChangeSet to work CompoundTag natve = (CompoundTag) toNative(tag); natve.getValue().put("Id", new StringTag(id)); @@ -286,7 +320,7 @@ public final class FAWE_Spigot_v1_16_R2 extends CachedBukkitAdapter implements I } catch (NullPointerException e) { init(); return adaptToChar(ibd); - } catch(ArrayIndexOutOfBoundsException e1){ + } catch (ArrayIndexOutOfBoundsException e1) { Fawe.debug("Attempted to convert " + ibd.getBlock() + " with ID " + Block.REGISTRY_ID.getId(ibd) + " to char. ibdToStateOrdinal length: " + ibdToStateOrdinal.length + ". Defaulting to air!"); return 0; } @@ -392,7 +426,7 @@ public final class FAWE_Spigot_v1_16_R2 extends CachedBukkitAdapter implements I // originalWorld.getMethodProfiler(), // server.worldLoadListenerFactory.create(11), // env, -// gen){ +// gen) { // @Override // public boolean addEntityChunk(Entity entity) { // //Fixes #320; Prevent adding entities so we aren't attempting to spawn them asynchronously 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 440b98efa..99c5d4206 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java @@ -79,70 +79,57 @@ public class Fawe { private static final Logger log = LoggerFactory.getLogger(Fawe.class); - /** - * The FAWE instance; - */ - private static Fawe INSTANCE; + private static Fawe instance; /** - * TPS timer + * The ticks-per-second timer. */ private final FaweTimer timer; private FaweVersion version; private VisualQueue visualQueue; private TextureUtil textures; - // TODO: Ping @MattBDev to reimplement 2020-02-04 -// private DefaultTransformParser transformParser; + private QueueHandler queueHandler; /** - * Get the implementation specific class - * - * @return + * Get the implementation specific class. */ @SuppressWarnings("unchecked") public static T imp() { - return INSTANCE != null ? (T) INSTANCE.IMP : null; + return instance != null ? (T) instance.implementation : null; } /** - * Get the implementation independent class - * - * @return + * Get the implementation independent class. */ public static Fawe get() { - return INSTANCE; + return instance; } /** - * Setup Fawe - * - * @param implementation - * @throws InstanceAlreadyExistsException + * This method is not for public use. If you have to ask what it does then you shouldn't be using it. */ public static void set(final IFawe implementation) throws InstanceAlreadyExistsException, IllegalArgumentException { - if (INSTANCE != null) { - throw new InstanceAlreadyExistsException("FAWE has already been initialized with: " + INSTANCE.IMP); + if (instance != null) { + throw new InstanceAlreadyExistsException("FAWE has already been initialized with: " + instance.implementation); } if (implementation == null) { throw new IllegalArgumentException("Implementation may not be null."); } - INSTANCE = new Fawe(implementation); + instance = new Fawe(implementation); } public static void debugPlain(String s) { - if (INSTANCE != null) { - INSTANCE.IMP.debug(s); + if (instance != null) { + instance.implementation.debug(s); } else { - System.out.println(s); + log.debug(s); } } /** - * Write something to the console - * - * @param s + * Write something to the console. */ public static void debug(String s) { Actor actor = Request.request().getActor(); @@ -152,9 +139,9 @@ public class Fawe { } debugPlain(s); } - + /** - * Write something to the console + * Write something to the console. * * @param c The Component to be printed */ @@ -168,24 +155,26 @@ public class Fawe { } /** - * The platform specific implementation + * The platform specific implementation. */ - private final IFawe IMP; + private final IFawe implementation; private Thread thread; private Fawe(final IFawe implementation) { - INSTANCE = this; - this.IMP = implementation; + instance = this; + this.implementation = implementation; this.thread = Thread.currentThread(); /* * Implementation dependent stuff */ this.setupConfigs(); - TaskManager.IMP = this.IMP.getTaskManager(); + TaskManager.IMP = this.implementation.getTaskManager(); TaskManager.IMP.async(() -> { - MainUtil.deleteOlder(MainUtil.getFile(IMP.getDirectory(), Settings.IMP.PATHS.HISTORY), TimeUnit.DAYS.toMillis(Settings.IMP.HISTORY.DELETE_AFTER_DAYS), false); - MainUtil.deleteOlder(MainUtil.getFile(IMP.getDirectory(), Settings.IMP.PATHS.CLIPBOARD), TimeUnit.DAYS.toMillis(Settings.IMP.CLIPBOARD.DELETE_AFTER_DAYS), false); + MainUtil.deleteOlder(MainUtil.getFile(this.implementation + .getDirectory(), Settings.IMP.PATHS.HISTORY), TimeUnit.DAYS.toMillis(Settings.IMP.HISTORY.DELETE_AFTER_DAYS), false); + MainUtil.deleteOlder(MainUtil.getFile(this.implementation + .getDirectory(), Settings.IMP.PATHS.CLIPBOARD), TimeUnit.DAYS.toMillis(Settings.IMP.CLIPBOARD.DELETE_AFTER_DAYS), false); }); /* @@ -197,11 +186,10 @@ public class Fawe { // Delayed worldedit setup TaskManager.IMP.later(() -> { try { - // TODO: Ping @MattBDev to reimplement 2020-02-04 -// transformParser = new DefaultTransformParser(getWorldEdit()); visualQueue = new VisualQueue(3); - WEManager.IMP.managers.addAll(Fawe.this.IMP.getMaskManagers()); - } catch (Throwable ignored) {} + WEManager.IMP.managers.addAll(Fawe.this.implementation.getMaskManagers()); + } catch (Throwable ignored) { + } }, 0); TaskManager.IMP.repeat(timer, 1); @@ -214,17 +202,12 @@ public class Fawe { if (queueHandler == null) { synchronized (this) { if (queueHandler == null) { - queueHandler = IMP.getQueueHandler(); + queueHandler = implementation.getQueueHandler(); } } } return queueHandler; } - - // TODO: Ping @MattBDev to reimplement 2020-02-04 -// public DefaultTransformParser getTransformParser() { -// return transformParser; -// } public TextureUtil getCachedTextureUtil(boolean randomize, int min, int max) { // TODO NOT IMPLEMENTED - optimize this by caching the default true/0/100 texture util @@ -257,32 +240,27 @@ public class Fawe { } /** - * The FaweTimer is a useful class for monitoring TPS - * - * @return FaweTimer + * Gets the TPS monitor. */ public FaweTimer getTimer() { return timer; } /** - * The visual queue is used to queue visualizations - * - * @return + * Get the visual queue. */ public VisualQueue getVisualQueue() { return visualQueue; } /** - * The FAWE version - * - Unofficial jars may be lacking version information + * The FAWE version. * + * @apiNote Unofficial jars may be lacking version information * @return FaweVersion */ - public @Nullable - FaweVersion getVersion() { + public FaweVersion getVersion() { return version; } @@ -293,8 +271,8 @@ public class Fawe { public void setupConfigs() { MainUtil.copyFile(MainUtil.getJarFile(), "lang/strings.json", null); // Setting up config.yml - File file = new File(this.IMP.getDirectory(), "config.yml"); - Settings.IMP.PLATFORM = IMP.getPlatform().replace("\"", ""); + File file = new File(this.implementation.getDirectory(), "config.yml"); + Settings.IMP.PLATFORM = implementation.getPlatform().replace("\"", ""); try (InputStream stream = getClass().getResourceAsStream(File.separator + "fawe.properties"); BufferedReader br = new BufferedReader(new InputStreamReader(stream))) { String versionString = br.readLine(); @@ -305,14 +283,12 @@ public class Fawe { Settings.IMP.DATE = new Date(100 + version.year, version.month, version.day).toGMTString(); Settings.IMP.BUILD = "https://ci.athion.net/job/FastAsyncWorldEdit-1.16/" + version.build; Settings.IMP.COMMIT = "https://github.com/IntellectualSites/FastAsyncWorldEdit/commit/" + Integer.toHexString(version.hash); - } catch (Throwable ignore) {} + } catch (Throwable ignored) { + } try { Settings.IMP.reload(file); } catch (Throwable e) { - debug("====== Failed to load config ======"); - debug("Please validate your yaml files:"); - e.printStackTrace(); - debug("===================================="); + log.error("Failed to load config.", e); } } @@ -334,22 +310,15 @@ public class Fawe { if (Settings.IMP.CLIPBOARD.COMPRESSION_LEVEL > 6 || Settings.IMP.HISTORY.COMPRESSION_LEVEL > 6) { Settings.IMP.CLIPBOARD.COMPRESSION_LEVEL = Math.min(6, Settings.IMP.CLIPBOARD.COMPRESSION_LEVEL); Settings.IMP.HISTORY.COMPRESSION_LEVEL = Math.min(6, Settings.IMP.HISTORY.COMPRESSION_LEVEL); - debug("====== ZSTD COMPRESSION BINDING NOT FOUND ======"); - debug(e.getMessage()); - debug("FAWE will work but won't compress data as much"); - debug("==============================================="); + log.error("ZSTD Compression Binding Not Found.\n" + + "FAWE will still work but compression won't work as well.\n", e); } } try { net.jpountz.util.Native.load(); } catch (Throwable e) { - e.printStackTrace(); - debug("====== LZ4 COMPRESSION BINDING NOT FOUND ======"); - debug(e.getMessage()); - debug("FAWE will work but compression will be slower"); - debug(" - Try updating your JVM / OS"); - debug(" - Report this issue if you cannot resolve it"); - debug("==============================================="); + log.error("LZ4 Compression Binding Not Found.\n" + + "FAWE will still work but compression will be slower.\n", e); } } @@ -402,22 +371,18 @@ public class Fawe { } /** - * Get the main thread - * - * @return + * Get the main thread. */ public Thread getMainThread() { return this.thread; } public static boolean isMainThread() { - return INSTANCE == null || INSTANCE.thread == Thread.currentThread(); + return instance == null || instance.thread == Thread.currentThread(); } /** - * Sets the main thread to the current thread - * - * @return + * Sets the main thread to the current thread. */ public Thread setMainThread() { return this.thread = Thread.currentThread(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/FaweAPI.java b/worldedit-core/src/main/java/com/boydti/fawe/FaweAPI.java index 3267eab57..aa8ef4859 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/FaweAPI.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/FaweAPI.java @@ -55,19 +55,20 @@ import javax.annotation.Nullable; * FaweAPI.[some method] */ public class FaweAPI { + /** - * Offers a lot of options for building an EditSession + * Offers a lot of options for building an EditSession. * - * @param world * @return A new EditSessionBuilder * @see EditSessionBuilder */ + @Deprecated public static EditSessionBuilder getEditSessionBuilder(World world) { return new EditSessionBuilder(world); } /** - * The TaskManager has some useful methods for doing things asynchronously + * The TaskManager has some useful methods for doing things asynchronously. * * @return TaskManager */ @@ -75,26 +76,15 @@ public class FaweAPI { return TaskManager.IMP; } -// /** -// * Add a custom transform for use in -// * -// * @param methods The class with a bunch of transform methods -// * @return true if the transform was registered -// * @see com.sk89q.worldedit.command.TransformCommands -// */ -// public static boolean registerTransforms(Object methods) { -// DefaultTransformParser parser = Fawe.get().getTransformParser(); -// if (parser != null) parser.register(methods); -// return parser != null; -// } - /** - * You can either use a IQueueExtent or an EditSession to change blocks
- * - The IQueueExtent skips a bit of overhead so it's marginally faster
- * - The WorldEdit EditSession can do a lot more
- * Remember to commit when you're done!
+ * You can either use a {@code IQueueExtent} or an {@code EditSession} to change blocks. * - * @param world The name of the world + *

+ * The {@link IQueueExtent} skips a bit of overhead, so it is marginally faster. {@link + * EditSession} can do a lot more. Remember to commit when you are done! + *

+ * + * @param world The name of the world * @param autoQueue If it should start dispatching before you enqueue it. * @return the queue extent */ @@ -118,10 +108,10 @@ public class FaweAPI { } /** - * Upload the clipboard to the configured web interface + * Upload the clipboard to the configured web interface. * * @param clipboard The clipboard (may not be null) - * @param format The format to use (some formats may not be supported) + * @param format The format to use (some formats may not be supported) * @return The download URL or null */ public static URL upload(final Clipboard clipboard, final ClipboardFormat format) { @@ -129,7 +119,7 @@ public class FaweAPI { } /** - * Just forwards to ClipboardFormat.SCHEMATIC.load(file) + * Just forwards to ClipboardFormat.SCHEMATIC.load(file). * * @param file the file to load * @return a clipboard containing the schematic @@ -149,7 +139,7 @@ public class FaweAPI { } /** - * Check if the server has more than the configured low memory threshold + * Check if the server has more than the configured low memory threshold. * * @return True if the server has limited memory */ @@ -158,28 +148,26 @@ public class FaweAPI { } /** - * Get a player's allowed WorldEdit region - * - * @param player - * @return + * Get a player's allowed WorldEdit region. */ public static Region[] getRegions(Player player) { return WEManager.IMP.getMask(player); } /** - * Cancel the edit with the following extent
- * - The extent must be the one being used by an EditSession, otherwise an error may be thrown
- * - Insert an extent into the EditSession using the EditSessionEvent: http://wiki.sk89q.com/wiki/WorldEdit/API/Hooking_EditSession
+ * Cancel the edit with the following extent. * - * @param extent - * @param reason - * @see EditSession#getRegionExtent() To get the FaweExtent for an EditSession + *

+ * The extent must be the one being used by an EditSession, otherwise an error will be thrown. + * Insert an extent into the EditSession using the EditSessionEvent. + *

+ * + * @see EditSession#getRegionExtent() How to get the FaweExtent for an EditSession */ public static void cancelEdit(AbstractDelegateExtent extent, Component reason) { try { WEManager.IMP.cancelEdit(extent, new FaweException(reason)); - } catch (WorldEditException ignore) { + } catch (WorldEditException ignored) { } } @@ -188,10 +176,7 @@ public class FaweAPI { } /** - * Get the DiskStorageHistory object representing a File - * - * @param file - * @return + * Get the DiskStorageHistory object representing a File. */ public static DiskStorageHistory getChangeSetFromFile(File file) { if (!file.exists() || file.isDirectory()) { @@ -200,7 +185,7 @@ public class FaweAPI { if (Settings.IMP.HISTORY.USE_DISK) { throw new IllegalArgumentException("History on disk not enabled!"); } - if (!file.getName().toLowerCase().endsWith(".bd")) { + if (!file.getName().toLowerCase(Locale.ROOT).endsWith(".bd")) { throw new IllegalArgumentException("Not a BD file!"); } String[] path = file.getPath().split(File.separator); @@ -223,16 +208,18 @@ public class FaweAPI { } /** - * Used in the RollBack to generate a list of DiskStorageHistory objects
- * - Note: An edit outside the radius may be included if it overlaps with an edit inside that depends on it. + * Used in the rollback to generate a list of {@link DiskStorageHistory} objects. * - * @param origin - The origin location - * @param user - The uuid (may be null) - * @param radius - The radius from the origin of the edit + * @param origin - The origin location + * @param user - The uuid (may be null) + * @param radius - The radius from the origin of the edit * @param timediff - The max age of the file in milliseconds - * @param shallow - If shallow is true, FAWE will only read the first Settings.IMP.BUFFER_SIZE bytes to obtain history info
- * Reading only part of the file will result in unreliable bounds info for large edits + * @param shallow - If shallow is true, FAWE will only read the first {@link + * Settings.HISTORY#BUFFER_SIZE} bytes to obtain history info * @return a list of DiskStorageHistory Objects + * @apiNote An edit outside the radius may be included if it overlaps with an edit inside + * that depends on it. Reading only part of the file will result in unreliable bounds info + * for large edits. */ public static List getBDFiles(Location origin, UUID user, int radius, long timediff, boolean shallow) { Extent extent = origin.getExtent(); @@ -312,35 +299,19 @@ public class FaweAPI { /** * The DiskStorageHistory class is what FAWE uses to represent the undo on disk. * - * @param world - * @param uuid - * @param index - * @return - * @see DiskStorageHistory#toEditSession(Player) */ public static DiskStorageHistory getChangeSetFromDisk(World world, UUID uuid, int index) { return new DiskStorageHistory(world, uuid, index); } /** - * Compare two versions + * Fix the lighting in a selection. This is a multi-step process as outlined below. * - * @param version - * @param major - * @param minor - * @param minor2 - * @return true if version is >= major, minor, minor2 - */ - public static boolean checkVersion(final int[] version, final int major, final int minor, final int minor2) { - return (version[0] > major) || ((version[0] == major) && (version[1] > minor)) || ((version[0] == major) && (version[1] == minor) && (version[2] >= minor2)); - } - - - /** - * Fix the lighting in a selection
- * - First removes all lighting, then relights - * - Relights in parallel (if enabled) for best performance
- * - Also resends chunks
+ *
    + *
  1. Removes all lighting, then relights.
  2. + *
  3. Relights in parallel (if enabled) for best performance.
  4. + *
  5. Resends the chunks to the client.
  6. + *
* * @param world World to relight in * @param selection Region to relight @@ -395,26 +366,19 @@ public class FaweAPI { } /** - * Have a task run when the server is low on memory (configured threshold) - * - * @param run + * Runs a task when the server is low on memory. */ public static void addMemoryLimitedTask(Runnable run) { MemUtil.addMemoryLimitedTask(run); } /** - * Have a task run when the server is no longer low on memory (configured threshold) - * - * @param run + * Runs a task when the server is no longer low on memory. */ public static void addMemoryPlentifulTask(Runnable run) { MemUtil.addMemoryPlentifulTask(run); } - /** - * @return Map of translation ket to value - */ public static Map getTranslations(Locale locale) { return WorldEdit.getInstance().getTranslationManager().getTranslationMap(locale); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/FaweCache.java b/worldedit-core/src/main/java/com/boydti/fawe/FaweCache.java index 27544b581..31ce66af6 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/FaweCache.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/FaweCache.java @@ -312,8 +312,6 @@ public enum FaweCache implements Trimable { /** * Convert raw int array to unstretched palette (1.16) - * @param layerOffset - * @param blocks * @return palette */ public Palette toPaletteUnstretched(int layerOffset, int[] blocks) { @@ -518,7 +516,9 @@ public enum FaweCache implements Trimable { } list.add(tag); } - if (clazz == null) clazz = EndTag.class; + if (clazz == null) { + clazz = EndTag.class; + } return new ListTag(clazz, list); } @@ -532,7 +532,9 @@ public enum FaweCache implements Trimable { } list.add(tag); } - if (clazz == null) clazz = EndTag.class; + if (clazz == null) { + clazz = EndTag.class; + } return new ListTag(clazz, list); } @@ -543,9 +545,9 @@ public enum FaweCache implements Trimable { int nThreads = Settings.IMP.QUEUE.PARALLEL_THREADS; ArrayBlockingQueue queue = new ArrayBlockingQueue<>(nThreads); return new ThreadPoolExecutor(nThreads, nThreads, - 0L, TimeUnit.MILLISECONDS, queue - , Executors.defaultThreadFactory(), - new ThreadPoolExecutor.CallerRunsPolicy()) { + 0L, TimeUnit.MILLISECONDS, queue, + Executors.defaultThreadFactory(), + new ThreadPoolExecutor.CallerRunsPolicy()) { protected void afterExecute(Runnable r, Throwable t) { try { super.afterExecute(r, t); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/FaweVersion.java b/worldedit-core/src/main/java/com/boydti/fawe/FaweVersion.java index 3c4f08062..01a16086a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/FaweVersion.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/FaweVersion.java @@ -1,7 +1,11 @@ package com.boydti.fawe; public class FaweVersion { - public final int year, month, day, hash, build; + public final int year; + public final int month; + public final int day; + public final int hash; + public final int build; public FaweVersion(int year, int month, int day, int hash, int build) { this.year = year; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/CombinedBlocks.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/CombinedBlocks.java index b2bcaa9dc..61917bea1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/CombinedBlocks.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/CombinedBlocks.java @@ -18,8 +18,8 @@ public class CombinedBlocks implements IBlocks { private final int addMask; /** - * @param secondary - * @param primary + * TODO Add a constructor here to satisfy checkstyle. + * * @param addMask - bitMask for force sending sections, else 0 to send the primary ones */ public CombinedBlocks(IBlocks secondary, IBlocks primary, int addMask) { @@ -92,11 +92,15 @@ public class CombinedBlocks implements IBlocks { BlockVector3 pos = entry.getKey(); BlockState block = primary.getBlock(pos.getX(), pos.getY(), pos.getZ()); if (block.getBlockType() == BlockTypes.__RESERVED__) { - if (copy == null) copy = new HashMap<>(tiles); + if (copy == null) { + copy = new HashMap<>(tiles); + } copy.put(pos, entry.getValue()); } } - if (copy != null) return copy; + if (copy != null) { + return copy; + } } } return tiles; @@ -116,8 +120,12 @@ public class CombinedBlocks implements IBlocks { Set joined = primary.getEntities(); if (primary != secondary) { Set ents2 = secondary.getEntities(); - if (joined.isEmpty()) return ents2; - if (ents2.isEmpty()) return joined; + if (joined.isEmpty()) { + return ents2; + } + if (ents2.isEmpty()) { + return joined; + } joined = new HashSet<>(joined); joined.addAll(ents2); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/IBatchProcessor.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/IBatchProcessor.java index 33d8afd5c..25f8e6146 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/IBatchProcessor.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/IBatchProcessor.java @@ -15,12 +15,9 @@ import java.util.concurrent.Future; import java.util.function.Function; public interface IBatchProcessor { + /** - * Process a chunk that has been set - * @param chunk - * @param get - * @param set - * @return + * Process a chunk that has been set. */ IChunkSet processSet(IChunk chunk, IChunkGet get, IChunkSet set); @@ -31,18 +28,13 @@ public interface IBatchProcessor { } /** - * Convert this processor into an Extent based processor instead of a queue batch based on - * @param child - * @return + * Convert this processor into an Extent based processor instead of a queue batch based on. */ @Nullable Extent construct(Extent child); /** - * Utility method to trim a chunk based on min and max Y - * @param set - * @param minY - * @param maxY + * Utility method to trim a chunk based on min and max Y. * @return false if chunk is empty of blocks */ default boolean trimY(IChunkSet set, int minY, int maxY) { @@ -52,7 +44,9 @@ public interface IBatchProcessor { if (layer == minLayer) { char[] arr = set.load(layer); int index = (minY & 15) << 8; - for (int i = 0; i < index; i++) arr[i] = 0; + for (int i = 0; i < index; i++) { + arr[i] = 0; + } set.setBlocks(layer, arr); } else { set.setBlocks(layer, null); @@ -65,7 +59,9 @@ public interface IBatchProcessor { if (layer == minLayer) { char[] arr = set.load(layer); int index = ((maxY + 1) & 15) << 8; - for (int i = index; i < arr.length; i++) arr[i] = 0; + for (int i = index; i < arr.length; i++) { + arr[i] = 0; + } set.setBlocks(layer, arr); } else { set.setBlocks(layer, null); @@ -91,9 +87,8 @@ public interface IBatchProcessor { } /** - * Utility method to trim entity and blocks with a provided contains function - * @param set - * @param contains + * Utility method to trim entity and blocks with a provided contains function. + * * @return false if chunk is empty of NBT */ default boolean trimNBT(IChunkSet set, Function contains) { @@ -110,9 +105,7 @@ public interface IBatchProcessor { } /** - * Join two processors and return the result - * @param other - * @return + * Join two processors and return the result. */ default IBatchProcessor join(IBatchProcessor other) { return MultiBatchProcessor.of(this, other); @@ -122,13 +115,11 @@ public interface IBatchProcessor { return MultiBatchProcessor.of(this, other); } - default void flush() {} + default void flush() { + } /** - * Return a new processor after removing all are instances of a specified class - * @param clazz - * @param - * @return + * Return a new processor after removing all are instances of a specified class. */ default IBatchProcessor remove(Class clazz) { if (clazz.isInstance(this)) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/IBlocks.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/IBlocks.java index c89c71adb..eda96ee39 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/IBlocks.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/IBlocks.java @@ -19,7 +19,7 @@ import java.util.Set; import java.util.stream.IntStream; /** - * A shared interface for IGetBlocks and ISetBlocks + * A shared interface for IGetBlocks and ISetBlocks. */ public interface IBlocks extends Trimable { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/IChunkSet.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/IChunkSet.java index 5dd95da55..1395fa4af 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/IChunkSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/IChunkSet.java @@ -75,16 +75,16 @@ public interface IChunkSet extends IBlocks, OutputExtent { } // Default to avoid tricky child classes. We only need it in a few cases anyway. - default void setFastMode(boolean fastMode){} + default void setFastMode(boolean fastMode) {} default boolean isFastMode() { return false; } // Allow setting for bitmask for flushing lighting. Default to avoid tricky child classes. - default void setBitMask(int bitMask){} + default void setBitMask(int bitMask) {} - default int getBitMask(){ + default int getBitMask() { return -1; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/IQueueExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/IQueueExtent.java index c79eef5fb..28b41a2e4 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/IQueueExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/IQueueExtent.java @@ -49,16 +49,16 @@ public interface IQueueExtent extends Flushable, Trimable, ICh void init(Extent extent, IChunkCache get, IChunkCache set); /** - * Get the cached get object - * - Faster than getting it using NMS and allows for wrapping - * @param x - * @param z + * Get the cached get object. This is faster than getting the object using NMS and allows for + * wrapping. + * @param chunkX + * @param chunkZ * @return */ - IChunkGet getCachedGet(@Range(from = 0, to = 15) int x, @Range(from = 0, to = 15) int z); + IChunkGet getCachedGet(@Range(from = 0, to = 15) int chunkX, @Range(from = 0, to = 15) int chunkZ); /** - * Get the cached chunk set object + * Get the cached chunk set object. * @param chunkX * @param chunkZ * @return @@ -88,19 +88,18 @@ public interface IQueueExtent extends Flushable, Trimable, ICh boolean isFastMode(); /** - * Create a new root IChunk object
- Full chunks will be reused, so a more optimized chunk - * can be returned in that case
- Don't wrap the chunk, that should be done in {@link - * #wrap(T)} + * Create a new root IChunk object. Full chunks will be reused, so a more optimized chunk can be + * returned in that case. * + * @apiNote Don't wrap the chunk, that should be done in {@link IQueueExtent#wrap(IChunk)} * @param isFull true if a more optimized chunk should be returned * @return a more optimized chunk object */ T create(boolean isFull); /** - * Wrap the chunk object (i.e., for region restrictions / limits etc.) + * Wrap the chunk object (i.e., for region restrictions / limits etc.). * - * @param root * @return wrapped chunk */ default T wrap(T root) { @@ -115,15 +114,15 @@ public interface IQueueExtent extends Flushable, Trimable, ICh } /** - * Flush all changes to the world - Best to call this async so it doesn't hang the server + * Flush all changes to the world. + * @apiNote Best to call this async, so it doesn't hang the server. */ @Override void flush(); /** - * A filter block is used to iterate over blocks / positions - * - Essentially combines BlockVector3, Extent and BlockState functions in a way that avoids lookups - * @return + * A filter block is used to iterate over blocks / positions. Essentially combines BlockVector3, + * Extent and BlockState functions in a way that avoids lookups. */ ChunkFilterBlock initFilterBlock(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/Trimable.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/Trimable.java index c513a76f8..7ed498687 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/Trimable.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/Trimable.java @@ -1,19 +1,20 @@ package com.boydti.fawe.beta; /** - * Interface for objects that can be trimmed (memory related)
- Trimming will reduce its memory - * footprint + * Interface for objects that can be trimmed (memory related). Trimming will reduce its memory + * footprint. */ public interface Trimable { /** - * Trims the object, reducing its memory footprint + * Trims the object, reducing its memory footprint. * - * @param aggressive if trimming should be aggressive e.g., Not return early when the first + * @param aggressive if trimming should be aggressive e.g., Not returning early when the first * element cannot be trimmed * @return if this object is empty at the end of the trim, and can therefore be deleted */ boolean trim(boolean aggressive); - default void recycle() {} + default void recycle() { + } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/BitSetBlocks.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/BitSetBlocks.java index ae28aac4e..10c5e78d9 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/BitSetBlocks.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/BitSetBlocks.java @@ -68,19 +68,33 @@ public class BitSetBlocks implements IChunkSet { return false; } - @Override public void setBlockLight(int x, int y, int z, int value) {} + @Override + public void setBlockLight(int x, int y, int z, int value) { + } - @Override public void setSkyLight(int x, int y, int z, int value) {} + @Override + public void setSkyLight(int x, int y, int z, int value) { + } - @Override public void setHeightMap(HeightMapType type, int[] heightMap) {} + @Override + public void setHeightMap(HeightMapType type, int[] heightMap) { + } - @Override public void setLightLayer(int layer, char[] toSet) {} + @Override + public void setLightLayer(int layer, char[] toSet) { + } - @Override public void setSkyLightLayer(int layer, char[] toSet) {} + @Override + public void setSkyLightLayer(int layer, char[] toSet) { + } - @Override public void removeSectionLighting(int layer, boolean sky) {} + @Override + public void removeSectionLighting(int layer, boolean sky) { + } - @Override public void setFullBright(int layer) {} + @Override + public void setFullBright(int layer) { + } @Override public void setEntity(CompoundTag tag) { @@ -134,11 +148,13 @@ public class BitSetBlocks implements IChunkSet { return null; } - @Override public char[][] getLight() { + @Override + public char[][] getLight() { return new char[0][]; } - @Override public char[][] getSkyLight() { + @Override + public char[][] getSkyLight() { return new char[0][]; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/CharBlocks.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/CharBlocks.java index 15ce82298..834fca3ae 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/CharBlocks.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/CharBlocks.java @@ -139,7 +139,7 @@ public abstract class CharBlocks implements IBlocks { sections[layer].set(this, layer, index, value); } - public static abstract class Section { + public abstract static class Section { public abstract char[] get(CharBlocks blocks, @Range(from = 0, to = 15) int layer); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/CharSetBlocks.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/CharSetBlocks.java index 8f7dffee3..fcb899b58 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/CharSetBlocks.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/CharSetBlocks.java @@ -24,6 +24,7 @@ import java.util.stream.IntStream; public class CharSetBlocks extends CharBlocks implements IChunkSet { private static final Pool POOL = FaweCache.IMP.registerPool(CharSetBlocks.class, CharSetBlocks::new, Settings.IMP.QUEUE.POOL); + public static CharSetBlocks newInstance() { return POOL.poll(); } @@ -38,7 +39,8 @@ public class CharSetBlocks extends CharBlocks implements IChunkSet { private boolean fastMode = false; private int bitMask = -1; - private CharSetBlocks() {} + private CharSetBlocks() { + } @Override public void recycle() { @@ -52,7 +54,9 @@ public class CharSetBlocks extends CharBlocks implements IChunkSet { @Override public BiomeType getBiomeType(int x, int y, int z) { - if (biomes == null) return null; + if (biomes == null) { + return null; + } return biomes[(z << 4) | x]; } @@ -213,7 +217,7 @@ public class CharSetBlocks extends CharBlocks implements IChunkSet { @Override public boolean setBiome(BlockVector3 position, BiomeType biome) { - return setBiome(position.getX(),position.getY(), position.getZ(), biome); + return setBiome(position.getX(), position.getY(), position.getZ(), biome); } @Override diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/FallbackChunkGet.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/FallbackChunkGet.java index 1a6ab8612..3babb36c8 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/FallbackChunkGet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/blocks/FallbackChunkGet.java @@ -24,7 +24,8 @@ import java.util.UUID; import java.util.concurrent.Future; public class FallbackChunkGet implements IChunkGet { - private final int bx, bz; + private final int bx; + private final int bz; private final Extent extent; public FallbackChunkGet(Extent extent, int chunkX, int chunkZ) { @@ -32,6 +33,7 @@ public class FallbackChunkGet implements IChunkGet { this.bx = chunkX << 4; this.bz = chunkZ << 4; } + @Override public BaseBlock getFullBlock(int x, int y, int z) { return extent.getFullBlock(bx + x, y, bz + z); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/cache/ChunkCache.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/cache/ChunkCache.java index e4636899f..e34114a0f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/cache/ChunkCache.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/cache/ChunkCache.java @@ -20,7 +20,7 @@ public class ChunkCache implements IChunkCache { } /** - * Get or create the IGetBlocks + * Get or create the IGetBlocks. * * @return cached IGetBlocks */ diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/cache/preloader/AsyncPreloader.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/cache/preloader/AsyncPreloader.java index 31745548d..a489b739d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/cache/preloader/AsyncPreloader.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/cache/preloader/AsyncPreloader.java @@ -45,7 +45,9 @@ public class AsyncPreloader implements Preloader, Runnable { @Override public void update(Player player) { LocalSession session = WorldEdit.getInstance().getSessionManager().getIfPresent(player); - if (session == null) return; + if (session == null) { + return; + } World world = player.getWorld(); MutablePair> existing = cancelAndGet(player); try { @@ -67,7 +69,8 @@ public class AsyncPreloader implements Preloader, Runnable { update.notify(); } } - } catch (IncompleteRegionException ignore){} + } catch (IncompleteRegionException ignored) { + } } @Override diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/chunk/ChunkHolder.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/chunk/ChunkHolder.java index 50db1eb2f..1ca097b80 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/chunk/ChunkHolder.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/chunk/ChunkHolder.java @@ -28,7 +28,7 @@ import java.util.UUID; import java.util.concurrent.Future; /** - * An abstract {@link IChunk} class that implements basic get/set blocks + * An abstract {@link IChunk} class that implements basic get/set blocks. */ @SuppressWarnings("rawtypes") public class ChunkHolder> implements IQueueChunk { @@ -189,7 +189,7 @@ public class ChunkHolder> implements IQueueChunk { } @Override - public void setFullBright(ChunkHolder chunk, int layer){ + public void setFullBright(ChunkHolder chunk, int layer) { chunk.chunkSet.setFullBright(layer); } @@ -317,7 +317,7 @@ public class ChunkHolder> implements IQueueChunk { } @Override - public void setFullBright(ChunkHolder chunk, int layer){ + public void setFullBright(ChunkHolder chunk, int layer) { chunk.getOrCreateSet(); chunk.delegate = BOTH; chunk.setFullBright(layer); @@ -425,7 +425,7 @@ public class ChunkHolder> implements IQueueChunk { } @Override - public void setFullBright(ChunkHolder chunk, int layer){ + public void setFullBright(ChunkHolder chunk, int layer) { chunk.chunkSet.setFullBright(layer); } @@ -603,7 +603,7 @@ public class ChunkHolder> implements IQueueChunk { } @Override - public void setFullBright(ChunkHolder chunk, int layer){ + public void setFullBright(ChunkHolder chunk, int layer) { chunk.getOrCreateSet(); chunk.delegate = SET; chunk.setFullBright(layer); @@ -812,7 +812,7 @@ public class ChunkHolder> implements IQueueChunk { } /** - * Get the extent this chunk is in + * Get the extent this chunk is in. */ public IQueueExtent getExtent() { return extent; @@ -911,6 +911,7 @@ public class ChunkHolder> implements IQueueChunk { public interface IBlockDelegate { > IChunkGet get(ChunkHolder chunk); + IChunkSet set(ChunkHolder chunk); boolean setBiome(ChunkHolder chunk, int x, int y, int z, BiomeType biome); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/LinkedFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/LinkedFilter.java index c749fa6e7..a1bb96611 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/LinkedFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/LinkedFilter.java @@ -14,12 +14,12 @@ public final class LinkedFilter extends Dele private final S child; - public LinkedFilter(T parent, S child){ + public LinkedFilter(T parent, S child) { super(parent); this.child = child; } - public S getChild(){ + public S getChild() { return this.child; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/MaskFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/MaskFilter.java index eaca8a67a..ab274dee7 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/MaskFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/MaskFilter.java @@ -56,7 +56,7 @@ public class MaskFilter extends DelegateFilter { * * @return number of blocks which passed the Mask test and were applied to */ - public int getBlocksApplied(){ + public int getBlocksApplied() { return this.changes.get(); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/AbstractFilterBlock.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/AbstractFilterBlock.java index f56b1018c..414dc664d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/AbstractFilterBlock.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/AbstractFilterBlock.java @@ -54,11 +54,6 @@ public abstract class AbstractFilterBlock extends FilterBlock { return getFullBlock().toBlockState(); } - @Override - public void setBlock(BlockState state) { - setFullBlock(state.toBaseBlock(getBlock().getNbtData())); - } - @Override public CompoundTag getNbtData() { return getFullBlock().getNbtData(); @@ -79,6 +74,11 @@ public abstract class AbstractFilterBlock extends FilterBlock { return BlockVector3.at(getX(), getY(), getZ()); } + @Override + public void setBlock(BlockState state) { + setFullBlock(state.toBaseBlock(getBlock().getNbtData())); + } + @Override public > boolean setBlock(int x, int y, int z, T block) throws WorldEditException { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/ArrayFilterBlock.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/ArrayFilterBlock.java index ca4594151..af0fc9bf2 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/ArrayFilterBlock.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/ArrayFilterBlock.java @@ -16,8 +16,11 @@ public class ArrayFilterBlock extends AbstractExtentFilterBlock { private final char[] blocks; private final byte[] heights; private final int yOffset; - private final int width, length; - private int x, z, index; + private final int width; + private final int length; + private int x; + private int z; + private int index; public ArrayFilterBlock(Extent extent, char[] blocks, byte[] heights, int width, int length, int yOffset) { @@ -51,11 +54,6 @@ public class ArrayFilterBlock extends AbstractExtentFilterBlock { return BlockTypesCache.states[getOrdinal()]; } - @Override - public void setBlock(BlockState state) { - blocks[index] = state.getOrdinalChar(); - } - @Override public BaseBlock getFullBlock() { return getBlock().toBaseBlock(); @@ -90,14 +88,19 @@ public class ArrayFilterBlock extends AbstractExtentFilterBlock { return z; } + @Override + public void setBlock(BlockState state) { + blocks[index] = state.getOrdinalChar(); + } + @Override public > boolean setBlock(int x, int y, int z, T block) throws WorldEditException { - return getExtent().setBlock(x,y, z, block); + return getExtent().setBlock(x, y, z, block); } @Override public boolean setBiome(int x, int y, int z, BiomeType biome) { - return getExtent().setBiome(x,y, z,biome); + return getExtent().setBiome(x, y, z, biome); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/CharFilterBlock.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/CharFilterBlock.java index 722671857..b07db6013 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/CharFilterBlock.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/CharFilterBlock.java @@ -34,10 +34,20 @@ public class CharFilterBlock extends ChunkFilterBlock { private CharGetBlocks get; private IChunkSet set; private char[] getArr; - private @Nullable char[] setArr; + @Nullable + private char[] setArr; private SetDelegate delegate; // local - private int layer, index, x, y, z, xx, yy, zz, chunkX, chunkZ; + private int layer; + private int index; + private int x; + private int y; + private int z; + private int xx; + private int yy; + private int zz; + private int chunkX; + private int chunkZ; public CharFilterBlock(Extent extent) { super(extent); @@ -107,8 +117,8 @@ public class CharFilterBlock extends ChunkFilterBlock { } @Override - public void filter(Filter filter, int yStart, int yEnd) { - for (y = yStart, index = yStart << 8; y <= yEnd; y++) { + public void filter(Filter filter, int startY, int endY) { + for (y = startY, index = startY << 8; y <= endY; y++) { for (z = 0; z < 16; z++) { for (x = 0; x < 16; x++, index++) { filter.applyBlock(this); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/ChunkFilterBlock.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/ChunkFilterBlock.java index 8a0aea0c2..ec50201a7 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/ChunkFilterBlock.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/ChunkFilterBlock.java @@ -23,21 +23,12 @@ public abstract class ChunkFilterBlock extends AbstractExtentFilterBlock { } /** - * Initialize with chunk coordinates - * - The layer must also be initialized - * @param chunkX - * @param chunkZ - * @return + * Initialize with chunk coordinates. The layer must also be initialized. */ public abstract ChunkFilterBlock initChunk(int chunkX, int chunkZ); /** - * Initialize a chunk layer - * - The chunk coordinates must also be initialized first - * @param iget - * @param iset - * @param layer - * @return + * Initialize a chunk layer. the Chunk coordinates need to be initialized first. */ public abstract ChunkFilterBlock initLayer(IBlocks iget, IChunkSet iset, int layer); @@ -46,55 +37,33 @@ public abstract class ChunkFilterBlock extends AbstractExtentFilterBlock { /** - * Filter a single block - * @param filter - * @param x - * @param y - * @param z + * Filter a single block. */ public abstract void filter(Filter filter, int x, int y, int z); /** - * Filter a cuboid region - * @param filter - * @param minX - * @param minY - * @param minZ - * @param maxX - * @param maxY - * @param maxZ + * Filter a cuboid region. */ public abstract void filter(Filter filter, int minX, int minY, int minZ, int maxX, int maxY, int maxZ); /** - * Filter everything in the layer - * @param filter + * Filter everything in the layer. */ public abstract void filter(Filter filter); /** - * Filter everything between y layers - * @param filter - * @param yStart - * @param yEnd + * Filter everything between y layers. */ - public abstract void filter(Filter filter, int yStart, int yEnd); + public abstract void filter(Filter filter, int startY, int endY); /** - * Filter with a region - * @param filter - * @param region + * Filter with a region. */ public abstract void filter(Filter filter, Region region); /** - * Filter with a chunk object - * @param chunk - * @param get - * @param set - * @param filter - * @return + * Filter with a chunk object. */ public final IChunkSet filter(IChunk chunk, IChunkGet get, IChunkSet set, Filter filter) { initChunk(chunk.getX(), chunk.getZ()); @@ -108,14 +77,7 @@ public abstract class ChunkFilterBlock extends AbstractExtentFilterBlock { } /** - * Filter a chunk with a region / filter - * @param chunk - * @param get - * @param set - * @param filter - * @param region - * @param full - * @return + * Filter a chunk with a region / filter. */ public final IChunkSet filter(IChunk chunk, IChunkGet get, IChunkSet set, Filter filter, Region region, boolean full) { if (region != null) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/SingleFilterBlock.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/SingleFilterBlock.java index 4c2e41244..c15f4ed74 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/SingleFilterBlock.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/filter/block/SingleFilterBlock.java @@ -4,7 +4,9 @@ import com.sk89q.worldedit.world.block.BaseBlock; public class SingleFilterBlock extends AbstractSingleFilterBlock { - private int x, y, z; + private int x; + private int y; + private int z; public SingleFilterBlock init(int x, int y, int z, BaseBlock block) { this.x = x; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/lighting/NMSRelighter.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/lighting/NMSRelighter.java index 7b55ce48d..b10281e29 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/lighting/NMSRelighter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/lighting/NMSRelighter.java @@ -28,6 +28,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; @@ -281,7 +282,7 @@ public class NMSRelighter implements Relighter { } int lightLevel = iChunk.getEmmittedLight(node.getX() & 15, node.getY(), node.getZ() & 15); BlockState state = this.queue.getBlock(node.getX(), node.getY(), node.getZ()); - String id = state.getBlockType().getId().toLowerCase(); + String id = state.getBlockType().getId().toLowerCase(Locale.ROOT); if (lightLevel <= 1) { continue; } @@ -319,7 +320,7 @@ public class NMSRelighter implements Relighter { if (!(checkStairEast(state) && isStairOrTrueTop(state, top) && isSlabOrTrueValue(state, top ? "top" : "bottom"))) { break east; } - if (!state.getBlockType().getId().toLowerCase().contains("stair")) { + if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) { this.computeSpreadBlockLight(x + 1, y, z, currentLight, queue, visited); break east; } @@ -370,7 +371,7 @@ public class NMSRelighter implements Relighter { if (!(checkStairWest(state) && isStairOrTrueTop(state, top) && isSlabOrTrueValue(state, top ? "top" : "bottom"))) { break west; } - if (!state.getBlockType().getId().toLowerCase().contains("stair")) { + if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) { this.computeSpreadBlockLight(x - 1, y, z, currentLight, queue, visited); break west; } @@ -421,7 +422,7 @@ public class NMSRelighter implements Relighter { if (!(checkStairSouth(state) && isStairOrTrueTop(state, top) && isSlabOrTrueValue(state, top ? "top" : "bottom"))) { break south; } - if (!state.getBlockType().getId().toLowerCase().contains("stair")) { + if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) { this.computeSpreadBlockLight(x, y, z + 1, currentLight, queue, visited); break south; } @@ -472,7 +473,7 @@ public class NMSRelighter implements Relighter { if (!(checkStairNorth(state) && isStairOrTrueTop(state, top) && isSlabOrTrueValue(state, top ? "top" : "bottom"))) { break north; } - if (!state.getBlockType().getId().toLowerCase().contains("stair")) { + if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) { this.computeSpreadBlockLight(x, y, z - 1, currentLight, queue, visited); break north; } @@ -611,7 +612,7 @@ public class NMSRelighter implements Relighter { } private boolean checkStairNorth(BlockState state) { - if (!state.getBlockType().getId().toLowerCase().contains("stair")) { + if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) { return true; } Direction direction = getStairDir(state); @@ -629,7 +630,7 @@ public class NMSRelighter implements Relighter { } private boolean checkStairSouth(BlockState state) { - if (!state.getBlockType().getId().toLowerCase().contains("stair")) { + if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) { return true; } Direction direction = getStairDir(state); @@ -647,7 +648,7 @@ public class NMSRelighter implements Relighter { } private boolean checkStairEast(BlockState state) { - if (!state.getBlockType().getId().toLowerCase().contains("stair")) { + if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) { return true; } Direction direction = getStairDir(state); @@ -665,7 +666,7 @@ public class NMSRelighter implements Relighter { } private boolean checkStairWest(BlockState state) { - if (!state.getBlockType().getId().toLowerCase().contains("stair")) { + if (!state.getBlockType().getId().toLowerCase(Locale.ROOT).contains("stair")) { return true; } Direction direction = getStairDir(state); @@ -687,7 +688,7 @@ public class NMSRelighter implements Relighter { } private String getStairShape(BlockState state) { - return state.getState(stairShape).toLowerCase(); + return state.getState(stairShape).toLowerCase(Locale.ROOT); } private boolean isStairOrTrueTop(BlockState state, boolean top) { @@ -784,8 +785,9 @@ public class NMSRelighter implements Relighter { public void fixBlockLighting() { synchronized (lightQueue) { - while (!lightLock.compareAndSet(false, true)) + while (!lightLock.compareAndSet(false, true)) { ; + } try { updateBlockLight(this.lightQueue); } finally { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/lighting/Relighter.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/lighting/Relighter.java index 966d944b2..ad60cfa94 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/lighting/Relighter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/lighting/Relighter.java @@ -3,7 +3,7 @@ package com.boydti.fawe.beta.implementation.lighting; public interface Relighter { /** - * Add a chunk to be relit when {@link Relighter#removeLighting} etc are called + * Add a chunk to be relit when {@link Relighter#removeLighting} etc are called. * * @param cx chunk x * @param cz chunk z @@ -14,7 +14,7 @@ public interface Relighter { boolean addChunk(int cx, int cz, byte[] skipReason, int bitmask); /** - * Add a block to be relit + * Add a block to be relit. * * @param x block x * @param y block y @@ -23,14 +23,14 @@ public interface Relighter { void addLightUpdate(int x, int y, int z); /** - * Safely? Fix block lighting + * Safely? Fix block lighting. * * @param sky whether to also relight sky light values */ void fixLightingSafe(boolean sky); /** - * Remove lighting and then relight safely + * Remove lighting and then relight safely. * * @param sky whether to also relight sky light values */ @@ -40,33 +40,33 @@ public interface Relighter { } /** - * Clear all chunks and blocks to be relit + * Clear all chunks and blocks to be relit. */ void clear(); /** - * Remove all block and sky light values (set to 0 light) in all chunks added to relighter + * Remove all block and sky light values (set to 0 light) in all chunks added to relighter. */ void removeLighting(); /** - * Fix block light values in all chunks added to relighter + * Fix block light values in all chunks added to relighter. */ void fixBlockLighting(); /** - * Fix sky light values in all chunks added to relighter + * Fix sky light values in all chunks added to relighter. */ void fixSkyLighting(); /** - * Are there any block or chunk added to be relit + * Are there any block or chunk added to be relit. * * @return is the relight stuff to be relit empty */ boolean isEmpty(); - public static class SkipReason { + class SkipReason { public static final byte NONE = 0; public static final byte AIR = 1; public static final byte SOLID = 2; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/packet/ChunkPacket.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/packet/ChunkPacket.java index d10eb55cc..7914b880d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/packet/ChunkPacket.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/packet/ChunkPacket.java @@ -116,8 +116,8 @@ public class ChunkPacket implements Function, Supplier { fos.writeVarInt(sectionBytes.length); fos.write(sectionBytes); // TODO entities / NBT -// Set entities = chunk.getEntities(); -// Map tiles = chunk.getTiles(); + //Set entities = chunk.getEntities(); + //Map tiles = chunk.getTiles(); fos.writeVarInt(0); // (Entities / NBT) return baos.toByteArray(); } catch (Throwable e) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/LimitExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/LimitExtent.java index 7ffb4201d..ee29dfbf5 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/LimitExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/LimitExtent.java @@ -573,7 +573,9 @@ public class LimitExtent extends AbstractDelegateExtent { @Deprecated public > boolean setBlock(BlockVector3 position, T block) throws WorldEditException { limit.THROW_MAX_CHANGES(); - if (block.hasNbtData()) limit.MAX_BLOCKSTATES(); + if (block.hasNbtData()) { + limit.MAX_BLOCKSTATES(); + } try { return super.setBlock(position, block); } catch (FaweException e) { @@ -587,7 +589,9 @@ public class LimitExtent extends AbstractDelegateExtent { @Override public > boolean setBlock(int x, int y, int z, T block) throws WorldEditException { limit.THROW_MAX_CHANGES(); - if (block.hasNbtData()) limit.MAX_BLOCKSTATES(); + if (block.hasNbtData()) { + limit.MAX_BLOCKSTATES(); + } try { return super.setBlock(x, y, z, block); } catch (FaweException e) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/MultiBatchProcessor.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/MultiBatchProcessor.java index 2e23cf8a6..2108c7a76 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/MultiBatchProcessor.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/MultiBatchProcessor.java @@ -33,7 +33,7 @@ public class MultiBatchProcessor implements IBatchProcessor { for (IBatchProcessor processor : processors) { if (processor instanceof MultiBatchProcessor) { list.addAll(Arrays.asList(((MultiBatchProcessor) processor).processors)); - } else if (!(processor instanceof EmptyBatchProcessor)){ + } else if (!(processor instanceof EmptyBatchProcessor)) { list.add(processor); } } @@ -154,7 +154,9 @@ public class MultiBatchProcessor implements IBatchProcessor { @Override public void flush() { - for (IBatchProcessor processor : this.processors) processor.flush(); + for (IBatchProcessor processor : this.processors) { + processor.flush(); + } } @Override diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/PersistentChunkSendProcessor.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/PersistentChunkSendProcessor.java index b9715c515..c2c4add4e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/PersistentChunkSendProcessor.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/processors/PersistentChunkSendProcessor.java @@ -44,7 +44,9 @@ public class PersistentChunkSendProcessor extends ChunkSendProcessor { current.put(pair, (Character) bitMask); if (previous != null) { Character lastValue = previous.remove(pair); - if (lastValue != null) bitMask |= lastValue; + if (lastValue != null) { + bitMask |= lastValue; + } } } return new CombinedBlocks(get, set, bitMask); @@ -56,7 +58,9 @@ public class PersistentChunkSendProcessor extends ChunkSendProcessor { } public void clear() { - if (queue == null) throw new IllegalStateException("Queue is not provided"); + if (queue == null) { + throw new IllegalStateException("Queue is not provided"); + } clear(current); current.clear(); queue = null; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/ParallelQueueExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/ParallelQueueExtent.java index 953ee7be3..e558e2cea 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/ParallelQueueExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/ParallelQueueExtent.java @@ -106,7 +106,8 @@ public class ParallelQueueExtent extends PassthroughExtent implements IQueueWrap while (true) { // Get the next chunk posWeakChunk - final int chunkX, chunkZ; + final int chunkX; + final int chunkZ; synchronized (chunksIter) { if (!chunksIter.hasNext()) { break; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/QueuePool.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/QueuePool.java index 25b51f528..61f0ad007 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/QueuePool.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/QueuePool.java @@ -21,7 +21,9 @@ public class QueuePool extends ConcurrentLinkedQueue implements Pool { @Override public void clear() { - if (!isEmpty()) super.clear(); + if (!isEmpty()) { + super.clear(); + } } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/SingleThreadQueueExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/SingleThreadQueueExtent.java index f8056de24..65b43a342 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/SingleThreadQueueExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/beta/implementation/queue/SingleThreadQueueExtent.java @@ -100,7 +100,9 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen * Resets the queue. */ protected synchronized void reset() { - if (!this.initialized) return; + if (!this.initialized) { + return; + } if (!this.chunks.isEmpty()) { for (IChunk chunk : this.chunks.values()) { chunk.recycle(); @@ -175,9 +177,9 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen if (Fawe.isMainThread()) { V result = (V)chunk.call(); - if (result == null){ + if (result == null) { return (V) (Future) Futures.immediateFuture(null); - }else{ + } else { return result; } } @@ -285,7 +287,9 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen while (!submissions.isEmpty()) { Future future = submissions.poll(); try { - while (future != null) future = (Future) future.get(); + while (future != null) { + future = (Future) future.get(); + } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } @@ -294,7 +298,9 @@ public class SingleThreadQueueExtent extends ExtentBatchProcessorHolder implemen for (int i = 0; i < overflow; i++) { Future first = submissions.poll(); try { - while (first != null) first = (Future) first.get(); + while (first != null) { + first = (Future) first.get(); + } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/AnvilCommands.java b/worldedit-core/src/main/java/com/boydti/fawe/command/AnvilCommands.java index 0530ecb3d..0eeab009d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/AnvilCommands.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/command/AnvilCommands.java @@ -158,13 +158,15 @@ public class AnvilCommands { name = "deleteallunvisited", aliases = {"delunvisited" }, desc = "Delete all chunks which haven't been occupied", - descFooter = "occupied for `age-ticks` (20t = 1s) and \n" + - "Have not been accessed since `file-duration` (ms) after creation and\n" + - "Have not been used in the past `chunk-inactivity` (ms)" + - "The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`" + descFooter = "occupied for `age-ticks` (20t = 1s) and \n" + + "Have not been accessed since `file-duration` (ms) after creation and\n" + + "Have not been used in the past `chunk-inactivity` (ms)" + + "The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`" ) @CommandPermissions("worldedit.anvil.deleteallunvisited") - public void deleteAllUnvisited(Player player, String folder, int inhabitedTicks, @Arg(desc = "int", def = "60000") int fileDurationMillis) throws WorldEditException { + public void deleteAllUnvisited(Player player, String folder, int inhabitedTicks, + @Arg(desc = "int", def = "60000") + int fileDurationMillis) throws WorldEditException { // DeleteUninhabitedFilter filter = new DeleteUninhabitedFilter(fileDurationMillis, inhabitedTicks, fileDurationMillis); TODO NOT IMPLEMENTED // DeleteUninhabitedFilter result = runWithWorld(player, folder, filter, true); // if (result != null) { @@ -176,14 +178,18 @@ public class AnvilCommands { name = "deleteallunclaimed", aliases = {"delallunclaimed" }, desc = "Delete all chunks which haven't been occupied", - descFooter = "Supports: WG, P2, GP:\n" + - "Delete all chunks which aren't claimed AND haven't been occupied for `age-ticks` (20t = 1s) and \n" + - "Have not been accessed since `file-duration` (ms) after creation and\n" + - "Have not been used in the past `chunk-inactivity` (ms)" + - "The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`" + descFooter = "Supports: WorldGuard, PlotSquared, GriefPrevention:\n" + + "Delete all chunks which aren't claimed AND haven't been occupied for `age-ticks` (20t = 1s) and \n" + + "Have not been accessed since `file-duration` (ms) after creation and\n" + + "Have not been used in the past `chunk-inactivity` (ms)" + + "The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`" ) @CommandPermissions("worldedit.anvil.deleteallunclaimed") - public void deleteAllUnclaimed(Player player, int inhabitedTicks, @Arg(desc = "int", def = "60000") int fileDurationMillis, @Switch(name = 'd', desc = "TODO") boolean debug) throws WorldEditException { + public void deleteAllUnclaimed(Player player, int inhabitedTicks, + @Arg(desc = "int", def = "60000") + int fileDurationMillis, + @Switch(name = 'd', desc = "The flag will debug the task") + boolean debug) throws WorldEditException { // String folder = player.getWorld().getName(); TODO NOT IMPLEMENTED // DeleteUnclaimedFilter filter = new DeleteUnclaimedFilter(player.getWorld(), fileDurationMillis, inhabitedTicks, fileDurationMillis); // if (debug) { @@ -198,15 +204,19 @@ public class AnvilCommands { @Command( name = "deleteunclaimed", desc = "Delete all chunks which haven't been occupied", - descFooter = "(Supports: WG, P2, GP):\n" + - "Is not claimed\n" + - "Has not been occupied for `age-ticks` (20t = 1s) and \n" + - "Have not been accessed since `file-duration` (ms) after creation and\n" + - "Have not been used in the past `chunk-inactivity` (ms)" + - "The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`" + descFooter = "(Supports: WorldGuard, PlotSquared, GriefPrevention):\n" + + "Is not claimed\n" + + "Has not been occupied for `age-ticks` (20t = 1s) and \n" + + "Have not been accessed since `file-duration` (ms) after creation and\n" + + "Have not been used in the past `chunk-inactivity` (ms)" + + "The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`" ) @CommandPermissions("worldedit.anvil.deleteunclaimed") - public void deleteUnclaimed(Player player, EditSession editSession, @Selection Region selection, int inhabitedTicks, @Arg(desc = "int", def = "60000") int fileDurationMillis, @Switch(name = 'd', desc = "TODO") boolean debug) throws WorldEditException { + public void deleteUnclaimed(Player player, EditSession editSession, @Selection Region selection, int inhabitedTicks, + @Arg(desc = "int", def = "60000") + int fileDurationMillis, + @Switch(name = 'd', desc = "The flag will debug the task") + boolean debug) throws WorldEditException { // DeleteUnclaimedFilter filter = new DeleteUnclaimedFilter(player.getWorld(), fileDurationMillis, inhabitedTicks, fileDurationMillis); TODO NOT IMPLEMENTED // if (debug) { // filter.enableDebug(); @@ -221,8 +231,8 @@ public class AnvilCommands { name = "deletealloldregions", aliases = {"deloldreg" }, desc = "Delete regions which haven't been accessed in a certain amount of time", - descFooter = "You can use seconds (s), minutes (m), hours (h), days (d), weeks (w), years (y)\n" + - "(months are not a unit of time) e.g., 8h5m12s\n" + descFooter = "You can use seconds (s), minutes (m), hours (h), days (d), weeks (w), years (y)\n" + + "(months are not a unit of time) e.g., 8h5m12s\n" ) @CommandPermissions("worldedit.anvil.deletealloldregions") public void deleteAllOldRegions(Player player, String folder, String time) throws WorldEditException { @@ -236,12 +246,13 @@ public class AnvilCommands { @Command( name = "trimallplots", - desc = "Trim chunks in a Plot World", descFooter = "Unclaimed chunks will be deleted\nUnmodified chunks will be deleted\n" ) @CommandPermissions("worldedit.anvil.trimallplots") - public void trimAllPlots(Player player, @Switch(name = 'v', desc = "Delete unvisited chunks") boolean deleteUnvisited) throws WorldEditException { + public void trimAllPlots(Player player, + @Switch(name = 'v', desc = "Delete unvisited chunks") + boolean deleteUnvisited) throws WorldEditException { // String folder = player.getWorld().getName(); TODO NOT IMPLEMENTED // int visitTime = deleteUnvisited ? 1 : -1; // PlotTrimFilter filter = new PlotTrimFilter(player.getWorld(), 0, visitTime, 600000); @@ -259,7 +270,9 @@ public class AnvilCommands { desc = "Delete chunks matching a specific biome" ) @CommandPermissions("worldedit.anvil.trimallair") - public void deleteBiome(Player player, String folder, BiomeType biome, @Switch(name = 'u', desc = "TODO") boolean unsafe) { + public void deleteBiome(Player player, String folder, BiomeType biome, + @Switch(name = 'u', desc = "The flag will run the task unsafe") + boolean unsafe) { // DeleteBiomeFilterSimple filter = new DeleteBiomeFilterSimple(biome); TODO NOT IMPLEMENTED // DeleteBiomeFilterSimple result = runWithWorld(player, folder, filter, true, unsafe); // if (result != null) { @@ -272,7 +285,9 @@ public class AnvilCommands { desc = "Trim all air in the world" ) @CommandPermissions("worldedit.anvil.trimallair") - public void trimAllAir(Player player, String folder, @Switch(name = 'u', desc = "TODO") boolean unsafe) throws WorldEditException { + public void trimAllAir(Player player, String folder, + @Switch(name = 'u', desc = "The flag will run the task unsafe") + boolean unsafe) throws WorldEditException { // TrimAirFilter filter = new TrimAirFilter(); TODO NOT IMPLEMENTED // TrimAirFilter result = runWithWorld(player, folder, filter, true, unsafe); // if (result != null) { @@ -282,7 +297,6 @@ public class AnvilCommands { @Command( name = "debugfixroads", - desc = "debug - do not use" ) @CommandPermissions("worldedit.anvil.debugfixroads") @@ -300,7 +314,13 @@ public class AnvilCommands { desc = "Replace all blocks in the selection with another" ) @CommandPermissions("worldedit.anvil.replaceall") - public void replaceAllPattern(Player player, String folder, @Arg(name = "from", desc = "String", def = "") String from, Pattern toPattern, @Switch(name = 'd', desc = "TODO") boolean useData, @Switch(name = 'm', desc = "TODO") boolean useMap) throws WorldEditException { + public void replaceAllPattern(Player player, String folder, + @Arg(desc = "String", def = "") + String from, Pattern toPattern, + @Switch(name = 'd', desc = "The flag specifies the data to use") + boolean useData, + @Switch(name = 'm', desc = "The flag specifies the map to use") + boolean useMap) throws WorldEditException { // MCAFilterCounter filter; TODO NOT IMPLEMENTED // if (useMap) { // if (to instanceof RandomPattern) { @@ -329,7 +349,9 @@ public class AnvilCommands { desc = "Count all blocks in a world" ) @CommandPermissions("worldedit.anvil.countall") - public void countAll(Player player, EditSession editSession, String folder, String argStr, @Switch(name = 'd', desc = "TODO") boolean useData) throws WorldEditException { + public void countAll(Player player, EditSession editSession, String folder, String argStr, + @Switch(name = 'd', desc = "The flag specifies the data to use") + boolean useData) throws WorldEditException { // Set searchBlocks = worldEdit.getBlocks(player, arg, true); // MCAFilterCounter filter; // if (useData || arg.contains(":")) { // Optimize for both cases @@ -403,7 +425,9 @@ public class AnvilCommands { desc = "Count blocks in a selection" ) @CommandPermissions("worldedit.anvil.count") - public void count(Player player, EditSession editSession, @Selection Region selection, String argStr, @Switch(name = 'd', desc = "TODO") boolean useData) throws WorldEditException { + public void count(Player player, EditSession editSession, @Selection Region selection, String argStr, + @Switch(name = 'd', desc = "The flag specifies the data to use") + boolean useData) throws WorldEditException { // Set searchBlocks = worldEdit.getBlocks(player, arg, true); TODO NOT IMPLEMENTED // MCAFilterCounter filter; // if (useData || arg.contains(":")) { // Optimize for both cases @@ -425,7 +449,9 @@ public class AnvilCommands { desc = "Replace all blocks in the selection with another" ) @CommandPermissions("worldedit.anvil.distr") - public void distr(Player player, EditSession editSession, @Selection Region selection, @Switch(name = 'd', desc = "TODO") boolean useData) throws WorldEditException { + public void distr(Player player, EditSession editSession, @Selection Region selection, + @Switch(name = 'd', desc = "The flag specifies the data to use") + boolean useData) throws WorldEditException { // long total = 0; TODO NOT IMPLEMENTED // long[] count; // MCAFilter counts; @@ -504,7 +530,11 @@ public class AnvilCommands { desc = "Replace all blocks in the selection with another" ) @CommandPermissions("worldedit.anvil.replace") - public void replace(Player player, EditSession editSession, @Selection Region selection, @Arg(name = "from", desc = "String", def = "") String from, String toStr, @Switch(name = 'd', desc = "TODO") boolean useData) throws WorldEditException { + public void replace(Player player, EditSession editSession, @Selection Region selection, + @Arg(desc = "String", def = "") + String from, String toStr, + @Switch(name = 'd', desc = "The flag specifies the data to use") + boolean useData) throws WorldEditException { // final FaweBlockMatcher matchFrom; TODO NOT IMPLEMENTED // if (from == null) { // matchFrom = FaweBlockMatcher.NOT_AIR; @@ -526,7 +556,13 @@ public class AnvilCommands { desc = "Replace all blocks in the selection with a pattern" ) @CommandPermissions("worldedit.anvil.replace") - public void replacePattern(Player player, EditSession editSession, @Selection Region selection, @Arg(name = "from", desc = "String", def = "") String from, final Pattern toPattern, @Switch(name = 'd', desc = "TODO") boolean useData, @Switch(name = 'm', desc = "TODO") boolean useMap) throws WorldEditException { + public void replacePattern(Player player, EditSession editSession, @Selection Region selection, + @Arg(desc = "String", def = "") + String from, final Pattern toPattern, + @Switch(name = 'd', desc = "The flag specifies the data to use") + boolean useData, + @Switch(name = 'm', desc = "The flag specifies the map to use") + boolean useMap) throws WorldEditException { // MCAFilterCounter filter; TODO NOT IMPLEMENTED // if (useMap) { // if (to instanceof RandomPattern) { @@ -556,7 +592,7 @@ public class AnvilCommands { desc = "Set all blocks in the selection with a pattern" ) @CommandPermissions("worldedit.anvil.set") - // Player player, String folder, @Arg(name = "from", desc = "String", def = "") String from, final Pattern toPattern, @Switch(name = 'd', desc = "TODO") boolean useData, @Switch(name = 'm', desc = "TODO") boolean useMap + // Player player, String folder, @Arg(name = "from", desc = "String", def = "") String from, final Pattern toPattern, @Switch(name = 'd', desc = "The flag specifies the data to use") boolean useData, @Switch(name = 'm', desc = "The flag specifies the map to use") boolean useMap public void set(Player player, EditSession editSession, @Selection Region selection, final Pattern toPattern) throws WorldEditException { // MCAFilterCounter filter = new SetPatternFilter(to); TODO NOT IMPLEMENTED // MCAFilterCounter result = runWithSelection(player, editSession, selection, filter); @@ -602,17 +638,18 @@ public class AnvilCommands { // MCAClipboard clipboard = new MCAClipboard(queue, cuboid, origin); // FawePlayer fp = FawePlayer.wrap(player); // fp.setMeta(FawePlayer.METADATA_KEYS.ANVIL_CLIPBOARD, clipboard); - // player.print(TranslatableComponent.of("fawe.worldedit.copy.command.copy" , selection.getArea())); + // player.print(TranslatableComponent.of("fawe.worldedit.copy.command.copy", selection.getArea())); } @Command( name = "paste", desc = "Paste chunks from your anvil clipboard", - descFooter = "Paste the chunks from your anvil clipboard.\n" + - "The -c flag will align the paste to the chunks." + descFooter = "Paste the chunks from your anvil clipboard." ) @CommandPermissions("worldedit.anvil.pastechunks") - public void paste(Player player, LocalSession session, EditSession editSession, @Switch(name = 'c', desc = "TODO") boolean alignChunk) throws WorldEditException, IOException { + public void paste(Player player, LocalSession session, EditSession editSession, + @Switch(name = 'c', desc = "Align to chunks") + boolean alignChunk) throws WorldEditException, IOException { // FawePlayer fp = FawePlayer.wrap(player); TODO NOT IMPLEMENTED // MCAClipboard clipboard = fp.getMeta(FawePlayer.METADATA_KEYS.ANVIL_CLIPBOARD); // if (clipboard == null) { @@ -639,6 +676,6 @@ public class AnvilCommands { // pasteQueue.pasteRegion(copyQueue, copyRegion, offset, iAnvilHistory); // } catch (IOException e) { throw new RuntimeException(e); } // }); - // player.print(TranslatableComponent.of("fawe.worldedit.paste.command.paste" , player.getPosition().toBlockVector())); + // player.print(TranslatableComponent.of("fawe.worldedit.paste.command.paste", player.getPosition().toBlockVector())); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/CFICommands.java b/worldedit-core/src/main/java/com/boydti/fawe/command/CFICommands.java index 7ab6d1f15..a3246d189 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/CFICommands.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/command/CFICommands.java @@ -245,7 +245,7 @@ // desc = "Set the floor and main block" // ) // @CommandPermissions("worldedit.anvil.cfi") -// public void column(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// public void column(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) { // HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); // if (image != null) { // gen.setColumn(load(image), pattern, !disableWhiteOnly); @@ -264,7 +264,7 @@ // desc = "Set the floor (default: grass)" // ) // @CommandPermissions("worldedit.anvil.cfi") -// public void floorCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// public void floorCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) { // floor(player, pattern, image, mask, disableWhiteOnly); // player.print("Set floor!"); // assertSettings(player).resetComponent(); @@ -287,14 +287,14 @@ // desc = "Set the main block (default: stone)" // ) // @CommandPermissions("worldedit.anvil.cfi") -// public void mainCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// public void mainCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) { // main(player, pattern, image, maskOpt, disableWhiteOnly); // player.print("Set main!"); // assertSettings(player).resetComponent(); // component(player); // } // -// public void main(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// public void main(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) { // HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); // if (image != null) { // gen.setMain(load(image), pattern, !disableWhiteOnly); @@ -313,7 +313,7 @@ // "e.g., Tallgrass" // ) // @CommandPermissions("worldedit.anvil.cfi") -// public void overlay(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// public void overlay(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) { // HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); // if (image != null) { // gen.setOverlay(load(image), pattern, !disableWhiteOnly); @@ -335,13 +335,13 @@ // " - A good value for radius and iterations would be 1 8." // ) // @CommandPermissions("worldedit.anvil.cfi") -// public void smoothCmd(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// public void smoothCmd(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) { // smooth(player, radius, iterations, image, mask, disableWhiteOnly); // assertSettings(player).resetComponent(); // component(player); // } // -// private void smooth(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// private void smooth(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) { // HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); // if (image != null) { // gen.smooth(load(image), !disableWhiteOnly, radius, iterations); @@ -355,7 +355,7 @@ // desc = "Create some snow" // ) // @CommandPermissions("worldedit.anvil.cfi") -// public void snow(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// public void snow(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) { // HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); // floor(player, BlockTypes.SNOW.getDefaultState().with(PropertyKey.LAYERS, 7), image, mask, disableWhiteOnly); // main(player, BlockTypes.SNOW_BLOCK, image, mask, disableWhiteOnly); @@ -422,7 +422,7 @@ // Request.request().setExtent(generator); // // Set blocks; -// switch (argOpt.toLowerCase()) { +// switch (argOpt.toLowerCase(Locale.ROOT)) { // case "true": // case "*": { // generator.setTextureUtil(Fawe.get().getTextureUtil()); @@ -535,7 +535,7 @@ // " - If a mask is used, the biome will be set anywhere the mask applies" // ) // @CommandPermissions("worldedit.anvil.cfi") -// public void biome(Player player, @Arg(desc = "Biome type") BiomeType biome, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// public void biome(Player player, @Arg(desc = "Biome type") BiomeType biome, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) { // HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); // if (image != null) { // gen.setBiome(load(image), biome, !disableWhiteOnly); @@ -819,7 +819,7 @@ // TextComponent.of("/cfi randomization " + !rand))); // @NotNull Builder builder = TextComponent.builder(">> Current Settings <<"); // builder.append(newline()); -// builder.append(TextComponent.of("Randomization [" + Boolean.toString(rand).toUpperCase() + "]") +// builder.append(TextComponent.of("Randomization [" + Boolean.toString(rand).toUpperCase(Locale.ROOT) + "]") // .clickEvent(ClickEvent.runCommand( // "/cfi randomization " + !rand)).hoverEvent(HoverEvent.showText( // TextComponent.of("/cfi randomization " + !rand)))); @@ -871,7 +871,7 @@ // desc = "Select a mask" // ) // @CommandPermissions("worldedit.anvil.cfi") -// public void mask(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly, InjectedValueAccess context){ +// public void mask(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly, InjectedValueAccess context) { // CFISettings settings = assertSettings(player); // String[] split = getArguments(context).split(" "); // int index = 2; @@ -950,7 +950,7 @@ // JsonObject data1 = obj.get("data").getAsJsonObject(); // String link = data1.get("link").getAsString(); // URL url = new URL(link); -// player.print(Caption.of("fawe.web.download.link" , url)); +// player.print(Caption.of("fawe.web.download.link", url)); // } // // @Command( diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/SuggestInputParseException.java b/worldedit-core/src/main/java/com/boydti/fawe/command/SuggestInputParseException.java index 55ca58c38..1fbc65b5e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/SuggestInputParseException.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/command/SuggestInputParseException.java @@ -20,12 +20,16 @@ public class SuggestInputParseException extends InputParseException { } public static SuggestInputParseException of(Throwable other, String prefix, Supplier> getSuggestions) { - if (other instanceof InputParseException) return of((InputParseException) other, prefix, getSuggestions); + if (other instanceof InputParseException) { + return of((InputParseException) other, prefix, getSuggestions); + } return of(new InputParseException(other.getMessage()), prefix, getSuggestions); } public static SuggestInputParseException of(InputParseException other, String prefix, Supplier> getSuggestions) { - if (other instanceof SuggestInputParseException) return (SuggestInputParseException) other; + if (other instanceof SuggestInputParseException) { + return (SuggestInputParseException) other; + } return new SuggestInputParseException(other, prefix, getSuggestions); } @@ -42,7 +46,9 @@ public class SuggestInputParseException extends InputParseException { Throwable t = e; while (t.getCause() != null) { t = t.getCause(); - if (t instanceof SuggestInputParseException) return (SuggestInputParseException) t; + if (t instanceof SuggestInputParseException) { + return (SuggestInputParseException) t; + } } return null; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/config/Caption.java b/worldedit-core/src/main/java/com/boydti/fawe/config/Caption.java index 8f0d39830..489facd14 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/config/Caption.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/config/Caption.java @@ -33,10 +33,7 @@ public class Caption { } /** - * Colorize a component with legacy color codes - * @param component - * @param locale - * @return Component + * Colorize a component with legacy color codes. */ public static Component color(Component component, Locale locale) { return color(WorldEditText.format(component, locale)); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/config/Config.java b/worldedit-core/src/main/java/com/boydti/fawe/config/Config.java index f6533209d..79265525f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/config/Config.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/config/Config.java @@ -21,6 +21,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; public class Config { @@ -32,12 +33,7 @@ public class Config { } /** - * Get the value for a node
- * Probably throws some error if you try to get a non existent key - * - * @param key - * @param - * @return + * Get the value for a node. Probably throws some error if you try to get a non-existent key. */ private T get(String key, Class root) { String[] split = key.split("\\."); @@ -57,8 +53,7 @@ public class Config { } /** - * Set the value of a specific node
- * Probably throws some error if you supply non existing keys or invalid values + * Set the value of a specific node. Probably throws some error if you supply non existing keys or invalid values. * * @param key config node * @param value value @@ -103,9 +98,7 @@ public class Config { } /** - * Set all values in the file (load first to avoid overwriting) - * - * @param file + * Set all values in the file (load first to avoid overwriting). */ public void save(File file) { Class root = getClass(); @@ -127,7 +120,7 @@ public class Config { } /** - * Indicates that a field should be instantiated / created + * Indicates that a field should be instantiated / created. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) @@ -135,7 +128,7 @@ public class Config { } /** - * Indicates that a field cannot be modified + * Indicates that a field cannot be modified. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) @@ -143,7 +136,7 @@ public class Config { } /** - * Creates a comment + * Creates a comment. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) @@ -152,7 +145,7 @@ public class Config { } /** - * The names of any default blocks + * The names of any default blocks. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) @@ -161,7 +154,7 @@ public class Config { } /** - * Any field or class with is not part of the config + * Any field or class with is not part of the config. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) @@ -199,10 +192,7 @@ public class Config { } /** - * Get the static fields in a section - * - * @param clazz - * @return + * Get the static fields in a section. */ private Map getFields(Class clazz) { HashMap map = new HashMap<>(); @@ -317,10 +307,9 @@ public class Config { } /** - * Get the field for a specific config node + * Get the field for a specific config node. * * @param split the node (split by period) - * @return */ private Field getField(String[] split, Class root) { Object instance = getInstance(split, root); @@ -331,12 +320,12 @@ public class Config { } /** - * Get the field for a specific config node and instance
- * Note: As expiry can have multiple blocks there will be multiple instances + * Get the field for a specific config node and instance. + * + * @apiNote As expiry can have multiple blocks there will be multiple instances * * @param split the node (split by period) * @param instance the instance - * @return */ private Field getField(String[] split, Object instance) { try { @@ -344,7 +333,7 @@ public class Config { setAccessible(field); return field; } catch (Throwable ignored) { - log.debug("Invalid config field: " + StringMan.join(split, ".") + " for " + toNodeName(instance.getClass().getSimpleName())); + log.debug("Invalid config field: " + StringMan.join(split, ".") + " for " + toNodeName(instance.getClass().getSimpleName())); return null; } } @@ -352,13 +341,13 @@ public class Config { private Object getInstance(Object instance, Class clazz) throws IllegalAccessException, InstantiationException { try { Field instanceField = clazz.getDeclaredField(clazz.getSimpleName()); - } catch (Throwable ignore) { + } catch (Throwable ignored) { } return clazz.newInstance(); } /** - * Get the instance for a specific config node + * Get the instance for a specific config node. * * @param split the node (split by period) * @return The instance or null @@ -407,7 +396,7 @@ public class Config { clazz = found; split = Arrays.copyOfRange(split, 2, split.length); continue; - } catch (NoSuchFieldException ignore) { + } catch (NoSuchFieldException ignored) { } if (found != null) { split = Arrays.copyOfRange(split, 1, split.length); @@ -425,31 +414,21 @@ public class Config { } /** - * Translate a node to a java field name - * - * @param node - * @return + * Translate a node to a java field name. */ private String toFieldName(String node) { - return node.toUpperCase().replaceAll("-", "_"); + return node.toUpperCase(Locale.ROOT).replaceAll("-", "_"); } /** - * Translate a field to a config node - * - * @param field - * @return + * Translate a field to a config node. */ private String toNodeName(String field) { - return field.toLowerCase().replace("_", "-"); + return field.toLowerCase(Locale.ROOT).replace("_", "-"); } /** - * Set some field to be accessible - * - * @param field - * @throws NoSuchFieldException - * @throws IllegalAccessException + * Set some field to be accessible. */ private void setAccessible(Field field) throws NoSuchFieldException, IllegalAccessException { field.setAccessible(true); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/config/Settings.java b/worldedit-core/src/main/java/com/boydti/fawe/config/Settings.java index 043952220..83dbe1149 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/config/Settings.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/config/Settings.java @@ -29,7 +29,7 @@ public class Settings extends Config { public String COMMIT; // These values are set from FAWE before loading @Final public String PLATFORM; // These values are set from FAWE before loading - + @Comment({ "Set true to enable WorldEdit restrictions per region (e.g. PlotSquared or WorldGuard).", "To be allowed to WorldEdit in a region, users need the appropriate", @@ -369,14 +369,14 @@ public class Settings extends Config { "Might cause client-side FPS lagg in some situations" }) public boolean KEEP_ENTITIES_IN_BLOCKS = false; - + @Comment({ "[SAFE] Experimental freebuild region restrictions", " - PERM: fawe.freebuild", " - PERM: fawe.freebuild." }) public boolean FREEBUILD = false; - + @Comment({ "Other experimental features" }) @@ -504,7 +504,9 @@ public class Settings extends Config { limit = new FaweLimit(); } ArrayList keys = new ArrayList<>(LIMITS.getSections()); - if (keys.remove("default")) keys.add("default"); + if (keys.remove("default")) { + keys.add("default"); + } boolean limitFound = false; for (String key : keys) { @@ -524,13 +526,16 @@ public class Settings extends Config { limit.SPEED_REDUCTION = Math.min(limit.SPEED_REDUCTION, newLimit.SPEED_REDUCTION); limit.FAST_PLACEMENT |= newLimit.FAST_PLACEMENT; limit.CONFIRM_LARGE &= newLimit.CONFIRM_LARGE; - if (limit.STRIP_NBT == null) limit.STRIP_NBT = newLimit.STRIP_NBT.isEmpty() ? Collections.emptySet() : new HashSet<>(newLimit.STRIP_NBT); - else if (limit.STRIP_NBT.isEmpty() || newLimit.STRIP_NBT.isEmpty()) { + if (limit.STRIP_NBT == null) { + limit.STRIP_NBT = newLimit.STRIP_NBT.isEmpty() ? Collections.emptySet() : new HashSet<>(newLimit.STRIP_NBT); + } else if (limit.STRIP_NBT.isEmpty() || newLimit.STRIP_NBT.isEmpty()) { limit.STRIP_NBT = Collections.emptySet(); } else { limit.STRIP_NBT = new HashSet<>(limit.STRIP_NBT); limit.STRIP_NBT.retainAll(newLimit.STRIP_NBT); - if (limit.STRIP_NBT.isEmpty()) limit.STRIP_NBT = Collections.emptySet(); + if (limit.STRIP_NBT.isEmpty()) { + limit.STRIP_NBT = Collections.emptySet(); + } } } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/configuration/Configuration.java b/worldedit-core/src/main/java/com/boydti/fawe/configuration/Configuration.java index 0d3a2db67..f3bdb400e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/configuration/Configuration.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/configuration/Configuration.java @@ -3,20 +3,23 @@ package com.boydti.fawe.configuration; import java.util.Map; /** - * Represents a source of configurable options and settings + * Represents a source of configurable options and settings. */ public interface Configuration extends ConfigurationSection { + /** * Sets the default value of the given path as provided. - *

- * If no source {@link Configuration} was provided as a default - * collection, then a new {@link MemoryConfiguration} will be created to - * hold the new default value. - *

- * If value is null, the value will be removed from the default - * Configuration source. * - * @param path Path of the value to set. + *

+ * If no source {@link Configuration} was provided as a default collection, then a new {@link + * MemoryConfiguration} will be created to hold the new default value. + *

+ * + *

+ * If value is null, the value will be removed from the default Configuration source. + *

+ * + * @param path Path of the value to set. * @param value Value to set the default to. * @throws IllegalArgumentException Thrown if path is null. */ @@ -25,10 +28,11 @@ public interface Configuration extends ConfigurationSection { /** * Sets the default values of the given paths as provided. + * *

- * If no source {@link Configuration} was provided as a default - * collection, then a new {@link MemoryConfiguration} will be created to - * hold the new default values. + * If no source {@link Configuration} was provided as a default collection, then a new {@link + * MemoryConfiguration} will be created to hold the new default values. + *

* * @param defaults A map of Path->Values to add to defaults. * @throws IllegalArgumentException Thrown if defaults is null. @@ -37,15 +41,17 @@ public interface Configuration extends ConfigurationSection { /** * Sets the default values of the given paths as provided. + * *

- * If no source {@link Configuration} was provided as a default - * collection, then a new {@link MemoryConfiguration} will be created to - * hold the new default value. + * If no source {@link Configuration} was provided as a default collection, then a new {@link + * MemoryConfiguration} will be created to hold the new default value. + *

+ * *

- * This method will not hold a reference to the specified Configuration, - * nor will it automatically update if that Configuration ever changes. If - * you require this, you should set the default source with {@link - * #setDefaults(Configuration)}. + * This method will not hold a reference to the specified Configuration, nor will it + * automatically update if that Configuration ever changes. If you require this, you should set + * the default source with {@link #setDefaults(Configuration)}. + *

* * @param defaults A configuration holding a list of defaults to copy. * @throws IllegalArgumentException Thrown if defaults is null or this. @@ -54,9 +60,11 @@ public interface Configuration extends ConfigurationSection { /** * Sets the source of all default values for this {@link Configuration}. + * *

- * If a previous source was set, or previous default values were defined, - * then they will not be copied to the new source. + * If a previous source was set, or previous default values were defined, then they will not be + * copied to the new source. + *

* * @param defaults New source of default values for this configuration. * @throws IllegalArgumentException Thrown if defaults is null or this. @@ -65,10 +73,12 @@ public interface Configuration extends ConfigurationSection { /** * Gets the source {@link Configuration} for this configuration. + * *

- * If no configuration source was set, but default values were added, then - * a {@link MemoryConfiguration} will be returned. If no source was set - * and no defaults were set, then this method will return null. + * If no configuration source was set, but default values were added, then a {@link + * MemoryConfiguration} will be returned. If no source was set and no defaults were set, then + * this method will return null. + *

* * @return Configuration source for default values, or null if none exist. */ @@ -76,8 +86,10 @@ public interface Configuration extends ConfigurationSection { /** * Gets the {@link ConfigurationOptions} for this {@link Configuration}. + * *

* All setters through this method are chainable. + *

* * @return Options for this configuration */ diff --git a/worldedit-core/src/main/java/com/boydti/fawe/configuration/ConfigurationSection.java b/worldedit-core/src/main/java/com/boydti/fawe/configuration/ConfigurationSection.java index 933645113..35e5b8f9d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/configuration/ConfigurationSection.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/configuration/ConfigurationSection.java @@ -5,130 +5,149 @@ import java.util.Map; import java.util.Set; /** - * Represents a section of a {@link com.boydti.fawe.configuration.Configuration} + * Represents a section of a {@link Configuration}. */ public interface ConfigurationSection { /** * Gets a set containing all keys in this section. - *

- * If deep is set to true, then this will contain all the keys within any - * child {@link com.boydti.fawe.configuration.ConfigurationSection}s (and their children, etc). These - * will be in a valid path notation for you to use. - *

- * If deep is set to false, then this will contain only the keys of any - * direct children, and not their own children. * - * @param deep Whether or not to get a deep list, as opposed to a shallow - * list. + *

+ * If deep is set to true, then this will contain all the keys within any child {@link + * ConfigurationSection}s (and their children, etc). These will be in a valid path notation for + * you to use. + *

+ * + *

+ * If deep is set to false, then this will contain only the keys of any direct children, and not + * their own children. + *

+ * + * @param deep Whether or not to get a deep list, as opposed to a shallow list. * @return Set of keys contained within this ConfigurationSection. */ Set getKeys(boolean deep); /** - * Gets a Map containing all keys and their values for this section. - *

- * If deep is set to true, then this will contain all the keys and values - * within any child {@link com.boydti.fawe.configuration.ConfigurationSection}s (and their children, - * etc). These keys will be in a valid path notation for you to use. - *

- * If deep is set to false, then this will contain only the keys and - * values of any direct children, and not their own children. + * Gets a Map containing all keys, and their values for this section. * - * @param deep Whether or not to get a deep list, as opposed to a shallow - * list. + *

+ * If deep is set to true, then this will contain all the keys and values within any child + * {@link ConfigurationSection}s (and their children, etc). These keys will be in a valid path + * notation for you to use. + *

+ * + *

+ * If deep is set to false, then this will contain only the keys and values of any direct + * children, and not their own children. + *

+ * + * @param deep Whether or not to get a deep list, as opposed to a shallow list. * @return Map of keys and values of this section. */ Map getValues(boolean deep); /** - * Checks if this {@link com.boydti.fawe.configuration.ConfigurationSection} contains the given path. + * Checks if this {@link ConfigurationSection} contains the given path. + * *

- * If the value for the requested path does not exist but a default value - * has been specified, this will return true. + * If the value for the requested path does not exist, but a default value has been specified, + * this will return true. + *

* * @param path Path to check for existence. - * @return True if this section contains the requested path, either via - * default or being set. + * @return True if this section contains the requested path, either via default or being set. * @throws IllegalArgumentException Thrown when path is null. */ boolean contains(String path); /** - * Checks if this {@link com.boydti.fawe.configuration.ConfigurationSection} has a value set for the - * given path. + * Checks if this {@link ConfigurationSection} has a value set for the given path. + * *

- * If the value for the requested path does not exist but a default value - * has been specified, this will still return false. + * If the value for the requested path does not exist, but a default value has been specified, + * this will still return false. + *

* * @param path Path to check for existence. - * @return True if this section contains the requested path, regardless of - * having a default. + * @return True if this section contains the requested path, regardless of having a default. * @throws IllegalArgumentException Thrown when path is null. */ boolean isSet(String path); /** - * Gets the path of this {@link com.boydti.fawe.configuration.ConfigurationSection} from its root {@link - * com.boydti.fawe.configuration.Configuration} + * Gets the path of this {@link ConfigurationSection} from its root {@link Configuration}. + * *

- * For any {@link com.boydti.fawe.configuration.Configuration} themselves, this will return an empty - * string. + * For any {@link Configuration} themselves, this will return an empty string. + *

+ * *

- * If the section is no longer contained within its root for any reason, - * such as being replaced with a different value, this may return null. + * If the section is no longer contained within its root for any reason, such as being replaced + * with a different value, this may return null. + *

+ * *

- * To retrieve the single name of this section, that is, the final part of - * the path returned by this method, you may use {@link #getName()}. + * To retrieve the single name of this section, that is, the final part of the path returned by + * this method, you may use {@link #getName()}. + *

* * @return Path of this section relative to its root */ String getCurrentPath(); /** - * Gets the name of this individual {@link com.boydti.fawe.configuration.ConfigurationSection}, in the - * path. + * Gets the name of this individual {@link ConfigurationSection}, in the path. + * *

- * This will always be the final part of {@link #getCurrentPath()}, unless - * the section is orphaned. + * This will always be the final part of {@link #getCurrentPath()}, unless the section is + * orphaned. + *

* * @return Name of this section */ String getName(); /** - * Gets the root {@link com.boydti.fawe.configuration.Configuration} that contains this {@link - * com.boydti.fawe.configuration.ConfigurationSection} + * Gets the root {@link Configuration} that contains this {@link ConfigurationSection}. + * *

- * For any {@link com.boydti.fawe.configuration.Configuration} themselves, this will return its own - * object. + * For any {@link Configuration} themselves, this will return its own object. + *

+ * *

- * If the section is no longer contained within its root for any reason, - * such as being replaced with a different value, this may return null. + * If the section is no longer contained within its root for any reason, such as being replaced + * with a different value, this may return null. + *

* * @return Root configuration containing this section. */ Configuration getRoot(); /** - * Gets the parent {@link com.boydti.fawe.configuration.ConfigurationSection} that directly contains - * this {@link com.boydti.fawe.configuration.ConfigurationSection}. + * Gets the parent {@link ConfigurationSection} that directly contains this {@link + * ConfigurationSection}. *

- * For any {@link com.boydti.fawe.configuration.Configuration} themselves, this will return null. + * For any {@link Configuration} themselves, this will return null. + *

+ * *

- * If the section is no longer contained within its parent for any reason, - * such as being replaced with a different value, this may return null. + * If the section is no longer contained within its parent for any reason, such as being + * replaced with a different value, this may return null. + *

* * @return Parent section containing this section. */ - com.boydti.fawe.configuration.ConfigurationSection getParent(); + ConfigurationSection getParent(); /** * Gets the requested Object by path. + * *

- * If the Object does not exist but a default value has been specified, - * this will return the default value. If the Object does not exist and no - * default value was specified, this will return null. + * If the Object does not exist, but a default value has been specified, this will return the + * default value. If the Object does not exist and no default value was specified, this will + * return null. + *

* * @param path Path of the Object to get. * @return Requested Object. @@ -136,69 +155,75 @@ public interface ConfigurationSection { Object get(String path); /** - * Gets the requested Object by path, returning a default value if not - * found. + * Gets the requested Object by a path, returning a default value if not found. + * *

- * If the Object does not exist then the specified default value will - * returned regardless of if a default has been identified in the root - * {@link com.boydti.fawe.configuration.Configuration}. + * If the Object does not exist then the specified default value will return regardless of if a + * default has been identified in the root {@link Configuration}. + *

* * @param path Path of the Object to get. - * @param def The default value to return if the path is not found. + * @param def The default value to return if the path is not found. * @return Requested Object. */ Object get(String path, Object def); /** * Sets the specified path to the given value. - *

- * If value is null, the entry will be removed. Any existing entry will be - * replaced, regardless of what the new value is. - *

- * Some implementations may have limitations on what you may store. See - * their individual javadoc for details. No implementations should allow - * you to store {@link com.boydti.fawe.configuration.Configuration}s or {@link com.boydti.fawe.configuration.ConfigurationSection}s, - * please use {@link #createSection(String)} for that. * - * @param path Path of the object to set. + *

+ * If value is null, the entry will be removed. Any existing entry will be replaced, regardless + * of what the new value is. + *

+ * + *

+ * Some implementations may have limitations on what you may store. See their individual javadoc + * for details. No implementations should allow you to store {@link Configuration}s or {@link + * ConfigurationSection}s, please use {@link #createSection(String)} for that. + *

+ * + * @param path Path of the object to set. * @param value New value to set the path to. */ void set(String path, Object value); /** - * Creates an empty {@link com.boydti.fawe.configuration.ConfigurationSection} at the specified path. + * Creates an empty {@link ConfigurationSection} at the specified path. + * *

- * Any value that was previously set at this path will be overwritten. If - * the previous value was itself a {@link com.boydti.fawe.configuration.ConfigurationSection}, it will - * be orphaned. + * Any value that was previously set at this path will be overwritten. If the previous value was + * itself a {@link ConfigurationSection}, it will be orphaned. + *

* * @param path Path to create the section at. * @return Newly created section */ - com.boydti.fawe.configuration.ConfigurationSection createSection(String path); + ConfigurationSection createSection(String path); /** - * Creates a {@link com.boydti.fawe.configuration.ConfigurationSection} at the specified path, with - * specified values. + * Creates a {@link ConfigurationSection} at the specified path, with specified values. + * *

- * Any value that was previously set at this path will be overwritten. If - * the previous value was itself a {@link com.boydti.fawe.configuration.ConfigurationSection}, it will - * be orphaned. + * Any value that was previously set at this path will be overwritten. If the previous value was + * itself a {@link ConfigurationSection}, it will be orphaned. + *

* * @param path Path to create the section at. - * @param map The values to used. + * @param map The values to used. * @return Newly created section */ - com.boydti.fawe.configuration.ConfigurationSection createSection(String path, Map map); + ConfigurationSection createSection(String path, Map map); // Primitives /** - * Gets the requested String by path. + * Gets the requested String by a path. + * *

- * If the String does not exist but a default value has been specified, - * this will return the default value. If the String does not exist and no - * default value was specified, this will return null. + * If the String does not exist, but a default value has been specified, this will return the + * default value. If the String does not exist and no default value was specified, this will + * return null. + *

* * @param path Path of the String to get. * @return Requested String. @@ -206,12 +231,14 @@ public interface ConfigurationSection { String getString(String path); /** - * Gets the requested String by path, returning a default value if not + * Gets the requested String by a path, returning a default value if not * found. + * *

* If the String does not exist then the specified default value will - * returned regardless of if a default has been identified in the root - * {@link com.boydti.fawe.configuration.Configuration}. + * return regardless of if a default has been identified in the root + * {@link Configuration}. + *

* * @param path Path of the String to get. * @param def The default value to return if the path is not found or is @@ -222,11 +249,12 @@ public interface ConfigurationSection { /** * Checks if the specified path is a String. + * *

- *

If the path exists but is not a String, this will return false. If the - * path does not exist, this will return false. If the path does not exist - * but a default value has been specified, this will check if that default - * value is a String and return appropriately.

+ * If the path exists but is not a String, this will return false. If the path does not exist, + * this will return false. If the path does not exist, but a default value has been specified, + * this will check if that default value is a String and return appropriately. + *

* * @param path Path of the String to check. * @return Whether or not the specified path is a String. @@ -234,11 +262,13 @@ public interface ConfigurationSection { boolean isString(String path); /** - * Gets the requested int by path. + * Gets the requested int by a path. + * *

- *

If the int does not exist but a default value has been specified, this + * If the int does not exist, but a default value has been specified, this * will return the default value. If the int does not exist and no default - * value was specified, this will return 0.

+ * value was specified, this will return 0. + *

* * @param path Path of the int to get. * @return Requested int. @@ -246,26 +276,27 @@ public interface ConfigurationSection { int getInt(String path); /** - * Gets the requested int by path, returning a default value if not found. + * Gets the requested int by a path, returning a default value if not found. + * *

- *

If the int does not exist then the specified default value will - * returned regardless of if a default has been identified in the root - * {@link com.boydti.fawe.configuration.Configuration}.

+ * If the int does not exist then the specified default value will return regardless of if a + * default has been identified in the root {@link Configuration}. + *

* * @param path Path of the int to get. - * @param def The default value to return if the path is not found or is - * not an int. + * @param def The default value to return if the path is not found or is not an int. * @return Requested int. */ int getInt(String path, int def); /** * Checks if the specified path is an int. + * *

- *

If the path exists but is not a int, this will return false. If the - * path does not exist, this will return false. If the path does not exist - * but a default value has been specified, this will check if that default - * value is a int and return appropriately.

+ * If the path exists but is not an int, this will return false. If the path does not exist, + * this will return false. If the path does not exist, but a default value has been specified, + * this will check if that default value is an int and return appropriately + *

* * @param path Path of the int to check. * @return Whether or not the specified path is an int. @@ -273,11 +304,13 @@ public interface ConfigurationSection { boolean isInt(String path); /** - * Gets the requested boolean by path. + * Gets the requested boolean by a path. + * *

- * If the boolean does not exist but a default value has been specified, - * this will return the default value. If the boolean does not exist and - * no default value was specified, this will return false. + * If the boolean does not exist, but a default value has been specified, this will return the + * default value. If the boolean does not exist and no default value was specified, this will + * return false. + *

* * @param path Path of the boolean to get. * @return Requested boolean. @@ -285,27 +318,27 @@ public interface ConfigurationSection { boolean getBoolean(String path); /** - * Gets the requested boolean by path, returning a default value if not - * found. + * Gets the requested boolean by a path, returning a default value if not found. + * *

- * If the boolean does not exist then the specified default value will - * returned regardless of if a default has been identified in the root - * {@link com.boydti.fawe.configuration.Configuration}. + * If the boolean does not exist then the specified default value will return regardless of if a + * default has been identified in the root {@link Configuration}. + *

* * @param path Path of the boolean to get. - * @param def The default value to return if the path is not found or is - * not a boolean. + * @param def The default value to return if the path is not found or is not a boolean. * @return Requested boolean. */ boolean getBoolean(String path, boolean def); /** * Checks if the specified path is a boolean. + * *

- * If the path exists but is not a boolean, this will return false. If the - * path does not exist, this will return false. If the path does not exist - * but a default value has been specified, this will check if that default - * value is a boolean and return appropriately. + * If the path exists but is not a boolean, this will return false. If the path does not exist, + * this will return false. If the path does not exist, but a default value has been specified, + * this will check if that default value is a boolean and return appropriately. + *

* * @param path Path of the boolean to check. * @return Whether or not the specified path is a boolean. @@ -313,11 +346,13 @@ public interface ConfigurationSection { boolean isBoolean(String path); /** - * Gets the requested double by path. + * Gets the requested double by a path. + * *

- * If the double does not exist but a default value has been specified, - * this will return the default value. If the double does not exist and no - * default value was specified, this will return 0. + * If the double does not exist, but a default value has been specified, this will return the + * default value. If the double does not exist and no default value was specified, this will + * return 0. + *

* * @param path Path of the double to get. * @return Requested double. @@ -325,27 +360,27 @@ public interface ConfigurationSection { double getDouble(String path); /** - * Gets the requested double by path, returning a default value if not - * found. + * Gets the requested double by a path, returning a default value if not found. + * *

- * If the double does not exist then the specified default value will - * returned regardless of if a default has been identified in the root - * {@link com.boydti.fawe.configuration.Configuration}. + * If the double does not exist then the specified default value will return regardless of if a + * default has been identified in the root {@link Configuration}. + *

* * @param path Path of the double to get. - * @param def The default value to return if the path is not found or is - * not a double. + * @param def The default value to return if the path is not found or is not a double. * @return Requested double. */ double getDouble(String path, double def); /** * Checks if the specified path is a double. + * *

- * If the path exists but is not a double, this will return false. If the - * path does not exist, this will return false. If the path does not exist - * but a default value has been specified, this will check if that default - * value is a double and return appropriately. + * If the path exists but is not a double, this will return false. If the path does not exist, + * this will return false. If the path does not exist, but a default value has been specified, + * this will check if that default value is a double and return appropriately. + *

* * @param path Path of the double to check. * @return Whether or not the specified path is a double. @@ -353,11 +388,13 @@ public interface ConfigurationSection { boolean isDouble(String path); /** - * Gets the requested long by path. + * Gets the requested long by a path. + * *

- * If the long does not exist but a default value has been specified, this - * will return the default value. If the long does not exist and no - * default value was specified, this will return 0. + * If the long does not exist, but a default value has been specified, this will return the + * default value. If the long does not exist and no default value was specified, this will + * return 0. + *

* * @param path Path of the long to get. * @return Requested long. @@ -365,27 +402,27 @@ public interface ConfigurationSection { long getLong(String path); /** - * Gets the requested long by path, returning a default value if not - * found. + * Gets the requested long by a path, returning a default value if not found. + * *

- * If the long does not exist then the specified default value will - * returned regardless of if a default has been identified in the root - * {@link com.boydti.fawe.configuration.Configuration}. + * If the long does not exist then the specified default value will return regardless of if a + * default has been identified in the root {@link Configuration}. + *

* * @param path Path of the long to get. - * @param def The default value to return if the path is not found or is - * not a long. + * @param def The default value to return if the path is not found or is not a long. * @return Requested long. */ long getLong(String path, long def); /** * Checks if the specified path is a long. + * *

- * If the path exists but is not a long, this will return false. If the - * path does not exist, this will return false. If the path does not exist - * but a default value has been specified, this will check if that default - * value is a long and return appropriately. + * If the path exists but is not a long, this will return false. If the path does not exist, + * this will return false. If the path does not exist, but a default value has been specified, + * this will check if that default value is a long and return appropriately. + *

* * @param path Path of the long to check. * @return Whether or not the specified path is a long. @@ -395,11 +432,13 @@ public interface ConfigurationSection { // Java /** - * Gets the requested List by path. + * Gets the requested List by a path. + * *

- * If the List does not exist but a default value has been specified, this - * will return the default value. If the List does not exist and no - * default value was specified, this will return null. + * If the List does not exist, but a default value has been specified, this will return the + * default value. If the List does not exist and no default value was specified, this will + * return null. + *

* * @param path Path of the List to get. * @return Requested List. @@ -407,27 +446,28 @@ public interface ConfigurationSection { List getList(String path); /** - * Gets the requested List by path, returning a default value if not - * found. + * Gets the requested List by a path, returning a default value if not found. + * *

- * If the List does not exist then the specified default value will - * returned regardless of if a default has been identified in the root - * {@link com.boydti.fawe.configuration.Configuration}. + * If the List does not exist then the specified default value will return regardless of if a + * default has been identified in the root {@link Configuration}. + *

* * @param path Path of the List to get. - * @param def The default value to return if the path is not found or is - * not a List. + * @param def The default value to return if the path is not found or is not a List. * @return Requested List. */ List getList(String path, List def); /** * Checks if the specified path is a List. + * *

* If the path exists but is not a List, this will return false. If the - * path does not exist, this will return false. If the path does not exist - * but a default value has been specified, this will check if that default + * path does not exist, this will return false. If the path does not exist, but + * a default value has been specified, this will check if that default * value is a List and return appropriately. + *

* * @param path Path of the List to check. * @return Whether or not the specified path is a List. @@ -436,13 +476,17 @@ public interface ConfigurationSection { /** * Gets the requested List of String by path. + * *

- * If the List does not exist but a default value has been specified, this + * If the List does not exist, but a default value has been specified, this * will return the default value. If the List does not exist and no * default value was specified, this will return an empty List. + *

+ * *

* This method will attempt to cast any values into a String if possible, * but may miss any values out if they are not compatible. + *

* * @param path Path of the List to get. * @return Requested List of String. @@ -450,14 +494,18 @@ public interface ConfigurationSection { List getStringList(String path); /** - * Gets the requested List of Integer by path. + * Gets the requested List of an Integer by a path. + * *

- * If the List does not exist but a default value has been specified, this - * will return the default value. If the List does not exist and no - * default value was specified, this will return an empty List. + * If the List does not exist, but a default value has been specified, this will return the + * default value. If the List does not exist and no default value was specified, this will + * return an empty List. + *

+ * *

- * This method will attempt to cast any values into a Integer if possible, - * but may miss any values out if they are not compatible. + * This method will attempt to cast any values into an Integer if possible, but may miss any + * values out if they are not compatible. + *

* * @param path Path of the List to get. * @return Requested List of Integer. @@ -465,14 +513,18 @@ public interface ConfigurationSection { List getIntegerList(String path); /** - * Gets the requested List of Boolean by path. + * Gets the requested List of Boolean by a path. + * *

- * If the List does not exist but a default value has been specified, this - * will return the default value. If the List does not exist and no - * default value was specified, this will return an empty List. + * If the List does not exist, but a default value has been specified, this will return the + * default value. If the List does not exist and no default value was specified, this will + * return an empty List. + *

+ * *

- * This method will attempt to cast any values into a Boolean if possible, - * but may miss any values out if they are not compatible. + * This method will attempt to cast any values into a Boolean if possible, but may miss any + * values out if they are not compatible. + *

* * @param path Path of the List to get. * @return Requested List of Boolean. @@ -480,14 +532,18 @@ public interface ConfigurationSection { List getBooleanList(String path); /** - * Gets the requested List of Double by path. + * Gets the requested List of Double by a path. + * *

- * If the List does not exist but a default value has been specified, this - * will return the default value. If the List does not exist and no - * default value was specified, this will return an empty List. + * If the List does not exist, but a default value has been specified, this will return the + * default value. If the List does not exist and no default value was specified, this will + * return an empty List. + *

+ * *

- * This method will attempt to cast any values into a Double if possible, - * but may miss any values out if they are not compatible. + * This method will attempt to cast any values into a Double if possible, but may miss any + * values out if they are not compatible. + *

* * @param path Path of the List to get. * @return Requested List of Double. @@ -495,14 +551,18 @@ public interface ConfigurationSection { List getDoubleList(String path); /** - * Gets the requested List of Float by path. + * Gets the requested List of Float by a path. + * *

- * If the List does not exist but a default value has been specified, this - * will return the default value. If the List does not exist and no - * default value was specified, this will return an empty List. + * If the List does not exist, but a default value has been specified, this will return the + * default value. If the List does not exist and no default value was specified, this will + * return an empty List. + *

+ * *

- * This method will attempt to cast any values into a Float if possible, - * but may miss any values out if they are not compatible. + * This method will attempt to cast any values into a Float if possible, but may miss any + * values out if they are not compatible. + *

* * @param path Path of the List to get. * @return Requested List of Float. @@ -510,14 +570,18 @@ public interface ConfigurationSection { List getFloatList(String path); /** - * Gets the requested List of Long by path. + * Gets the requested List of Long by a path. + * *

- * If the List does not exist but a default value has been specified, this - * will return the default value. If the List does not exist and no - * default value was specified, this will return an empty List. + * If the List does not exist, but a default value has been specified, this will return the + * default value. If the List does not exist and no default value was specified, this will + * return an empty List. + *

+ * *

- * This method will attempt to cast any values into a Long if possible, - * but may miss any values out if they are not compatible. + * This method will attempt to cast any values into a Long if possible, but may miss any + * values out if they are not compatible. + *

* * @param path Path of the List to get. * @return Requested List of Long. @@ -525,14 +589,18 @@ public interface ConfigurationSection { List getLongList(String path); /** - * Gets the requested List of Byte by path. + * Gets the requested List of Byte by a path. + * *

- * If the List does not exist but a default value has been specified, this - * will return the default value. If the List does not exist and no - * default value was specified, this will return an empty List. + * If the List does not exist, but a default value has been specified, this will return the + * default value. If the List does not exist and no default value was specified, this will + * return an empty List. + *

+ * *

- * This method will attempt to cast any values into a Byte if possible, - * but may miss any values out if they are not compatible. + * This method will attempt to cast any values into a Byte if possible, but may miss any + * values out if they are not compatible. + *

* * @param path Path of the List to get. * @return Requested List of Byte. @@ -540,14 +608,18 @@ public interface ConfigurationSection { List getByteList(String path); /** - * Gets the requested List of Character by path. + * Gets the requested List of Character by a path. + * *

- * If the List does not exist but a default value has been specified, this - * will return the default value. If the List does not exist and no - * default value was specified, this will return an empty List. + * If the List does not exist, but a default value has been specified, this will return the + * default value. If the List does not exist and no default value was specified, this will + * return an empty List. + *

+ * *

- * This method will attempt to cast any values into a Character if - * possible, but may miss any values out if they are not compatible. + * This method will attempt to cast any values into a Character if possible, but may miss any + * values out if they are not compatible. + *

* * @param path Path of the List to get. * @return Requested List of Character. @@ -555,14 +627,18 @@ public interface ConfigurationSection { List getCharacterList(String path); /** - * Gets the requested List of Short by path. + * Gets the requested List of Short by a path. + * *

- * If the List does not exist but a default value has been specified, this - * will return the default value. If the List does not exist and no - * default value was specified, this will return an empty List. + * If the List does not exist, but a default value has been specified, this will return the + * default value. If the List does not exist and no default value was specified, this will + * return an empty List. + *

+ * *

- * This method will attempt to cast any values into a Short if possible, - * but may miss any values out if they are not compatible. + * This method will attempt to cast any values into a Short if possible, but may miss any values + * out if they are not compatible. + *

* * @param path Path of the List to get. * @return Requested List of Short. @@ -570,14 +646,18 @@ public interface ConfigurationSection { List getShortList(String path); /** - * Gets the requested List of Maps by path. + * Gets the requested List of Maps by a path. + * *

- * If the List does not exist but a default value has been specified, this - * will return the default value. If the List does not exist and no - * default value was specified, this will return an empty List. + * If the List does not exist, but a default value has been specified, this will return the + * default value. If the List does not exist and no default value was specified, this will + * return an empty List. + *

+ * *

- * This method will attempt to cast any values into a Map if possible, but - * may miss any values out if they are not compatible. + * This method will attempt to cast any values into a Map if possible, but may miss any values + * out if they are not compatible. + *

* * @param path Path of the List to get. * @return Requested List of Maps. @@ -586,25 +666,27 @@ public interface ConfigurationSection { /** * Gets the requested ConfigurationSection by path. + * *

- * If the ConfigurationSection does not exist but a default value has been - * specified, this will return the default value. If the - * ConfigurationSection does not exist and no default value was specified, - * this will return null. + * If the ConfigurationSection does not exist, but a default value has been specified, this will + * return the default value. If the ConfigurationSection does not exist and no default value was + * specified, this will return null. + *

* * @param path Path of the ConfigurationSection to get. * @return Requested ConfigurationSection. */ - com.boydti.fawe.configuration.ConfigurationSection getConfigurationSection(String path); + ConfigurationSection getConfigurationSection(String path); /** - * Checks if the specified path is a ConfigurationSection. + * Checks if the specified path is a {@link ConfigurationSection}. + * *

- * If the path exists but is not a ConfigurationSection, this will return - * false. If the path does not exist, this will return false. If the path - * does not exist but a default value has been specified, this will check - * if that default value is a ConfigurationSection and return - * appropriately. + * If the path exists but is not a {@code ConfigurationSection}, this will return false. If the + * path does not exist, this will return false. If the path does not exist, but a default value + * has been specified, this will check if that default value is a ConfigurationSection and + * return appropriately. + *

* * @param path Path of the ConfigurationSection to check. * @return Whether or not the specified path is a ConfigurationSection. @@ -612,32 +694,37 @@ public interface ConfigurationSection { boolean isConfigurationSection(String path); /** - * Gets the equivalent {@link com.boydti.fawe.configuration.ConfigurationSection} from the default - * {@link com.boydti.fawe.configuration.Configuration} defined in {@link #getRoot()}. + * Gets the equivalent {@link ConfigurationSection} from the default + * {@link Configuration} defined in {@link #getRoot()}. + * *

* If the root contains no defaults, or the defaults doesn't contain a * value for this path, or the value at this path is not a {@link - * com.boydti.fawe.configuration.ConfigurationSection} then this will return null. + * ConfigurationSection} then this will return null. + *

* * @return Equivalent section in root configuration */ - com.boydti.fawe.configuration.ConfigurationSection getDefaultSection(); + ConfigurationSection getDefaultSection(); /** * Sets the default value in the root at the given path as provided. - *

- * If no source {@link com.boydti.fawe.configuration.Configuration} was provided as a default - * collection, then a new {@link com.boydti.fawe.configuration.MemoryConfiguration} will be created to - * hold the new default value. - *

- * If value is null, the value will be removed from the default - * Configuration source. - *

- * If the value as returned by {@link #getDefaultSection()} is null, then - * this will create a new section at the path, replacing anything that may - * have existed there previously. * - * @param path Path of the value to set. + *

+ * If no source {@link Configuration} was provided as a default collection, then a new {@link + * MemoryConfiguration} will be created to hold the new default value. + *

+ * + *

+ * If value is null, the value will be removed from the default Configuration source. + *

+ * + *

+ * If the value as returned by {@link #getDefaultSection()} is null, then this will create a new + * section at the path, replacing anything that may have existed there previously. + *

+ * + * @param path Path of the value to set. * @param value Value to set the default to. * @throws IllegalArgumentException Thrown if path is null. */ diff --git a/worldedit-core/src/main/java/com/boydti/fawe/configuration/MemorySection.java b/worldedit-core/src/main/java/com/boydti/fawe/configuration/MemorySection.java index 4663c7067..d84eba71e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/configuration/MemorySection.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/configuration/MemorySection.java @@ -295,7 +295,8 @@ public class MemorySection implements com.boydti.fawe.configuration.Configuratio char separator = root.options().pathSeparator(); // i1 is the leading (higher) index // i2 is the trailing (lower) index - int i1 = -1, i2; + int i1 = -1; + int i2; com.boydti.fawe.configuration.ConfigurationSection section = this; while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { String node = path.substring(i2, i1); @@ -377,7 +378,8 @@ public class MemorySection implements com.boydti.fawe.configuration.Configuratio char separator = root.options().pathSeparator(); // i1 is the leading (higher) index // i2 is the trailing (lower) index - int i1 = -1, i2; + int i1 = -1; + int i2; com.boydti.fawe.configuration.ConfigurationSection section = this; while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { String node = path.substring(i2, i1); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/configuration/TypeDescription.java b/worldedit-core/src/main/java/com/boydti/fawe/configuration/TypeDescription.java index 087cc7929..e621bf042 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/configuration/TypeDescription.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/configuration/TypeDescription.java @@ -1,18 +1,3 @@ -/** - * Copyright (c) 2008, http://www.snakeyaml.org - *

- * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.yaml.snakeyaml; import org.yaml.snakeyaml.nodes.Tag; @@ -60,8 +45,7 @@ public final class TypeDescription { /** * Set tag to be used to load or dump the type (class). * - * @param tag - * local or global tag + * @param tag local or global tag */ public void setTag(Tag tag) { this.tag = tag; @@ -72,7 +56,7 @@ public final class TypeDescription { } /** - * Get represented type (class) + * Get the represented type (class). * * @return type (class) to be described. */ @@ -81,12 +65,10 @@ public final class TypeDescription { } /** - * Specify that the property is a type-safe List. + * Specify that the property is a type-safe {@code List}. * - * @param property - * name of the JavaBean property - * @param type - * class of List values + * @param property name of the JavaBean property + * @param type class of List values */ public void putListPropertyType(String property, Class type) { listProperties.put(property, type); @@ -95,8 +77,7 @@ public final class TypeDescription { /** * Get class of List values for provided JavaBean property. * - * @param property - * property name + * @param property property name * @return class of List values */ public Class getListPropertyType(String property) { @@ -104,14 +85,11 @@ public final class TypeDescription { } /** - * Specify that the property is a type-safe Map. + * Specify that the property is a type-safe {@code Map}. * - * @param property - * property name of this JavaBean - * @param key - * class of keys in Map - * @param value - * class of values in Map + * @param property property name of this JavaBean + * @param key class of keys in Map + * @param value class of values in Map */ public void putMapPropertyType(String property, Class key, Class value) { @@ -120,10 +98,9 @@ public final class TypeDescription { } /** - * Get keys type info for this JavaBean + * Get keys type info for this JavaBean. * - * @param property - * property name of this JavaBean + * @param property property name of this JavaBean * @return class of keys in the Map */ public Class getMapKeyType(String property) { @@ -131,10 +108,9 @@ public final class TypeDescription { } /** - * Get values type info for this JavaBean + * Get values type info for this JavaBean. * - * @param property - * property name of this JavaBean + * @param property property name of this JavaBean * @return class of values in the Map */ public Class getMapValueType(String property) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/configuration/Yaml.java b/worldedit-core/src/main/java/com/boydti/fawe/configuration/Yaml.java index 01dee77db..1b94c11d1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/configuration/Yaml.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/configuration/Yaml.java @@ -35,10 +35,10 @@ import java.util.regex.Pattern; */ public class Yaml { protected final Resolver resolver; - private String name; protected BaseConstructor constructor; protected Representer representer; protected DumperOptions dumperOptions; + private String name; /** * Create Yaml instance. It is safe to create a few instances and use them @@ -212,19 +212,19 @@ public class Yaml { /** *

* Serialize a Java object into a YAML string. Override the default root tag - * with rootTag. + * with {@code rootTag}. *

* *

- * This method is similar to Yaml.dump(data) except that the + * This method is similar to {@code Yaml.dump(data)} except that the * root tag for the whole document is replaced with the given tag. This has * two main uses. *

* *

* First, if the root tag is replaced with a standard YAML tag, such as - * Tag.MAP, then the object will be dumped as a map. The root - * tag will appear as !!map, or blank (implicit !!map). + * {@code Tag.MAP}, then the object will be dumped as a map. The root + * tag will appear as {@code !!map}, or blank (implicit !!map). *

* *

@@ -237,11 +237,11 @@ public class Yaml { * @param data Java object to be serialized to YAML * @param rootTag the tag for the whole YAML document. The tag should be Tag.MAP * for a JavaBean to make the tag disappear (to use implicit tag - * !!map). If null is provided then the standard tag + * !!map). If {@code null} is provided then the standard tag * with the full class name is used. * @param flowStyle flow style for the whole document. See Chapter 10. Collection * Styles http://yaml.org/spec/1.1/#id930798. If - * null is provided then the flow style from + * {@code null} is provided then the flow style from * DumperOptions is used. * @return YAML String */ @@ -261,11 +261,11 @@ public class Yaml { /** *

* Serialize a Java object into a YAML string. Override the default root tag - * with Tag.MAP. + * with {@code Tag.MAP}. *

*

- * This method is similar to Yaml.dump(data) except that the - * root tag for the whole document is replaced with Tag.MAP tag + * This method is similar to {@code Yaml.dump(data)} except that the + * root tag for the whole document is replaced with {@code Tag.MAP} tag * (implicit !!map). *

*

@@ -300,18 +300,6 @@ public class Yaml { return emitter.getEvents(); } - private static class SilentEmitter implements Emitable { - private List events = new ArrayList<>(100); - - public List getEvents() { - return events; - } - - public void emit(Event event) throws IOException { - events.add(event); - } - } - /** * Parse the only YAML document in a String and produce the corresponding * Java object. (Because the encoding in known BOM is not respected.) @@ -420,18 +408,6 @@ public class Yaml { return new YamlIterable(result); } - private static class YamlIterable implements Iterable { - private Iterator iterator; - - public YamlIterable(Iterator iterator) { - this.iterator = iterator; - } - - public Iterator iterator() { - return iterator; - } - } - /** * Parse all YAML documents in a String and produce corresponding Java * objects. (Because the encoding in known BOM is not respected.) The @@ -499,26 +475,13 @@ public class Yaml { return new NodeIterable(result); } - private static class NodeIterable implements Iterable { - private Iterator iterator; - - public NodeIterable(Iterator iterator) { - this.iterator = iterator; - } - - public Iterator iterator() { - return iterator; - } - } - /** * Add an implicit scalar detector. If an implicit scalar value matches the * given regexp, the corresponding tag is assigned to the scalar. * * @param tag tag to assign to the node * @param regexp regular expression to match against - * @param first a sequence of possible initial characters or null (which means - * any). + * @param first a sequence of possible initial characters or null (which means any). */ public void addImplicitResolver(Tag tag, Pattern regexp, String first) { resolver.addImplicitResolver(tag, regexp, first); @@ -541,7 +504,7 @@ public class Yaml { } /** - * Set a meaningful name to be shown in toString() + * Set a meaningful name to be shown in {@code toString()}. * * @param name human readable name */ @@ -574,6 +537,51 @@ public class Yaml { return new EventIterable(result); } + public void setBeanAccess(BeanAccess beanAccess) { + constructor.getPropertyUtils().setBeanAccess(beanAccess); + representer.getPropertyUtils().setBeanAccess(beanAccess); + } + + + private static class SilentEmitter implements Emitable { + private List events = new ArrayList<>(100); + + public List getEvents() { + return events; + } + + public void emit(Event event) throws IOException { + events.add(event); + } + } + + + private static class YamlIterable implements Iterable { + private Iterator iterator; + + public YamlIterable(Iterator iterator) { + this.iterator = iterator; + } + + public Iterator iterator() { + return iterator; + } + } + + + private static class NodeIterable implements Iterable { + private Iterator iterator; + + public NodeIterable(Iterator iterator) { + this.iterator = iterator; + } + + public Iterator iterator() { + return iterator; + } + } + + private static class EventIterable implements Iterable { private Iterator iterator; @@ -586,9 +594,4 @@ public class Yaml { } } - public void setBeanAccess(BeanAccess beanAccess) { - constructor.getPropertyUtils().setBeanAccess(beanAccess); - representer.getPropertyUtils().setBeanAccess(beanAccess); - } - } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/configuration/file/YamlConfigurationOptions.java b/worldedit-core/src/main/java/com/boydti/fawe/configuration/file/YamlConfigurationOptions.java index f84d30310..5cf55ed18 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/configuration/file/YamlConfigurationOptions.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/configuration/file/YamlConfigurationOptions.java @@ -40,7 +40,7 @@ public class YamlConfigurationOptions extends FileConfigurationOptions { } /** - * Gets how much spaces should be used to indent each line. + * Gets how many spaces should be used to indent each line. * *

* The minimum value this may be is 2, and the maximum is 9. @@ -53,10 +53,11 @@ public class YamlConfigurationOptions extends FileConfigurationOptions { } /** - * Sets how much spaces should be used to indent each line. + * Sets how many spaces should be used to indent each line. + * *

* The minimum value this may be is 2, and the maximum is 9. - * + *

* @param value New indent * @return This object, for chaining */ diff --git a/worldedit-core/src/main/java/com/boydti/fawe/database/DBHandler.java b/worldedit-core/src/main/java/com/boydti/fawe/database/DBHandler.java index 720fd671f..c362be76b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/database/DBHandler.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/database/DBHandler.java @@ -12,7 +12,7 @@ public class DBHandler { private final Logger log = LoggerFactory.getLogger(Config.class); - public final static DBHandler IMP = new DBHandler(); + public static final DBHandler IMP = new DBHandler(); private Map databases = new ConcurrentHashMap<>(8, 0.9f, 1); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/database/RollbackDatabase.java b/worldedit-core/src/main/java/com/boydti/fawe/database/RollbackDatabase.java index a0219955c..f358498e7 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/database/RollbackDatabase.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/database/RollbackDatabase.java @@ -39,21 +39,33 @@ public class RollbackDatabase extends AsyncNotifyQueue { private final World world; private Connection connection; - private @Language("sql") String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS `{0}edits` (`player` BLOB(16) NOT NULL,`id` INT NOT NULL, `time` INT NOT NULL,`x1` INT NOT NULL,`x2` INT NOT NULL,`z1` INT NOT NULL,`z2` INT NOT NULL,`y1` INT NOT NULL, `y2` INT NOT NULL, `size` INT NOT NULL, `command` VARCHAR, PRIMARY KEY (player, id))"; - private @Language("sql") String UPDATE_TABLE1 = "ALTER TABLE `{0}edits` ADD COLUMN `command` VARCHAR"; - private @Language("sql") String UPDATE_TABLE2 = "alter table `{0}edits` add size int default 0 not null"; - private @Language("sql") String INSERT_EDIT = "INSERT OR REPLACE INTO `{0}edits` (`player`,`id`,`time`,`x1`,`x2`,`z1`,`z2`,`y1`,`y2`,`command`,`size`) VALUES(?,?,?,?,?,?,?,?,?,?,?)"; - private @Language("sql") String PURGE = "DELETE FROM `{0}edits` WHERE `time`? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? AND `player`=? ORDER BY `time` DESC, `id` DESC"; - private @Language("sql") String GET_EDITS_USER_ASC = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? AND `player`=? ORDER BY `time` ASC, `id` ASC"; - private @Language("sql") String GET_EDITS = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? ORDER BY `time` DESC, `id` DESC"; - private @Language("sql") String GET_EDITS_ASC = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? ORDER BY `time` , `id` "; - private @Language("sql") String GET_EDIT_USER = "SELECT * FROM `{0}edits` WHERE `player`=? AND `id`=?"; + @Language("SQLite") + private String createTable = "CREATE TABLE IF NOT EXISTS `{0}edits` (`player` BLOB(16) NOT NULL,`id` INT NOT NULL, `time` INT NOT NULL,`x1` INT NOT NULL,`x2` INT NOT NULL,`z1` INT NOT NULL,`z2` INT NOT NULL,`y1` INT NOT NULL, `y2` INT NOT NULL, `size` INT NOT NULL, `command` VARCHAR, PRIMARY KEY (player, id))"; + @Language("SQLite") + private String updateTable1 = "ALTER TABLE `{0}edits` ADD COLUMN `command` VARCHAR"; + @Language("SQLite") + private String updateTable2 = "alter table `{0}edits` add size int default 0 not null"; + @Language("SQLite") + private String insertEdit = "INSERT OR REPLACE INTO `{0}edits` (`player`,`id`,`time`,`x1`,`x2`,`z1`,`z2`,`y1`,`y2`,`command`,`size`) VALUES(?,?,?,?,?,?,?,?,?,?,?)"; + @Language("SQLite") + private String purge = "DELETE FROM `{0}edits` WHERE `time`? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? AND `player`=? ORDER BY `time` DESC, `id` DESC"; + @Language("SQLite") + private String getEditsUserAsc = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? AND `player`=? ORDER BY `time` ASC, `id` ASC"; + @Language("SQLite") + private String getEdits = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? ORDER BY `time` DESC, `id` DESC"; + @Language("SQLite") + private String getEditsAsc = "SELECT * FROM `{0}edits` WHERE `time`>? AND `x2`>=? AND `x1`<=? AND `z2`>=? AND `z1`<=? AND `y2`>=? AND `y1`<=? ORDER BY `time` , `id` "; + @Language("SQLite") + private String getEditUser = "SELECT * FROM `{0}edits` WHERE `player`=? AND `id`=?"; - private @Language("sql") String DELETE_EDITS_USER = "DELETE FROM `{0}edits` WHERE `player`=? AND `time`>? AND `x2`>=? AND `x1`<=? AND `y2`>=? AND `y1`<=? AND `z2`>=? AND `z1`<=?"; - private @Language("sql") String DELETE_EDIT_USER = "DELETE FROM `{0}edits` WHERE `player`=? AND `id`=?"; + @Language("SQLite") + private String deleteEditsUser = "DELETE FROM `{0}edits` WHERE `player`=? AND `time`>? AND `x2`>=? AND `x1`<=? AND `y2`>=? AND `y1`<=? AND `z2`>=? AND `z1`<=?"; + @Language("SQLite") + private String deleteEditUser = "DELETE FROM `{0}edits` WHERE `player`=? AND `id`=?"; - private ConcurrentLinkedQueue historyChanges = new ConcurrentLinkedQueue<>(); + private final ConcurrentLinkedQueue historyChanges = new ConcurrentLinkedQueue<>(); RollbackDatabase(World world) throws SQLException, ClassNotFoundException { super((t, e) -> e.printStackTrace()); @@ -63,18 +75,18 @@ public class RollbackDatabase extends AsyncNotifyQueue { connection = openConnection(); // update vars - CREATE_TABLE = CREATE_TABLE.replace("{0}", prefix); - UPDATE_TABLE1 = UPDATE_TABLE1.replace("{0}", prefix); - UPDATE_TABLE2 = UPDATE_TABLE2.replace("{0}", prefix); - INSERT_EDIT = INSERT_EDIT.replace("{0}", prefix); - PURGE = PURGE.replace("{0}", prefix); - GET_EDITS_USER = GET_EDITS_USER.replace("{0}", prefix); - GET_EDITS_USER_ASC = GET_EDITS_USER_ASC.replace("{0}", prefix); - GET_EDITS = GET_EDITS.replace("{0}", prefix); - GET_EDITS_ASC = GET_EDITS_ASC.replace("{0}", prefix); - GET_EDIT_USER = GET_EDIT_USER.replace("{0}", prefix); - DELETE_EDITS_USER = DELETE_EDITS_USER.replace("{0}", prefix); - DELETE_EDIT_USER = DELETE_EDIT_USER.replace("{0}", prefix); + createTable = createTable.replace("{0}", prefix); + updateTable1 = updateTable1.replace("{0}", prefix); + updateTable2 = updateTable2.replace("{0}", prefix); + insertEdit = insertEdit.replace("{0}", prefix); + purge = purge.replace("{0}", prefix); + getEditsUser = getEditsUser.replace("{0}", prefix); + getEditsUserAsc = getEditsUserAsc.replace("{0}", prefix); + getEdits = getEdits.replace("{0}", prefix); + getEditsAsc = getEditsAsc.replace("{0}", prefix); + getEditUser = getEditUser.replace("{0}", prefix); + deleteEditsUser = deleteEditsUser.replace("{0}", prefix); + deleteEditUser = deleteEditUser.replace("{0}", prefix); try { init().get(); @@ -90,22 +102,24 @@ public class RollbackDatabase extends AsyncNotifyQueue { public Future init() { return call(() -> { - try (PreparedStatement stmt = connection.prepareStatement(CREATE_TABLE)) { + try (PreparedStatement stmt = connection.prepareStatement(createTable)) { stmt.executeUpdate(); } - try (PreparedStatement stmt = connection.prepareStatement(UPDATE_TABLE1)) { + try (PreparedStatement stmt = connection.prepareStatement(updateTable1)) { stmt.executeUpdate(); - } catch (SQLException ignore) {} // Already updated - try (PreparedStatement stmt = connection.prepareStatement(UPDATE_TABLE2)) { + } catch (SQLException ignored) { + } // Already updated + try (PreparedStatement stmt = connection.prepareStatement(updateTable2)) { stmt.executeUpdate(); - } catch (SQLException ignore) {} // Already updated + } catch (SQLException ignored) { + } // Already updated return true; }); } public Future delete(UUID uuid, int id) { return call(() -> { - try (PreparedStatement stmt = connection.prepareStatement(DELETE_EDIT_USER)) { + try (PreparedStatement stmt = connection.prepareStatement(deleteEditUser)) { stmt.setBytes(1, toBytes(uuid)); stmt.setInt(2, id); return stmt.executeUpdate(); @@ -115,7 +129,7 @@ public class RollbackDatabase extends AsyncNotifyQueue { public Future getEdit(@NotNull UUID uuid, int id) { return call(() -> { - try (PreparedStatement stmt = connection.prepareStatement(GET_EDIT_USER)) { + try (PreparedStatement stmt = connection.prepareStatement(getEditUser)) { stmt.setBytes(1, toBytes(uuid)); stmt.setInt(2, id); ResultSet result = stmt.executeQuery(); @@ -155,7 +169,7 @@ public class RollbackDatabase extends AsyncNotifyQueue { long now = System.currentTimeMillis() / 1000; final int then = (int) (now - diff); return call(() -> { - try (PreparedStatement stmt = connection.prepareStatement(PURGE)) { + try (PreparedStatement stmt = connection.prepareStatement(purge)) { stmt.setInt(1, then); return stmt.executeUpdate(); } @@ -172,8 +186,8 @@ public class RollbackDatabase extends AsyncNotifyQueue { Future future = call(() -> { try { int count = 0; - String stmtStr = ascending ? uuid == null ? GET_EDITS_ASC : GET_EDITS_USER_ASC : - uuid == null ? GET_EDITS : GET_EDITS_USER; + String stmtStr = ascending ? uuid == null ? getEditsAsc : getEditsUserAsc : + uuid == null ? getEdits : getEditsUser; try (PreparedStatement stmt = connection.prepareStatement(stmtStr)) { stmt.setInt(1, (int) (minTime / 1000)); stmt.setInt(2, pos1.getBlockX()); @@ -197,7 +211,7 @@ public class RollbackDatabase extends AsyncNotifyQueue { } while (result.next()); } if (delete && uuid != null) { - try (PreparedStatement stmt = connection.prepareStatement(DELETE_EDITS_USER)) { + try (PreparedStatement stmt = connection.prepareStatement(deleteEditsUser)) { stmt.setInt(1, (int) (minTime / 1000)); stmt.setInt(2, pos1.getBlockX()); stmt.setInt(3, pos2.getBlockX()); @@ -239,7 +253,7 @@ public class RollbackDatabase extends AsyncNotifyQueue { RollbackOptimizedHistory[] copy = IntStream.range(0, size) .mapToObj(i -> historyChanges.poll()).toArray(RollbackOptimizedHistory[]::new); - try (PreparedStatement stmt = connection.prepareStatement(INSERT_EDIT)) { + try (PreparedStatement stmt = connection.prepareStatement(insertEdit)) { // `player`,`id`,`time`,`x1`,`x2`,`z1`,`z2`,`y1`,`y2`,`command`,`size`) VALUES(?,?,?,?,?,?,?,?,?,?,?)" for (RollbackOptimizedHistory change : copy) { UUID uuid = change.getUUID(); @@ -310,7 +324,7 @@ public class RollbackDatabase extends AsyncNotifyQueue { } /** - * Gets the connection with the database + * Gets the connection with the database. * * @return Connection with the database, null if none */ @@ -326,7 +340,7 @@ public class RollbackDatabase extends AsyncNotifyQueue { } /** - * Closes the connection with the database + * Closes the connection with the database. * * @return true if successful * @throws SQLException if the connection cannot be closed @@ -346,7 +360,7 @@ public class RollbackDatabase extends AsyncNotifyQueue { } /** - * Checks if a connection is open with the database + * Checks if a connection is open with the database. * * @return true if the connection is open */ diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAChunk.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAChunk.java index 7b0b7973e..6bc7cf282 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAChunk.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAChunk.java @@ -37,6 +37,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.UUID; @@ -276,7 +277,7 @@ public class MCAChunk implements IChunk { int ordinal = blocks[i]; int palette = blockToPalette[ordinal]; if (palette == Integer.MAX_VALUE) { -// BlockState state = BlockTypesCache.states[ordinal]; + //BlockState state = BlockTypesCache.states[ordinal]; blockToPalette[ordinal] = palette = num_palette; paletteToBlock[num_palette] = ordinal; num_palette++; @@ -308,7 +309,7 @@ public class MCAChunk implements IChunk { String valueStr = value.toString(); if (Character.isUpperCase(valueStr.charAt(0))) { System.out.println("Invalid uppercase value " + value); - valueStr = valueStr.toLowerCase(); + valueStr = valueStr.toLowerCase(Locale.ROOT); } out.writeNamedTag(key, valueStr); } @@ -337,13 +338,13 @@ public class MCAChunk implements IChunk { } -// out.writeNamedTagName("BlockLight", NBTConstants.TYPE_BYTE_ARRAY); -// out.writeInt(2048); -// out.write(blockLight, layer << 11, 1 << 11); -// -// out.writeNamedTagName("SkyLight", NBTConstants.TYPE_BYTE_ARRAY); -// out.writeInt(2048); -// out.write(skyLight, layer << 11, 1 << 11); + /* out.writeNamedTagName("BlockLight", NBTConstants.TYPE_BYTE_ARRAY); + out.writeInt(2048); + out.write(blockLight, layer << 11, 1 << 11); + + out.writeNamedTagName("SkyLight", NBTConstants.TYPE_BYTE_ARRAY); + out.writeInt(2048); + out.write(skyLight, layer << 11, 1 << 11); */ out.writeEndTag(); @@ -397,9 +398,13 @@ public class MCAChunk implements IChunk { @Override public boolean isEmpty() { - if (deleted) return true; + if (deleted) { + return true; + } for (boolean hasSection : hasSections) { - if (hasSection) return false; + if (hasSection) { + return false; + } } return true; } @@ -450,15 +455,19 @@ public class MCAChunk implements IChunk { } - @Override public void removeSectionLighting(int layer, boolean sky) {} + @Override public void removeSectionLighting(int layer, boolean sky) { + } - @Override public void setFullBright(int layer) {} + @Override public void setFullBright(int layer) { + } @Override - public void setLightLayer(int layer, char[] toSet) {} + public void setLightLayer(int layer, char[] toSet) { + } @Override - public void setSkyLightLayer(int layer, char[] toSet) {} + public void setSkyLightLayer(int layer, char[] toSet) { + } @Override public void setEntity(CompoundTag entityTag) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFile.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFile.java index b496ce375..1ff28d5ac 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFile.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFile.java @@ -66,7 +66,8 @@ public class MCAFile extends ExtentBatchProcessorHolder implements Trimable, ICh private RandomAccessFile raf; private boolean deleted; - private int X, Z; + private int X; + private int Z; private MCAChunk[] chunks; private boolean[] chunkInitialized; private Object[] locks; @@ -336,7 +337,7 @@ public class MCAFile extends ExtentBatchProcessorHolder implements Trimable, ICh if (size != 0) { try { onEach.accept(getChunk(x, z)); - } catch (Throwable ignore) { + } catch (Throwable ignored) { } } } @@ -462,7 +463,9 @@ public class MCAFile extends ExtentBatchProcessorHolder implements Trimable, ICh } public void close() { - if (raf == null) return; + if (raf == null) { + return; + } synchronized (raf) { if (raf != null) { flush(true); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/streamer/StreamDelegate.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/streamer/StreamDelegate.java index 1b0cc5b9a..0bf7db2eb 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/streamer/StreamDelegate.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/streamer/StreamDelegate.java @@ -100,7 +100,9 @@ public class StreamDelegate { default: { for (; index < keys.length; index++) { byte[] key = keys[index]; - if (key.length < nameLength) continue; + if (key.length < nameLength) { + continue; + } if (key.length == nameLength) { break; } else { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/DataAnglePattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/DataAnglePattern.java index fc4016206..f873f9917 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/DataAnglePattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/DataAnglePattern.java @@ -42,7 +42,9 @@ public class DataAnglePattern extends AbstractPattern { public BaseBlock apply(BlockVector3 position) { BlockState block = extent.getBlock(position); int slope = getSlope(block, position, extent); - if (slope == -1) return block.toBaseBlock(); + if (slope == -1) { + return block.toBaseBlock(); + } int data = Math.min(slope, 255) >> 4; return block.withPropertyId(data).toBaseBlock(); } @@ -51,7 +53,9 @@ public class DataAnglePattern extends AbstractPattern { public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { BlockState block = extent.getBlock(getPosition); int slope = getSlope(block, getPosition, extent); - if (slope == -1) return false; + if (slope == -1) { + return false; + } int data = Math.min(slope, 255) >> 4; return extent.setBlock(setPosition, block.withPropertyId(data)); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/FaweLimit.java b/worldedit-core/src/main/java/com/boydti/fawe/object/FaweLimit.java index 9b67bb819..77ecf68e1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/FaweLimit.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/FaweLimit.java @@ -136,72 +136,100 @@ public class FaweLimit { } public void THROW_MAX_CHANGES() { - if (MAX_CHANGES-- <= 0) throw FaweCache.MAX_CHANGES; + if (MAX_CHANGES-- <= 0) { + throw FaweCache.MAX_CHANGES; + } } public void THROW_MAX_FAILS() { - if (MAX_FAILS-- <= 0) throw FaweCache.MAX_CHECKS; + if (MAX_FAILS-- <= 0) { + throw FaweCache.MAX_CHECKS; + } } public void THROW_MAX_CHECKS() { - if (MAX_CHECKS-- <= 0) throw FaweCache.MAX_CHECKS; + if (MAX_CHECKS-- <= 0) { + throw FaweCache.MAX_CHECKS; + } } public void THROW_MAX_ITERATIONS() { - if (MAX_ITERATIONS-- <= 0) throw FaweCache.MAX_ITERATIONS; + if (MAX_ITERATIONS-- <= 0) { + throw FaweCache.MAX_ITERATIONS; + } } public void THROW_MAX_BLOCKSTATES() { - if (MAX_BLOCKSTATES-- <= 0) throw FaweCache.MAX_TILES; + if (MAX_BLOCKSTATES-- <= 0) { + throw FaweCache.MAX_TILES; + } } public void THROW_MAX_ENTITIES() { - if (MAX_ENTITIES-- <= 0) throw FaweCache.MAX_ENTITIES; + if (MAX_ENTITIES-- <= 0) { + throw FaweCache.MAX_ENTITIES; + } } public void THROW_MAX_CHANGES(int amt) { - if ((MAX_CHANGES -= amt) <= 0) throw FaweCache.MAX_CHANGES; + if ((MAX_CHANGES -= amt) <= 0) { + throw FaweCache.MAX_CHANGES; + } } public void THROW_MAX_CHANGES(long amt) { - if ((MAX_CHANGES -= amt) <= 0) throw FaweCache.MAX_CHANGES; + if ((MAX_CHANGES -= amt) <= 0) { + throw FaweCache.MAX_CHANGES; + } } public void THROW_MAX_FAILS(int amt) { - if ((MAX_FAILS -= amt) <= 0) throw FaweCache.MAX_CHECKS; + if ((MAX_FAILS -= amt) <= 0) { + throw FaweCache.MAX_CHECKS; + } } public void THROW_MAX_CHECKS(int amt) { - if ((MAX_CHECKS -= amt) <= 0) throw FaweCache.MAX_CHECKS; + if ((MAX_CHECKS -= amt) <= 0) { + throw FaweCache.MAX_CHECKS; + } } public void THROW_MAX_CHECKS(long amt) { - if ((MAX_CHECKS -= amt) <= 0) throw FaweCache.MAX_CHECKS; + if ((MAX_CHECKS -= amt) <= 0) { + throw FaweCache.MAX_CHECKS; + } } public void THROW_MAX_ITERATIONS(int amt) { - if ((MAX_ITERATIONS -= amt) <= 0) throw FaweCache.MAX_ITERATIONS; + if ((MAX_ITERATIONS -= amt) <= 0) { + throw FaweCache.MAX_ITERATIONS; + } } public void THROW_MAX_BLOCKSTATES(int amt) { - if ((MAX_BLOCKSTATES -= amt) <= 0) throw FaweCache.MAX_TILES; + if ((MAX_BLOCKSTATES -= amt) <= 0) { + throw FaweCache.MAX_TILES; + } } public void THROW_MAX_ENTITIES(int amt) { - if ((MAX_ENTITIES -= amt) <= 0) throw FaweCache.MAX_ENTITIES; + if ((MAX_ENTITIES -= amt) <= 0) { + throw FaweCache.MAX_ENTITIES; + } } public boolean isUnlimited() { - return MAX_CHANGES == Integer.MAX_VALUE && - MAX_FAILS == Integer.MAX_VALUE && - MAX_CHECKS == Integer.MAX_VALUE && - MAX_ITERATIONS == Integer.MAX_VALUE && - MAX_BLOCKSTATES == Integer.MAX_VALUE && - MAX_ENTITIES == Integer.MAX_VALUE && - MAX_HISTORY == Integer.MAX_VALUE && - INVENTORY_MODE == 0 && - SPEED_REDUCTION == 0 && - FAST_PLACEMENT && - (STRIP_NBT == null || STRIP_NBT.isEmpty()); + return MAX_CHANGES == Integer.MAX_VALUE + && MAX_FAILS == Integer.MAX_VALUE + && MAX_CHECKS == Integer.MAX_VALUE + && MAX_ITERATIONS == Integer.MAX_VALUE + && MAX_BLOCKSTATES == Integer.MAX_VALUE + && MAX_ENTITIES == Integer.MAX_VALUE + && MAX_HISTORY == Integer.MAX_VALUE + && INVENTORY_MODE == 0 + && SPEED_REDUCTION == 0 + && FAST_PLACEMENT + && (STRIP_NBT == null || STRIP_NBT.isEmpty()); } public void set(FaweLimit limit) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/RegionWrapper.java b/worldedit-core/src/main/java/com/boydti/fawe/object/RegionWrapper.java index 8513d3ee6..13afbea38 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/RegionWrapper.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/RegionWrapper.java @@ -5,7 +5,7 @@ import com.sk89q.worldedit.regions.CuboidRegion; @Deprecated public class RegionWrapper extends CuboidRegion { - private final static RegionWrapper GLOBAL = new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE); + private static final RegionWrapper GLOBAL = new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE); public int minX; public int maxX; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BlendBall.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BlendBall.java index cef6d9271..c431f588d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BlendBall.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BlendBall.java @@ -21,7 +21,6 @@ public class BlendBall implements Brush { int ty = position.getBlockY(); int tz = position.getBlockZ(); -// Map frequency = Maps.newHashMap(); int[] frequency = new int[BlockTypes.size()]; int maxY = editSession.getMaximumPoint().getBlockY(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BlobBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BlobBrush.java index 5856d922b..79159cba3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BlobBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BlobBrush.java @@ -64,9 +64,9 @@ public class BlobBrush implements Brush { } } else { AffineTransform transform = new AffineTransform() - .rotateX(ThreadLocalRandom.current().nextInt(360)) - .rotateY(ThreadLocalRandom.current().nextInt(360)) - .rotateZ(ThreadLocalRandom.current().nextInt(360)); + .rotateX(ThreadLocalRandom.current().nextInt(360)) + .rotateY(ThreadLocalRandom.current().nextInt(360)) + .rotateZ(ThreadLocalRandom.current().nextInt(360)); double manScaleX = 1.25 + seedX * 0.5; double manScaleY = 1.25 + seedY * 0.5; @@ -93,9 +93,7 @@ public class BlobBrush implements Brush { double manDist = xScaled + yScaled + zScaled; double distSqr = x * x * modX + z * z * modZ + y * y * modY; - double distance = - Math.sqrt(distSqr) * sphericity + - MathMan.max(manDist, xScaled * manScaleX, yScaled * manScaleY, zScaled * manScaleZ) * roughness; + double distance = Math.sqrt(distSqr) * sphericity + MathMan.max(manDist, xScaled * manScaleX, yScaled * manScaleY, zScaled * manScaleZ) * roughness; double noise = this.amplitude * SimplexNoise.noise(seedX + x * distort, seedZ + z * distort, seedZ + z * distort); if (distance + distance * noise < radius) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CatenaryBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CatenaryBrush.java index 85fc928e6..eb95ef9e0 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CatenaryBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CatenaryBrush.java @@ -6,6 +6,7 @@ import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.command.tool.brush.Brush; +import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.Vector3; @@ -17,7 +18,9 @@ import java.util.List; public class CatenaryBrush implements Brush, ResettableTool { - private final boolean shell, select, direction; + private final boolean shell; + private final boolean select; + private final boolean direction; private final double slack; private BlockVector3 pos1; @@ -34,21 +37,25 @@ public class CatenaryBrush implements Brush, ResettableTool { @Override public void build(EditSession editSession, BlockVector3 pos2, final Pattern pattern, double size) throws MaxChangedBlocksException { boolean visual = editSession.getExtent() instanceof VisualExtent; + Player player = editSession.getPlayer(); + if (player == null) { + return; //todo throw error + } if (pos1 == null || pos2.equals(pos1)) { if (!visual) { pos1 = pos2; - editSession.getPlayer().print(Caption.of("fawe.worldedit.brush.brush.line.primary", pos2)); + player.print(Caption.of("fawe.worldedit.brush.brush.line.primary", pos2)); } return; } if (this.vertex == null) { vertex = getVertex(pos1.toVector3(), pos2.toVector3(), slack); if (this.direction) { - editSession.getPlayer().print(Caption.of("fawe.worldedit.brush.brush.catenary.direction", 2)); + player.print(Caption.of("fawe.worldedit.brush.brush.catenary.direction", 2)); return; } } else if (this.direction) { - Location loc = editSession.getPlayer().getLocation(); + Location loc = player.getLocation(); Vector3 facing = loc.getDirection().normalize(); BlockVector3 midpoint = pos1.add(pos2).divide(2); BlockVector3 offset = midpoint.subtract(vertex); @@ -62,7 +69,7 @@ public class CatenaryBrush implements Brush, ResettableTool { e.printStackTrace(); } if (!visual) { - editSession.getPlayer().print(TranslatableComponent.of("fawe.worldedit.brush.brush.line.secondary")); + player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.line.secondary")); if (!select) { pos1 = null; return; @@ -78,7 +85,9 @@ public class CatenaryBrush implements Brush, ResettableTool { } public static BlockVector3 getVertex(Vector3 pos1, Vector3 pos2, double lenPercent) { - if (lenPercent <= 1) return pos1.add(pos2).divide(2).toBlockPoint(); + if (lenPercent <= 1) { + return pos1.add(pos2).divide(2).toBlockPoint(); + } double curveLen = pos1.distance(pos2) * lenPercent; double dy = pos2.getY() - pos1.getY(); double dx = pos2.getX() - pos1.getX(); @@ -86,8 +95,10 @@ public class CatenaryBrush implements Brush, ResettableTool { double dh = Math.sqrt(dx * dx + dz * dz); double g = Math.sqrt(curveLen * curveLen - dy * dy) / 2; double a = 0.00001; - for (;g < a * Math.sinh(dh/(2 * a)); a *= 1.00001); - double vertX = (dh-a*Math.log((curveLen + dy)/(curveLen - dy)))/2.0; + for (; g < a * Math.sinh(dh / (2 * a)); a *= 1.00001) { + ; + } + double vertX = (dh - a * Math.log((curveLen + dy) / (curveLen - dy))) / 2.0; double z = (dh / 2) / a; double oY = (dy - curveLen * (Math.cosh(z) / Math.sinh(z))) / 2; double vertY = a * 1 + oY; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CopyPastaBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CopyPastaBrush.java index 8dce2d4a0..0d0c36a5f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CopyPastaBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CopyPastaBrush.java @@ -90,7 +90,7 @@ public class CopyPastaBrush implements Brush, ResettableTool { ClipboardHolder holder = new ClipboardHolder(newClipboard); session.setClipboard(holder); int blocks = builder.size(); - player.print(Caption.of("fawe.worldedit.copy.command.copy" , blocks)); + player.print(Caption.of("fawe.worldedit.copy.command.copy", blocks)); } else { AffineTransform transform = null; if (randomRotate) { @@ -99,7 +99,9 @@ public class CopyPastaBrush implements Brush, ResettableTool { transform = transform.rotateY(rotate); } if (autoRotate) { - if (transform == null) transform = new AffineTransform(); + if (transform == null) { + transform = new AffineTransform(); + } Location loc = player.getLocation(); float yaw = loc.getYaw(); float pitch = loc.getPitch(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ErodeBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ErodeBrush.java index 9176c8b23..b043ffc43 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ErodeBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ErodeBrush.java @@ -20,7 +20,10 @@ import java.util.Arrays; public class ErodeBrush implements Brush { private static final BlockVector3[] FACES_TO_CHECK = Direction.valuesOf(Direction.Flag.CARDINAL).stream().map(Direction::toBlockVector).toArray(BlockVector3[]::new); - private final int erodeFaces, erodeRecursion, fillFaces, fillRecursion; + private final int erodeFaces; + private final int erodeRecursion; + private final int fillFaces; + private final int fillRecursion; public ErodeBrush() { this(2, 1, 5, 1); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/FallingSphere.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/FallingSphere.java index 08250d50c..302a60841 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/FallingSphere.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/FallingSphere.java @@ -30,7 +30,9 @@ public class FallingSphere implements Brush { int ax = px + x; int remainingY = remaining - xx; - if (remainingY < 0) continue; + if (remainingY < 0) { + continue; + } int yRadius = MathMan.usqrt(remainingY); int startY = Math.max(0, py - yRadius); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/HeightBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/HeightBrush.java index 8ac75c973..d489d2fe2 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/HeightBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/HeightBrush.java @@ -99,11 +99,19 @@ public class HeightBrush implements Brush { for (int z = minZ; z <= maxZ; z++, zIndex += width) { int zz = bz + z; int index = zIndex + (bx + minX); - if (index < minIndex) continue; - if (index >= metaHeight.length) break; + if (index < minIndex) { + continue; + } + if (index >= metaHeight.length) { + break; + } for (int x = minX; x <= maxX; x++, index++) { - if (index < 0) continue; - if (index >= metaHeight.length) break; + if (index < 0) { + continue; + } + if (index >= metaHeight.length) { + break; + } int xx = bx + x; int currentBlockHeight = hmmg.getHeight(index); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ImageBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ImageBrush.java index c710e20d4..d13f83bbe 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ImageBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ImageBrush.java @@ -76,7 +76,6 @@ public class ImageBrush implements Brush { float yaw = loc.getYaw(); float pitch = loc.getPitch(); AffineTransform transform = new AffineTransform().rotateY((-yaw) % 360).rotateX((pitch - 90) % 360).inverse(); - RecursiveVisitor visitor = new RecursiveVisitor( new ImageBrushMask(solid, center, transform, scale, centerImageX, centerImageZ, width, height, colorFunction, editSession, session.getTextureUtil()), vector -> true, Integer.MAX_VALUE); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/InspectBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/InspectBrush.java index 48cb92e72..2e786bc9b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/InspectBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/InspectBrush.java @@ -107,7 +107,7 @@ public class InspectBrush extends BrushTool { player.print(msg); } } - player.print(Caption.of("fawe.worldedit.tool.tool.inspect.info.footer" , count)); + player.print(Caption.of("fawe.worldedit.tool.tool.inspect.info.footer", count)); } catch (IOException e) { System.out.println("IOE"); throw new RuntimeException(e); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/LineBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/LineBrush.java index 16b03844d..e38bf08e2 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/LineBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/LineBrush.java @@ -11,7 +11,9 @@ import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; public class LineBrush implements Brush, ResettableTool { - private final boolean shell, select, flat; + private final boolean shell; + private final boolean select; + private final boolean flat; private BlockVector3 pos1; public LineBrush(boolean shell, boolean select, boolean flat) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RockBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RockBrush.java index 32cf5ba18..9b6016f94 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RockBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RockBrush.java @@ -33,9 +33,9 @@ public class RockBrush implements Brush { double distort = this.frequency / size; - double modX = 1d/radius.getX(); - double modY = 1d/radius.getY(); - double modZ = 1d/radius.getZ(); + double modX = 1D / radius.getX(); + double modY = 1D / radius.getY(); + double modZ = 1D / radius.getZ(); int radiusSqr = (int) (size * size); int sizeInt = (int) size * 2; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SurfaceSpline.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SurfaceSpline.java index ddfb6cbf6..a4225e4d2 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SurfaceSpline.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SurfaceSpline.java @@ -39,10 +39,14 @@ public class SurfaceSpline implements Brush { boolean vis = editSession.getExtent() instanceof VisualExtent; if (path.isEmpty() || !pos.equals(path.get(path.size() - 1))) { int max = editSession.getNearestSurfaceTerrainBlock(pos.getBlockX(), pos.getBlockZ(), pos.getBlockY(), 0, editSession.getMaxY()); - if (max == -1) return; + if (max == -1) { + return; + } path.add(BlockVector3.at(pos.getBlockX(), max, pos.getBlockZ())); editSession.getPlayer().printInfo(TranslatableComponent.of("fawe.worldedit.brush.spline.primary.2")); - if (!vis) return; + if (!vis) { + return; + } } final List nodes = new ArrayList<>(path.size()); final KochanekBartelsInterpolation interpol = new KochanekBartelsInterpolation(); @@ -64,7 +68,9 @@ public class SurfaceSpline implements Brush { final int tipz = (int) tipv.getZ(); int tipy = MathMan.roundInt(tipv.getY()); tipy = editSession.getNearestSurfaceTerrainBlock(tipx, tipz, tipy, 0, maxY); - if (tipy == -1) continue; + if (tipy == -1) { + continue; + } if (radius == 0) { BlockVector3 set = mutable.setComponents(tipx, tipy, tipz); try { @@ -81,19 +87,25 @@ public class SurfaceSpline implements Brush { LocalBlockVectorSet newSet = new LocalBlockVectorSet(); final int ceilrad = (int) Math.ceil(radius); for (BlockVector3 v : vset) { - final int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ(); + final int tipx = v.getBlockX(); + final int tipy = v.getBlockY(); + final int tipz = v.getBlockZ(); for (int loopx = tipx - ceilrad; loopx <= tipx + ceilrad; loopx++) { for (int loopz = tipz - ceilrad; loopz <= tipz + ceilrad; loopz++) { if (MathMan.hypot2(loopx - tipx, 0, loopz - tipz) <= radius2) { int y = editSession.getNearestSurfaceTerrainBlock(loopx, loopz, v.getBlockY(), 0, maxY); - if (y == -1) continue; + if (y == -1) { + continue; + } newSet.add(loopx, y, loopz); } } } } editSession.setBlocks(newSet, pattern); - if (!vis) path.clear(); + if (!vis) { + path.clear(); + } } editSession.getPlayer().printInfo(TranslatableComponent.of("fawe.worldedit.brush.spline.secondary")); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/ArrayHeightMap.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/ArrayHeightMap.java index bbfdab2ff..fcf10b0c7 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/ArrayHeightMap.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/ArrayHeightMap.java @@ -4,9 +4,11 @@ public class ArrayHeightMap extends ScalableHeightMap { // The heights private final byte[][] height; // The height map width/length - private final int width, length; + private final int width; + private final int length; // The size to width/length ratio - private double rx, rz; + private double rx; + private double rz; public ArrayHeightMap(byte[][] height) { setSize(5); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/HeightMap.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/HeightMap.java index 8e64eb64e..0a495dc38 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/HeightMap.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/HeightMap.java @@ -13,7 +13,7 @@ import com.sk89q.worldedit.util.Location; import java.util.concurrent.ThreadLocalRandom; public interface HeightMap { - + double getHeight(int x, int z); void setSize(int size); @@ -89,7 +89,9 @@ public interface HeightMap { height = tmpY = session.getNearestSurfaceLayer(xx, zz, tmpY, 0, maxY); } else { height = tmpY = session.getNearestSurfaceTerrainBlock(xx, zz, tmpY, 0, maxY); - if (height == -1) continue; + if (height == -1) { + continue; + } } oldData[index] = height; if (height == 0) { @@ -131,7 +133,9 @@ public interface HeightMap { height = session.getNearestSurfaceLayer(xx, zz, height, 0, maxY); } else { height = session.getNearestSurfaceTerrainBlock(xx, zz, height, 0, maxY); - if (height == -1) continue; + if (height == -1) { + continue; + } } oldData[index] = height; if (height == 0) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/Scroll.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/Scroll.java index 17584f04f..c17a11584 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/Scroll.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/Scroll.java @@ -15,6 +15,7 @@ import com.sk89q.worldedit.function.pattern.Pattern; import java.io.IOException; import java.util.Arrays; import java.util.List; +import java.util.Locale; public abstract class Scroll implements ScrollTool { private BrushTool tool; @@ -32,7 +33,7 @@ public abstract class Scroll implements ScrollTool { public static Scroll fromArguments(BrushTool tool, Player player, LocalSession session, String actionArgs, boolean message) { String[] split = actionArgs.split(" "); - Action mode = Action.valueOf(split[0].toUpperCase()); + Action mode = Action.valueOf(split[0].toUpperCase(Locale.ROOT)); List args = Arrays.asList(Arrays.copyOfRange(split, 1, split.length)); return fromArguments(tool, player, session, mode, args, message); } @@ -47,7 +48,9 @@ public abstract class Scroll implements ScrollTool { return null; case CLIPBOARD: if (arguments.size() != 2) { - if (message) player.print(Caption.of("fawe.error.command.syntax" , "clipboard [file]")); + if (message) { + player.print(Caption.of("fawe.error.command.syntax", "clipboard [file]")); + } return null; } String filename = arguments.get(1); @@ -62,7 +65,9 @@ public abstract class Scroll implements ScrollTool { } case MASK: if (arguments.size() < 2) { - if (message) player.print(Caption.of("fawe.error.command.syntax" , "mask [mask 1] [mask 2] [mask 3]...")); + if (message) { + player.print(Caption.of("fawe.error.command.syntax", "mask [mask 1] [mask 2] [mask 3]...")); + } return null; } Mask[] masks = new Mask[arguments.size() - 1]; @@ -73,7 +78,9 @@ public abstract class Scroll implements ScrollTool { return (new ScrollMask(tool, masks)); case PATTERN: if (arguments.size() < 2) { - if (message) player.print(Caption.of("fawe.error.command.syntax" , "pattern [pattern 1] [pattern 2] [pattern 3]...")); + if (message) { + player.print(Caption.of("fawe.error.command.syntax", "pattern [pattern 1] [pattern 2] [pattern 3]...")); + } return null; } Pattern[] patterns = new Pattern[arguments.size() - 1]; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/ClipboardSpline.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/ClipboardSpline.java index 849ba060e..133d6a614 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/ClipboardSpline.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/ClipboardSpline.java @@ -33,34 +33,44 @@ public class ClipboardSpline extends Spline { private LocalBlockVectorSet buffer; /** - * Constructor without position-correction. Use this constructor for an interpolation implementation which does not need position-correction. - *

- * Be advised that currently subsequent changes to the interpolation parameters may not be supported. - * @param editSession The EditSession which will be used when pasting the clipboard content + * Constructor without position-correction. Use this constructor for an interpolation + * implementation which does not need position-correction. + * + * @param editSession The EditSession which will be used when pasting the clipboard content * @param clipboardHolder The clipboard that will be pasted along the spline - * @param interpolation An implementation of the interpolation algorithm used to calculate the curve + * @param interpolation An implementation of the interpolation algorithm used to calculate + * the curve + * @apiNote Be advised that currently subsequent changes to the interpolation parameters may + * not be supported. */ public ClipboardSpline(EditSession editSession, ClipboardHolder clipboardHolder, Interpolation interpolation) { this(editSession, clipboardHolder, interpolation, new AffineTransform(), -1); } /** - * Constructor with position-correction. Use this constructor for an interpolation implementation that needs position-correction. + * Constructor with position-correction. Use this constructor for an interpolation + * implementation that needs position-correction. + * *

- * Some interpolation implementations calculate the position on the curve (used by {@link #pastePosition(double)}) - * based on an equidistant distribution of the nodes on the curve. For example: on a spline with 5 nodes position 0.0 would refer - * to the first node, 0.25 to the second, 0.5 to the third, ... .
- * By providing this method with the amount of nodes used by the interpolation implementation the distribution of the - * nodes is converted to a proportional distribution based on the length between two adjacent nodes calculated by {@link Interpolation#arcLength(double, double)}.
- * This means that the distance between two positions used to paste the clipboard (e.g., 0.75 - 0.5 = 0.25) on the curve - * will always amount to that part of the length (e.g., 40 units) of the curve. In this example it would amount to - * 0.25 × 40 = 10 units of curve length between these two positions. - *

- * Be advised that currently subsequent changes to the interpolation parameters may not be supported. - * @param editSession The EditSession which will be used when pasting the clipboard content + * Some interpolation implementations calculate the position on the curve (used by {@link + * #pastePosition(double)}) based on an equidistant distribution of the nodes on the curve. For + * example: on a spline with 5 nodes position 0.0 would refer to the first node, 0.25 to the + * second, 0.5 to the third, ... .
By providing this method with the amount of nodes used by + * the interpolation implementation the distribution of the nodes is converted to a proportional + * distribution based on the length between two adjacent nodes calculated by {@link + * Interpolation#arcLength(double, double)}.
This means that the distance between two + * positions used to paste the clipboard (e.g., 0.75 - 0.5 = 0.25) on the curve will always + * amount to that part of the length (e.g., 40 units) of the curve. In this example it would + * amount to 0.25 × 40 = 10 units of curve length between these two positions. + *

+ * + * @param editSession The EditSession which will be used when pasting the clipboard content * @param clipboardHolder The clipboard that will be pasted along the spline - * @param interpolation An implementation of the interpolation algorithm used to calculate the curve - * @param nodeCount The number of nodes provided to the interpolation object + * @param interpolation An implementation of the interpolation algorithm used to calculate + * the curve + * @param nodeCount The number of nodes provided to the interpolation object + * @apiNote Be advised that currently subsequent changes to the interpolation parameters may + * not be supported. */ public ClipboardSpline(EditSession editSession, ClipboardHolder clipboardHolder, Interpolation interpolation, Transform transform, int nodeCount) { super(editSession, interpolation, nodeCount); @@ -72,7 +82,7 @@ public class ClipboardSpline extends Spline { Region region = clipboard.getRegion(); BlockVector3 origin = clipboard.getOrigin(); -// center = region.getCenter().setY(origin.getY() - 1); + // center = region.getCenter().setY(origin.getY() - 1); center = region.getCenter().withY(origin.getY() - 1).toBlockPoint(); this.centerOffset = center.subtract(center.round()); this.center = center.subtract(centerOffset); 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 429c7b9a9..b8b582d78 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 @@ -2,7 +2,6 @@ package com.boydti.fawe.object.brush.sweep; import com.boydti.fawe.object.brush.ResettableTool; import com.boydti.fawe.object.brush.visualization.VisualExtent; -import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EmptyClipboardException; import com.sk89q.worldedit.LocalSession; @@ -12,15 +11,12 @@ import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldedit.math.MutableVector3; import com.sk89q.worldedit.math.Vector2; -import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.interpolation.Interpolation; import com.sk89q.worldedit.math.interpolation.KochanekBartelsInterpolation; import com.sk89q.worldedit.math.interpolation.Node; import com.sk89q.worldedit.math.interpolation.ReparametrisingInterpolation; import com.sk89q.worldedit.math.transform.AffineTransform; -import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; @@ -91,7 +87,7 @@ public class SweepBrush implements Brush, ResettableTool { ClipboardSpline spline = new ClipboardSpline(editSession, holder, interpol, transform, nodes.size()); - if (dimensions.getBlockX() > dimensions.getBlockZ()) { + if (dimensions.getBlockX() > dimensions.getBlockZ()) { spline.setDirection(Vector2.at(0, 1)); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/CFIDrawer.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/CFIDrawer.java index 57715ea79..566711e88 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/CFIDrawer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/CFIDrawer.java @@ -45,7 +45,7 @@ public final class CFIDrawer { int start = i * size; int end = Math.min(heights.length, start + size); pool.submit((Runnable) () -> { - for (int index = start; index < end; index ++) { + for (int index = start; index < end; index++) { int height = (heights[index] & 0xFF); char ordinal; if ((ordinal = overlay[index]) == 0) { @@ -105,11 +105,11 @@ public final class CFIDrawer { int c0 = tu.getBiome(biomes[index] & 0xFF).grassCombined; int c2 = getBiome(biomes, index + 1 + width, index); int c1 = getBiome(biomes, index - 1 - width, index); -// int c3 = getBiome(biomes, index + width, index); -// int c4 = getBiome(biomes, index - width, index); - int r = ((c0 >> 16) & 0xFF) + ((c1 >> 16) & 0xFF) + ((c2 >> 16) & 0xFF);// + ((c3 >> 16) & 0xFF) + ((c4 >> 16) & 0xFF); - int g = ((c0 >> 8) & 0xFF) + ((c1 >> 8) & 0xFF) + ((c2 >> 8) & 0xFF);// + ((c3 >> 8) & 0xFF) + ((c4 >> 8) & 0xFF); - int b = ((c0) & 0xFF) + ((c1) & 0xFF) + ((c2) & 0xFF);// + ((c3) & 0xFF) + ((c4) & 0xFF); + // int c3 = getBiome(biomes, index + width, index); + // int c4 = getBiome(biomes, index - width, index); + int r = ((c0 >> 16) & 0xFF) + ((c1 >> 16) & 0xFF) + ((c2 >> 16) & 0xFF); // + ((c3 >> 16) & 0xFF) + ((c4 >> 16) & 0xFF); + int g = ((c0 >> 8) & 0xFF) + ((c1 >> 8) & 0xFF) + ((c2 >> 8) & 0xFF); // + ((c3 >> 8) & 0xFF) + ((c4 >> 8) & 0xFF); + int b = ((c0) & 0xFF) + ((c1) & 0xFF) + ((c2) & 0xFF); // + ((c3) & 0xFF) + ((c4) & 0xFF); r = r * 85 >> 8; g = g * 85 >> 8; b = b * 85 >> 8; @@ -117,7 +117,9 @@ public final class CFIDrawer { } private final int getBiome(byte[] biomes, int newIndex, int index) { - if (newIndex < 0 || newIndex >= biomes.length) newIndex = index; + if (newIndex < 0 || newIndex >= biomes.length) { + newIndex = index; + } int biome = biomes[newIndex] & 0xFF; return tu.getBiome(biome).grassCombined; } @@ -125,16 +127,18 @@ public final class CFIDrawer { private int getSlope(byte[] heights, int width, int index, int height) { return ( + getHeight(heights, index + 1, height) -// + getHeight(heights, index + width, height) - + getHeight(heights, index + width + 1, height) - - getHeight(heights, index - 1, height) -// - getHeight(heights, index - width, height) - - getHeight(heights, index - width - 1, height) - ); + // + getHeight(heights, index + width, height) + + getHeight(heights, index + width + 1, height) + - getHeight(heights, index - 1, height) + // - getHeight(heights, index - width, height) + - getHeight(heights, index - width - 1, height) + ); } private int getHeight(byte[] heights, int index, int height) { - if (index < 0 || index >= heights.length) return height; + if (index < 0 || index >= heights.length) { + return height; + } return heights[index] & 0xFF; } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/HeightMapMCAGenerator.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/HeightMapMCAGenerator.java index 64f9a332a..ccebad451 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/HeightMapMCAGenerator.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/HeightMapMCAGenerator.java @@ -799,7 +799,7 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr try { blocks.set(x, y, z, combined); return true; - } catch (IndexOutOfBoundsException ignore) { + } catch (IndexOutOfBoundsException ignored) { return false; } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/MCAWriter.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/MCAWriter.java index ce5c98868..878df9fa7 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/MCAWriter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/cfi/MCAWriter.java @@ -20,7 +20,8 @@ public abstract class MCAWriter implements Extent { private final int length; private final int width; private final int area; - private int OX, OZ; + private int OX; + private int OZ; public MCAWriter(int width, int length, File regionFolder) { @@ -91,7 +92,7 @@ public abstract class MCAWriter implements Extent { final ForkJoinPool pool = new ForkJoinPool(); int tcx = (width - 1) >> 4; int tcz = (length - 1) >> 4; - try (CleanableThreadLocal chunkStore = createCache()){ + try (CleanableThreadLocal chunkStore = createCache()) { final ThreadLocal byteStore1 = ThreadLocal.withInitial(() -> new byte[500000]); final ThreadLocal byteStore2 = ThreadLocal.withInitial(() -> new byte[500000]); final ThreadLocal deflateStore = ThreadLocal diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/change/StreamChange.java b/worldedit-core/src/main/java/com/boydti/fawe/object/change/StreamChange.java index 015bab727..8fafe7de3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/change/StreamChange.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/change/StreamChange.java @@ -22,7 +22,7 @@ public interface StreamChange { default void flushChanges(File file) throws IOException { try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { try (LZ4BlockOutputStream compressed = new LZ4BlockOutputStream(out)) { -// compressed.setLevel(Deflater.BEST_SPEED); + // compressed.setLevel(Deflater.BEST_SPEED); try (FaweOutputStream fos = new FaweOutputStream(compressed)) { flushChanges(fos); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AbstractChangeSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AbstractChangeSet.java index e0c4b84c5..ee9b3b7c6 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AbstractChangeSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AbstractChangeSet.java @@ -278,6 +278,10 @@ public abstract class AbstractChangeSet implements ChangeSet, IBatchProcessor { } } + public boolean isEmpty() { + return waitingCombined.get() == 0 && waitingAsync.get() == 0 && size() == 0; + } + public void add(BlockVector3 loc, BaseBlock from, BaseBlock to) { int x = loc.getBlockX(); int y = loc.getBlockY(); @@ -308,10 +312,6 @@ public abstract class AbstractChangeSet implements ChangeSet, IBatchProcessor { } } - public boolean isEmpty() { - return waitingCombined.get() == 0 && waitingAsync.get() == 0 && size() == 0; - } - public void add(int x, int y, int z, int combinedFrom, BaseBlock to) { try { if (to.hasNbtData()) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AbstractDelegateChangeSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AbstractDelegateChangeSet.java index c47e1218b..f4a6af0d5 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AbstractDelegateChangeSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AbstractDelegateChangeSet.java @@ -29,21 +29,6 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet { this.waitingAsync = parent.waitingAsync; } - @Override - public void closeAsync() { - parent.closeAsync(); - } - - @Override - public void flush() { - parent.flush(); - } - - @Override - public void close() throws IOException { - parent.close(); - } - public final AbstractChangeSet getParent() { return parent; } @@ -54,28 +39,13 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet { } @Override - public void add(int x, int y, int z, int combinedFrom, int combinedTo) { - parent.add(x, y, z, combinedFrom, combinedTo); + public void closeAsync() { + parent.closeAsync(); } @Override - public Iterator backwardIterator() { - return parent.backwardIterator(); - } - - @Override - public Iterator forwardIterator() { - return parent.forwardIterator(); - } - - @Override - public int size() { - return parent.size(); - } - - @Override - public void addBiomeChange(int x, int z, BiomeType from, BiomeType to) { - parent.addBiomeChange(x, z, from, to); + public void flush() { + parent.flush(); } @Override @@ -98,6 +68,11 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet { parent.addEntityCreate(tag); } + @Override + public void addBiomeChange(int x, int z, BiomeType from, BiomeType to) { + parent.addBiomeChange(x, z, from, to); + } + @Override public Iterator getIterator(BlockBag blockBag, int mode, boolean redo) { return parent.getIterator(blockBag, mode, redo); @@ -108,16 +83,6 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet { return parent.getIterator(redo); } - @Override - public void delete() { - parent.delete(); - } - - @Override - public ChangeSetSummary summarize(Region region, boolean shallow) { - return parent.summarize(region, shallow); - } - @Override public EditSession toEditSession(Player player) { return parent.toEditSession(player); @@ -128,6 +93,11 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet { return parent.toEditSession(player, regions); } + @Override + public void add(int x, int y, int z, int combinedFrom, int combinedTo) { + parent.add(x, y, z, combinedFrom, combinedTo); + } + @Override public void add(EntityCreate change) { parent.add(change); @@ -159,13 +129,28 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet { } @Override - public boolean isEmpty() { - return parent.isEmpty(); + public void add(int x, int y, int z, int combinedFrom, BaseBlock to) { + parent.add(x, y, z, combinedFrom, to); } @Override - public void add(int x, int y, int z, int combinedFrom, BaseBlock to) { - parent.add(x, y, z, combinedFrom, to); + public Iterator backwardIterator() { + return parent.backwardIterator(); + } + + @Override + public Iterator forwardIterator() { + return parent.forwardIterator(); + } + + @Override + public void close() throws IOException { + parent.close(); + } + + @Override + public boolean isEmpty() { + return parent.isEmpty(); } @Override @@ -187,4 +172,19 @@ public class AbstractDelegateChangeSet extends AbstractChangeSet { public void setRecordChanges(boolean recordChanges) { parent.setRecordChanges(recordChanges); } + + @Override + public int size() { + return parent.size(); + } + + @Override + public void delete() { + parent.delete(); + } + + @Override + public ChangeSetSummary summarize(Region region, boolean shallow) { + return parent.summarize(region, shallow); + } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/BlockBagChangeSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/BlockBagChangeSet.java index c3d17c2a0..e1ede0d10 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/BlockBagChangeSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/BlockBagChangeSet.java @@ -33,9 +33,8 @@ public class BlockBagChangeSet extends AbstractDelegateChangeSet { * * @return a block bag, which may be null if none is used */ - public @Nullable - BlockBag getBlockBag() { + public BlockBag getBlockBag() { return blockBag; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/CFIChangeSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/CFIChangeSet.java index 39220f70e..3059013f0 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/CFIChangeSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/CFIChangeSet.java @@ -25,16 +25,22 @@ public class CFIChangeSet extends AbstractChangeSet { int max = MainUtil.getMaxFileId(folder); this.file = new File(folder, max + ".cfi"); File parent = this.file.getParentFile(); - if (!parent.exists()) this.file.getParentFile().mkdirs(); - if (!this.file.exists()) this.file.createNewFile(); + if (!parent.exists()) { + this.file.getParentFile().mkdirs(); + } + if (!this.file.exists()) { + this.file.createNewFile(); + } hmmg.flushChanges(file); } @Override - public void close() {} + public void close() { + } @Override - public void closeAsync() {} + public void closeAsync() { + } @Override public void add(int x, int y, int z, int combinedFrom, int combinedTo) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/DiskStorageHistory.java b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/DiskStorageHistory.java index edc368509..296887527 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/DiskStorageHistory.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/DiskStorageHistory.java @@ -65,13 +65,13 @@ public class DiskStorageHistory extends FaweStreamChangeSet { super(world); init(uuid, world.getName()); } - + private void init(UUID uuid, String worldName) { File folder = MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.HISTORY + File.separator + worldName + File.separator + uuid); int max = MainUtil.getMaxFileId(folder); init(uuid, max); } - + public DiskStorageHistory(World world, UUID uuid, int index) { super(world); init(uuid, index); @@ -83,7 +83,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet { this.index = i; initFiles(folder); } - + private void initFiles(File folder) { nbtfFile = new File(folder, index + ".nbtf"); nbttFile = new File(folder, index + ".nbtt"); @@ -174,12 +174,24 @@ public class DiskStorageHistory extends FaweStreamChangeSet { super.flush(); synchronized (this) { try { - if (osBD != null) osBD.flush(); - if (osBIO != null) osBIO.flush(); - if (osNBTF != null) osNBTF.flush(); - if (osNBTT != null) osNBTT.flush(); - if (osENTCF != null) osENTCF.flush(); - if (osENTCT != null) osENTCT.flush(); + if (osBD != null) { + osBD.flush(); + } + if (osBIO != null) { + osBIO.flush(); + } + if (osNBTF != null) { + osNBTF.flush(); + } + if (osNBTT != null) { + osNBTT.flush(); + } + if (osENTCF != null) { + osENTCF.flush(); + } + if (osENTCT != null) { + osENTCT.flush(); + } } catch (Exception e) { e.printStackTrace(); } 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 4da062af4..3eb4d6cb7 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 @@ -40,7 +40,7 @@ public abstract class FaweStreamChangeSet extends AbstractChangeSet { public FaweStreamChangeSet(World world) { this(world, Settings.IMP.HISTORY.COMPRESSION_LEVEL, Settings.IMP.HISTORY.STORE_REDO, Settings.IMP.HISTORY.SMALL_EDITS); } - + public FaweStreamChangeSet(World world, int compression, boolean storeRedo, boolean smallLoc) { super(world); this.compression = compression; @@ -129,7 +129,9 @@ public abstract class FaweStreamChangeSet extends AbstractChangeSet { } if (mode == 1 || mode == 4) { // small posDel = new FaweStreamPositionDelegate() { - int lx, ly, lz; + int lx; + int ly; + int lz; @Override public void write(OutputStream out, int x, int y, int z) throws IOException { @@ -169,7 +171,9 @@ public abstract class FaweStreamChangeSet extends AbstractChangeSet { } else { posDel = new FaweStreamPositionDelegate() { final byte[] buffer = new byte[5]; - int lx, ly, lz; + int lx; + int ly; + int lz; @Override public void write(OutputStream stream, int x, int y, int z) throws IOException { @@ -696,7 +700,7 @@ public abstract class FaweStreamChangeSet extends AbstractChangeSet { public Change next() { try { return current.next(); - } catch (Throwable ignore) { + } catch (Throwable ignored) { if (i >= iterators.length - 1) { throw new NoSuchElementException("End of iterator"); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/MemoryOptimizedHistory.java b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/MemoryOptimizedHistory.java index 634391b73..be091c4ee 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/MemoryOptimizedHistory.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/MemoryOptimizedHistory.java @@ -53,12 +53,24 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet { super.flush(); synchronized (this) { try { - if (idsStream != null) idsStreamZip.flush(); - if (biomeStream != null) biomeStreamZip.flush(); - if (entCStream != null) entCStreamZip.flush(); - if (entRStream != null) entRStreamZip.flush(); - if (tileCStream != null) tileCStreamZip.flush(); - if (tileRStream != null) tileRStreamZip.flush(); + if (idsStream != null) { + idsStreamZip.flush(); + } + if (biomeStream != null) { + biomeStreamZip.flush(); + } + if (entCStream != null) { + entCStreamZip.flush(); + } + if (entRStream != null) { + entRStreamZip.flush(); + } + if (tileCStream != null) { + tileCStreamZip.flush(); + } + if (tileRStream != null) { + tileRStreamZip.flush(); + } } catch (IOException e) { e.printStackTrace(); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/CPUOptimizedClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/CPUOptimizedClipboard.java index 5de49ba4d..859b3a233 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/CPUOptimizedClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/CPUOptimizedClipboard.java @@ -39,7 +39,7 @@ public class CPUOptimizedClipboard extends LinearClipboard { nbtMapLoc = new HashMap<>(); nbtMapIndex = new HashMap<>(); } - + @Override public boolean hasBiomes() { return biomes != null; @@ -66,7 +66,9 @@ public class CPUOptimizedClipboard extends LinearClipboard { @Override public void streamBiomes(IntValueReader task) { - if (!hasBiomes()) return; + if (!hasBiomes()) { + return; + } int index = 0; try { for (int z = 0; z < getLength(); z++) { 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 4d1692d1a..b0dcd3035 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 @@ -57,7 +57,7 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable private static int HEADER_SIZE = 14; private static final int MAX_SIZE = Short.MAX_VALUE - Short.MIN_VALUE; - + private final HashMap nbtMap; private final File file; @@ -114,7 +114,7 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable throw new RuntimeException(e); } } - + @Override public URI getURI() { return file.toURI(); @@ -207,7 +207,9 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable @Override public void streamBiomes(IntValueReader task) { - if (!hasBiomes()) return; + if (!hasBiomes()) { + return; + } int index = 0; int mbbIndex = HEADER_SIZE + (getVolume() << 1); try { @@ -266,7 +268,9 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable } private void closeDirectBuffer(ByteBuffer cb) { - if (cb == null || !cb.isDirect()) return; + if (cb == null || !cb.isDirect()) { + return; + } // we could use this type cast and call functions without reflection code, // but static import from sun.* package is risky for non-SUN virtual machine. //try { ((sun.nio.ch.DirectBuffer)cb).cleaner().clean(); } catch (Exception ex) { } @@ -373,7 +377,7 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable int diskIndex = HEADER_SIZE + (index << 1); char ordinal = byteBuffer.getChar(diskIndex); return BlockState.getFromOrdinal(ordinal); - } catch (IndexOutOfBoundsException ignore) { + } catch (IndexOutOfBoundsException ignored) { } catch (Exception e) { e.printStackTrace(); } @@ -448,7 +452,7 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable public List getEntities() { return new ArrayList<>(entities); } - + @Override public List getEntities(Region region) { return new ArrayList<>(entities.stream().filter(e -> region.contains(e.getLocation().toBlockPoint())).collect(Collectors.toList())); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/MemoryOptimizedClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/MemoryOptimizedClipboard.java index 35064a85a..341fa7d4e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/MemoryOptimizedClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/MemoryOptimizedClipboard.java @@ -91,7 +91,9 @@ public class MemoryOptimizedClipboard extends LinearClipboard { @Override public void streamBiomes(IntValueReader task) { - if (!hasBiomes()) return; + if (!hasBiomes()) { + return; + } try { int index = 0; for (int z = 0; z < getLength(); z++) { @@ -308,7 +310,7 @@ public class MemoryOptimizedClipboard extends LinearClipboard { public List getEntities(Region region) { return new ArrayList<>(entities.stream().filter(e -> region.contains(e.getLocation().toBlockPoint())).collect(Collectors.toList())); } - + @Override public void removeEntity(Entity entity) { if (entity instanceof ClipboardEntity) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/MultiClipboardHolder.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/MultiClipboardHolder.java index 8792062a3..cb48f5d99 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/MultiClipboardHolder.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/MultiClipboardHolder.java @@ -28,7 +28,9 @@ public class MultiClipboardHolder extends URIClipboardHolder { public MultiClipboardHolder(URI uri, URIClipboardHolder... addHolders) { this(uri); - for (URIClipboardHolder h : addHolders) add(h); + for (URIClipboardHolder h : addHolders) { + add(h); + } } public MultiClipboardHolder(Clipboard clipboard) { @@ -44,7 +46,9 @@ public class MultiClipboardHolder extends URIClipboardHolder { public void remove(URI uri) { cached = null; if (getUri().equals(uri)) { - for (ClipboardHolder holder : holders) holder.close(); + for (ClipboardHolder holder : holders) { + holder.close(); + } holders.clear(); return; } @@ -66,7 +70,9 @@ public class MultiClipboardHolder extends URIClipboardHolder { if (holder instanceof URIClipboardHolder) { URIClipboardHolder uriHolder = (URIClipboardHolder) holder; URI uri = uriHolder.getURI(clipboard); - if (uri != null) return uri; + if (uri != null) { + return uri; + } } } return null; @@ -79,7 +85,9 @@ public class MultiClipboardHolder extends URIClipboardHolder { @Override public boolean contains(Clipboard clipboard) { for (ClipboardHolder holder : holders) { - if (holder.contains(clipboard)) return true; + if (holder.contains(clipboard)) { + return true; + } } return false; } @@ -128,7 +136,9 @@ public class MultiClipboardHolder extends URIClipboardHolder { return true; } for (URIClipboardHolder uch : holders) { - if (uch.contains(uri)) return true; + if (uch.contains(uri)) { + return true; + } } return false; } @@ -154,7 +164,9 @@ public class MultiClipboardHolder extends URIClipboardHolder { for (ClipboardHolder holder : getHolders()) { if (holder instanceof URIClipboardHolder) { URI uri = ((URIClipboardHolder) holder).getUri(); - if (!uri.toString().isEmpty()) set.add(uri); + if (!uri.toString().isEmpty()) { + set.add(uri); + } } } return set; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/URIClipboardHolder.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/URIClipboardHolder.java index 5b324a52b..56a2120af 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/URIClipboardHolder.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/URIClipboardHolder.java @@ -24,8 +24,9 @@ public class URIClipboardHolder extends ClipboardHolder { } /** + * Get the original clipboard source, typically a file or uri. * @deprecated If a holder has multiple sources, this will return an empty URI - * @return The original source of this clipboard (usually a file or url) + * @return the source of the clipboard */ @Deprecated public URI getUri() { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/WorldCopyClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/WorldCopyClipboard.java index e04b0a68c..2dfc31ec1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/WorldCopyClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/WorldCopyClipboard.java @@ -61,7 +61,9 @@ public class WorldCopyClipboard extends ReadOnlyClipboard { @Override public List getEntities() { - if (!hasEntities) return new ArrayList<>(); + if (!hasEntities) { + return new ArrayList<>(); + } return getExtent().getEntities(getRegion()); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BitArray.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BitArray.java index 7717382d0..e42ddc081 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BitArray.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BitArray.java @@ -33,13 +33,15 @@ public final class BitArray { } public final void set(int index, int value) { - if (longLen == 0) return; + if (longLen == 0) { + return; + } int bitIndexStart = index * bitsPerEntry; int longIndexStart = bitIndexStart >> 6; int localBitIndexStart = bitIndexStart & 63; this.data[longIndexStart] = this.data[longIndexStart] & ~(mask << localBitIndexStart) | (long) value << localBitIndexStart; - if(localBitIndexStart > maxSeqLocIndex) { + if (localBitIndexStart > maxSeqLocIndex) { int longIndexEnd = longIndexStart + 1; int localShiftStart = 64 - localBitIndexStart; int localShiftEnd = bitsPerEntry - localShiftStart; @@ -48,14 +50,16 @@ public final class BitArray { } public final int get(int index) { - if (longLen == 0) return 0; + if (longLen == 0) { + return 0; + } int bitIndexStart = index * bitsPerEntry; int longIndexStart = bitIndexStart >> 6; int localBitIndexStart = bitIndexStart & 63; - if(localBitIndexStart <= maxSeqLocIndex) { - return (int)(this.data[longIndexStart] >>> localBitIndexStart & mask); + if (localBitIndexStart <= maxSeqLocIndex) { + return (int) (this.data[longIndexStart] >>> localBitIndexStart & mask); } else { int localShift = 64 - localBitIndexStart; return (int) ((this.data[longIndexStart] >>> localBitIndexStart | this.data[longIndexStart + 1] << localShift) & mask); @@ -65,7 +69,7 @@ public final class BitArray { public int getLength() { return longLen; } - + public final void fromRaw(int[] arr) { final long[] data = this.data; final int bitsPerEntry = this.bitsPerEntry; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BitArrayUnstretched.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BitArrayUnstretched.java index d5af50a0a..b850aeb87 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BitArrayUnstretched.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/BitArrayUnstretched.java @@ -40,7 +40,9 @@ public final class BitArrayUnstretched { } public final void set(int index, int value) { - if (longLen == 0) return; + if (longLen == 0) { + return; + } int bitIndexStart = index * bitsPerEntry + MathMan.floorZero((double) index / longLen) * emptyBitCount; int longIndexStart = bitIndexStart >> 6; int localBitIndexStart = bitIndexStart & 63; @@ -48,19 +50,21 @@ public final class BitArrayUnstretched { } public final int get(int index) { - if (longLen == 0) return 0; + if (longLen == 0) { + return 0; + } int bitIndexStart = index * bitsPerEntry + MathMan.floorZero((double) index / longLen) * emptyBitCount; int longIndexStart = bitIndexStart >> 6; int localBitIndexStart = bitIndexStart & 63; - return (int)(this.data[longIndexStart] >>> localBitIndexStart & mask); + return (int) (this.data[longIndexStart] >>> localBitIndexStart & mask); } public int getLength() { return longLen; } - + public final void fromRaw(int[] arr) { final long[] data = this.data; final int bitsPerEntry = this.bitsPerEntry; 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 60c82b697..b38d6551a 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 @@ -17,10 +17,12 @@ import java.util.Objects; import java.util.Set; /** - * The BlockVectorSet is a Memory optimized Set for storing BlockVectors - * - Internally it uses a map of Index->LocalBlockVectorSet - * - All BlockVectors must be a valid world coordinate: y=[0,255],x=[-30000000,30000000],z=[-30000000,30000000] - * - This will use ~8 bytes for every 64 BlockVectors (about 800x less than a HashSet) + * The BlockVectorSet is a memory optimized Set for storing {@link BlockVector3}'s. + * + *

+ * It uses about 8 bytes of memory for every 64 {@code BlockVector3}s (about 800 times less than a + * {@code HashSet}. + *

*/ public class BlockVectorSet extends AbstractCollection implements Set { private Int2ObjectMap localSets = new Int2ObjectOpenHashMap<>(); @@ -92,7 +94,7 @@ public class BlockVectorSet extends AbstractCollection implements return new Iterator() { Int2ObjectMap.Entry entry = entries.next(); Iterator entryIter = entry.getValue().iterator(); - MutableBlockVector3 mutable = new MutableBlockVector3(); + final MutableBlockVector3 mutable = new MutableBlockVector3(); @Override public void remove() { @@ -185,7 +187,7 @@ public class BlockVectorSet extends AbstractCollection implements public boolean retainAll(@NotNull Collection c) { Objects.requireNonNull(c); boolean modified = false; - Iterator it = iterator(); + Iterator it = iterator(); while (it.hasNext()) { if (!c.contains(it.next())) { it.remove(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/CleanableThreadLocal.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/CleanableThreadLocal.java index 8e0c15b68..e7369f397 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/CleanableThreadLocal.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/CleanableThreadLocal.java @@ -118,7 +118,7 @@ public class CleanableThreadLocal extends ThreadLocal implements Closeable if (methodRemove != null) { try { methodRemove.invoke(tlm, instance); - } catch (Throwable ignore) { + } catch (Throwable ignored) { } } } catch (NoSuchMethodException e) { @@ -158,7 +158,7 @@ public class CleanableThreadLocal extends ThreadLocal implements Closeable clean(threadLocal); } } - } catch(Exception e) { + } catch (Exception e) { // We will tolerate an exception here and just log it throw new IllegalStateException(e); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/DifferentialArray.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/DifferentialArray.java index 0010823f9..366779659 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/DifferentialArray.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/DifferentialArray.java @@ -139,8 +139,11 @@ public final class DifferentialArray implements DifferentialCollection { } } if (caught != null) { - if (caught instanceof RuntimeException) throw (RuntimeException) caught; - else throw new RuntimeException(caught); + if (caught instanceof RuntimeException) { + throw (RuntimeException) caught; + } else { + throw new RuntimeException(caught); + } } } @@ -277,7 +280,7 @@ public final class DifferentialArray implements DifferentialCollection { changed = true; try { changesBytes[index] += (dataBytes[index] - value); - } catch (NullPointerException ignore) { + } catch (NullPointerException ignored) { changes = (T) (changesBytes = new byte[dataBytes.length]); changesBytes[index] += (dataBytes[index] - value); } @@ -288,7 +291,7 @@ public final class DifferentialArray implements DifferentialCollection { changed = true; try { changesInts[index] += dataInts[index] - value; - } catch (NullPointerException ignore) { + } catch (NullPointerException ignored) { changes = (T) (changesInts = new int[dataInts.length]); changesInts[index] += dataInts[index] - value; } @@ -299,7 +302,7 @@ public final class DifferentialArray implements DifferentialCollection { changed = true; try { changesChars[index] += dataChars[index] - value; - } catch (NullPointerException ignore) { + } catch (NullPointerException ignored) { changes = (T) (changesChars = new char[dataChars.length]); changesChars[index] += dataChars[index] - value; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/DifferentialBlockBuffer.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/DifferentialBlockBuffer.java index 59b1d8a50..80ea9a3f0 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/DifferentialBlockBuffer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/DifferentialBlockBuffer.java @@ -12,8 +12,10 @@ import java.lang.reflect.Array; */ public final class DifferentialBlockBuffer implements DifferentialCollection { - private final int width, length; - private final int t1, t2; + private final int width; + private final int length; + private final int t1; + private final int t2; private char[][][][][] data; private char[][][][][] changes; @@ -63,7 +65,9 @@ public final class DifferentialBlockBuffer implements DifferentialCollection> 4; @@ -154,7 +160,9 @@ public final class DifferentialBlockBuffer implements DifferentialCollection { - private final int width, length; - private final int t1, t2; + private final int width; + private final int length; + private final int t1; + private final int t2; private char[][][][][] data; private char[][][][][] changes; @@ -63,7 +65,9 @@ public final class DifferentialCharBlockBuffer implements DifferentialCollection @Override public void undoChanges(FaweInputStream in) throws IOException { - if (changes != null && changes.length != 0) throw new IllegalStateException("There are uncommitted changes, please flush first"); + if (changes != null && changes.length != 0) { + throw new IllegalStateException("There are uncommitted changes, please flush first"); + } boolean modified = in.readBoolean(); if (modified) { int len = in.readVarInt(); @@ -118,7 +122,9 @@ public final class DifferentialCharBlockBuffer implements DifferentialCollection } public void set(int x, int y, int z, char combined) { - if (combined == 0) combined = 1; + if (combined == 0) { + combined = 1; + } int localX = x & 15; int localZ = z & 15; int chunkX = x >> 4; @@ -154,7 +160,9 @@ public final class DifferentialCharBlockBuffer implements DifferentialCollection } } else { - if (changes == null || changes.length == 0) changes = new char[t1][][][][]; + if (changes == null || changes.length == 0) { + changes = new char[t1][][][][]; + } appendChange(changes, chunkX, chunkZ, localX, localZ, y, (char) (zMap[localX] - combined)); } @@ -166,25 +174,33 @@ public final class DifferentialCharBlockBuffer implements DifferentialCollection if (arr == null) { src[chunkZ] = new char[0][][][]; return; - } else if (arr.length == 0) return; + } else if (arr.length == 0) { + return; + } char[][][] arr2 = arr[chunkX]; if (arr2 == null) { arr[chunkX] = new char[0][][]; return; - } else if (arr2.length == 0) return; + } else if (arr2.length == 0) { + return; + } char[][] yMap = arr2[y]; if (yMap == null) { arr2[y] = new char[0][]; return; - } else if (yMap.length == 0) return; + } else if (yMap.length == 0) { + return; + } char[] zMap = yMap[localZ]; if (zMap == null) { yMap[localZ] = new char[0]; return; - } else if (zMap.length == 0) return; + } else if (zMap.length == 0) { + return; + } char current = zMap[localX]; zMap[localX] = combined; @@ -210,4 +226,4 @@ public final class DifferentialCharBlockBuffer implements DifferentialCollection } zMap[localX] = combined; } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/FastBitSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/FastBitSet.java index bc09373c3..e5349e957 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/FastBitSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/FastBitSet.java @@ -24,22 +24,23 @@ public final class FastBitSet { return (bits[i >> 6] & (1L << (i & 0x3F))) != 0; } - public static final void set(long[] bits, final int i) { + public static void set(long[] bits, final int i) { bits[i >> 6] |= (1L << (i & 0x3F)); } - public static final void clear(long[] bits, final int i) { + public static void clear(long[] bits, final int i) { bits[i >> 6] &= ~(1L << (i & 0x3F)); } - public static final void set(long[] bits, final int i, final boolean v) { - if (v) + public static void set(long[] bits, final int i, final boolean v) { + if (v) { set(bits, i); - else + } else { clear(bits, i); + } } - public static final void setRange(long[] bits, final int b, final int e) { + public static void setRange(long[] bits, final int b, final int e) { final int bt = b >> 6; final int et = e >> 6; if (bt != et) { @@ -51,7 +52,7 @@ public final class FastBitSet { } } - public static final void clearRange(long[] bits, final int b, final int e) { + public static void clearRange(long[] bits, final int b, final int e) { final int bt = b >> 6; final int et = e >> 6; if (bt != et) { @@ -63,53 +64,70 @@ public final class FastBitSet { } } - public static final void setAll(long[] bits) { + public static void setAll(long[] bits) { Arrays.fill(bits, -1L); } - public static final void clearAll(long[] bits) { + public static void clearAll(long[] bits) { Arrays.fill(bits, 0L); } - public static final void invertAll(long[] bits) { - for (int i = 0; i < bits.length; ++i) + public static void invertAll(long[] bits) { + for (int i = 0; i < bits.length; ++i) { bits[i] = ~bits[i]; + } } - public static final void and(long[] bits, final long[] other) { + public static void and(long[] bits, final long[] other) { final int end = Math.min(other.length, bits.length); - for (int i = 0; i < end; ++i) + for (int i = 0; i < end; ++i) { bits[i] &= other[i]; + } } - public static final void or(long[] bits, final long[] other) { + public static void or(long[] bits, final long[] other) { final int end = Math.min(other.length, bits.length); - for (int i = 0; i < end; ++i) + for (int i = 0; i < end; ++i) { bits[i] |= other[i]; + } } - public static final void nand(long[] bits, final long[] other) { + public static void nand(long[] bits, final long[] other) { final int end = Math.min(other.length, bits.length); - for (int i = 0; i < end; ++i) + for (int i = 0; i < end; ++i) { bits[i] = ~(bits[i] & other[i]); + } } - public static final void nor(long[] bits, final long[] other) { + public static void nor(long[] bits, final long[] other) { final int end = Math.min(other.length, bits.length); - for (int i = 0; i < end; ++i) + for (int i = 0; i < end; ++i) { bits[i] = ~(bits[i] | other[i]); + } } - public static final void xor(long[] bits, final long[] other) { + public static void xor(long[] bits, final long[] other) { final int end = Math.min(other.length, bits.length); - for (int i = 0; i < end; ++i) + for (int i = 0; i < end; ++i) { bits[i] ^= other[i]; + } } - public static final long memoryUsage(long[] bits) { + public static long memoryUsage(long[] bits) { return 8L * bits.length; } + private static void fill(final long[] a, final int b, final int e, final long l) { + for (int i = b; i < e; ++i) { + a[i] = l; + } + } + + public static long calculateMemoryUsage(int entries) { + final int numLongs = (entries + 64) >> 6; + return 8L * numLongs; + } + public final boolean get(final int i) { return (bits[i >> 6] & (1L << (i & 0x3F))) != 0; } @@ -123,10 +141,11 @@ public final class FastBitSet { } public final void set(final int i, final boolean v) { - if (v) + if (v) { set(i); - else + } else { clear(i); + } } public final void setRange(final int b, final int e) { @@ -162,45 +181,54 @@ public final class FastBitSet { } public final void invertAll() { - for (int i = 0; i < bits.length; ++i) + for (int i = 0; i < bits.length; ++i) { bits[i] = ~bits[i]; + } } public final void and(final FastBitSet other) { final int end = Math.min(other.bits.length, bits.length); - for (int i = 0; i < end; ++i) + for (int i = 0; i < end; ++i) { bits[i] &= other.bits[i]; + } } public final void or(final FastBitSet other) { final int end = Math.min(other.bits.length, bits.length); - for (int i = 0; i < end; ++i) + for (int i = 0; i < end; ++i) { bits[i] |= other.bits[i]; + } } public final void nand(final FastBitSet other) { final int end = Math.min(other.bits.length, bits.length); - for (int i = 0; i < end; ++i) + for (int i = 0; i < end; ++i) { bits[i] = ~(bits[i] & other.bits[i]); + } } public final void nor(final FastBitSet other) { final int end = Math.min(other.bits.length, bits.length); - for (int i = 0; i < end; ++i) + for (int i = 0; i < end; ++i) { bits[i] = ~(bits[i] | other.bits[i]); + } } public final void xor(final FastBitSet other) { final int end = Math.min(other.bits.length, bits.length); - for (int i = 0; i < end; ++i) + for (int i = 0; i < end; ++i) { bits[i] ^= other.bits[i]; + } } public final int cardinality() { - if (size == 0) return 0; + if (size == 0) { + return 0; + } int count = 0; - for (int i = 0; i < bits.length - 1; ++i) + for (int i = 0; i < bits.length - 1; ++i) { count += Long.bitCount(bits[i]); + } return count + Long.bitCount(bits[bits.length - 1] & ~(-1L << (size & 0x3F))); } @@ -212,16 +240,6 @@ public final class FastBitSet { return 8L * bits.length; } - private static void fill(final long[] a, final int b, final int e, final long l) { - for (int i = b; i < e; ++i) - a[i] = l; - } - - public static long calculateMemoryUsage(int entries) { - final int numLongs = (entries + 64) >> 6; - return 8L * numLongs; - } - public IntIterator iterator() { return new IntIterator(); } @@ -240,8 +258,8 @@ public final class FastBitSet { index++; } final long lowBit = Long.lowestOneBit(bitBuffer); - final int bitIndex = Long.bitCount(lowBit-1); - value = ((index-1)<<6)+bitIndex; + final int bitIndex = Long.bitCount(lowBit - 1); + value = ((index - 1) << 6) + bitIndex; bitBuffer = bitBuffer ^ lowBit; return true; } @@ -250,4 +268,4 @@ public final class FastBitSet { return value; } } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/FastRandomCollection.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/FastRandomCollection.java index d283cfb57..e59a37f95 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/FastRandomCollection.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/FastRandomCollection.java @@ -16,15 +16,15 @@ public class FastRandomCollection extends RandomCollection { } /** - * Create a new FastRandomCollection if the given values and weights match the criteria. - * The criteria may change at any point, so this method isn't guaranteed to return a - * non-empty Optional in any case. + * Create a new FastRandomCollection if the given values and weights match the criteria. The + * criteria may change at any point, so this method isn't guaranteed to return a non-empty + * {@code Optional} in any case. * * @param weights the weight of the values. * @param random the random generator to use for this collection. * @param the value type. - * @return an {@link Optional} containing the new collection if it could - * be created, {@link Optional#empty()} otherwise. + * @return an {@link Optional} containing the new collection if it could be created, {@link + * Optional#empty()} otherwise. * @see RandomCollection for API usage. */ public static Optional> create(Map weights, SimpleRandom random) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/IAdaptedMap.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/IAdaptedMap.java index 18aa4d1c9..0cf6559d3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/IAdaptedMap.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/IAdaptedMap.java @@ -71,21 +71,27 @@ public interface IAdaptedMap extends Map { @NotNull @Override default Set keySet() { - if (isEmpty()) return Collections.emptySet(); + if (isEmpty()) { + return Collections.emptySet(); + } return new AdaptedSetCollection<>(getParent().keySet(), this::adaptKey2); } @NotNull @Override default Collection values() { - if (isEmpty()) return Collections.emptySet(); + if (isEmpty()) { + return Collections.emptySet(); + } return new AdaptedSetCollection<>(getParent().values(), this::adaptValue2); } @NotNull @Override default Set> entrySet() { - if (isEmpty()) return Collections.emptySet(); + if (isEmpty()) { + return Collections.emptySet(); + } return new AdaptedSetCollection<>(getParent().entrySet(), new Function, Entry>() { private MutablePair entry = new MutablePair<>(); @Override diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LocalBlockVector2DSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LocalBlockVector2DSet.java index 899b4cfa9..52ab3a577 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LocalBlockVector2DSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LocalBlockVector2DSet.java @@ -51,7 +51,9 @@ public class LocalBlockVector2DSet implements Set { public boolean containsRadius(int x, int y, int radius) { int size = size(); - if (size == 0) return false; + if (size == 0) { + return false; + } if (radius <= 0 || size == 1) { return contains(x, y); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LocalBlockVectorSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LocalBlockVectorSet.java index bcd4f23d0..da172cb7a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LocalBlockVectorSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LocalBlockVectorSet.java @@ -15,7 +15,8 @@ import java.util.Set; * - This will use 8 bytes for every 64 BlockVectors (about 800x less than a HashSet) */ public class LocalBlockVectorSet implements Set { - private int offsetX, offsetZ; + private int offsetX; + private int offsetZ; private final SparseBitSet set; public LocalBlockVectorSet() { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LongHashSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LongHashSet.java index 2d9e37a1e..712b2ed40 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LongHashSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/LongHashSet.java @@ -61,7 +61,9 @@ public class LongHashSet { public void add(long key) { int mainIdx = (int) (key & 255); long outer[][] = this.values[mainIdx]; - if (outer == null) this.values[mainIdx] = outer = new long[256][]; + if (outer == null) { + this.values[mainIdx] = outer = new long[256][]; + } int outerIdx = (int) ((key >> 32) & 255); long inner[] = outer[outerIdx]; @@ -88,23 +90,33 @@ public class LongHashSet { public boolean containsKey(long key) { long[][] outer = this.values[(int) (key & 255)]; - if (outer == null) return false; + if (outer == null) { + return false; + } long[] inner = outer[(int) ((key >> 32) & 255)]; - if (inner == null) return false; + if (inner == null) { + return false; + } for (long entry : inner) { - if (entry == key) return true; + if (entry == key) { + return true; + } } return false; } public void remove(long key) { long[][] outer = this.values[(int) (key & 255)]; - if (outer == null) return; + if (outer == null) { + return; + } long[] inner = outer[(int) ((key >> 32) & 255)]; - if (inner == null) return; + if (inner == null) { + return; + } int max = inner.length - 1; for (int i = 0; i <= max; i++) { @@ -122,11 +134,15 @@ public class LongHashSet { public long popFirst() { for (long[][] outer: this.values) { - if (outer == null) continue; + if (outer == null) { + continue; + } for (int i = 0; i < outer.length; i++) { long[] inner = outer[i]; - if (inner == null || inner.length == 0) continue; + if (inner == null || inner.length == 0) { + continue; + } this.count--; long ret = inner[inner.length - 1]; @@ -142,11 +158,15 @@ public class LongHashSet { int index = 0; long[] ret = new long[this.count]; for (long[][] outer : this.values) { - if (outer == null) continue; + if (outer == null) { + continue; + } for (int oIdx = outer.length - 1; oIdx >= 0; oIdx--) { long[] inner = outer[oIdx]; - if (inner == null) continue; + if (inner == null) { + continue; + } for (long entry: inner) { ret[index++] = entry; @@ -162,10 +182,14 @@ public class LongHashSet { int index = 0; long[] ret = new long[this.count]; for (long[][] outer : this.values) { - if (outer == null) continue; + if (outer == null) { + continue; + } for (long[] inner : outer) { - if (inner == null) continue; + if (inner == null) { + continue; + } for (long entry : inner) { ret[index++] = entry; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/MemBlockSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/MemBlockSet.java index 3d7994ef9..ddfbff231 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/MemBlockSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/MemBlockSet.java @@ -20,11 +20,11 @@ import java.util.Set; * - Grouping / iteration is by chunk section, and the y>z>x order */ public final class MemBlockSet extends BlockSet { - public final static int BITS_PER_WORD = 6; - public final static int WORDS = FaweCache.IMP.BLOCKS_PER_LAYER >> BITS_PER_WORD; - public final static IRow NULL_ROW_X = new NullRowX(); - public final static IRow NULL_ROW_Z = new NullRowZ(); - public final static IRow NULL_ROW_Y = new NullRowY(); + public static final int BITS_PER_WORD = 6; + public static final int WORDS = FaweCache.IMP.BLOCKS_PER_LAYER >> BITS_PER_WORD; + public static final IRow NULL_ROW_X = new NullRowX(); + public static final IRow NULL_ROW_Z = new NullRowZ(); + public static final IRow NULL_ROW_Y = new NullRowY(); public final IRow[] rows; public final MutableBlockVector3 mutable; @@ -35,7 +35,9 @@ public final class MemBlockSet extends BlockSet { public MemBlockSet(int size, int offsetX, int offsetZ) { super(offsetX, offsetZ); this.rows = new IRow[size]; - for (int i = 0; i < size; i++) rows[i] = NULL_ROW_X; + for (int i = 0; i < size; i++) { + rows[i] = NULL_ROW_X; + } this.mutable = new MutableBlockVector3(); } @@ -92,19 +94,21 @@ public final class MemBlockSet extends BlockSet { return new Iterator() { private MutableBlockVector2 mutable = new MutableBlockVector2(); private boolean hasNext; - private int X,Z; - private int setX, setZ; + private int X; + private int Z; + private int setX; + private int setZ; { init(); } private void init() { - for (;X < rows.length; X++) { + for (; X < rows.length; X++) { IRow nullRowX = rows[X]; if (nullRowX instanceof RowX) { RowX rowx = (RowX) nullRowX; - for (;Z < rowx.rows.length; Z++) { + for (; Z < rowx.rows.length; Z++) { IRow nullRowZ = rowx.rows[Z]; if (nullRowZ instanceof RowZ) { setX = X; @@ -182,23 +186,27 @@ public final class MemBlockSet extends BlockSet { return new Iterator() { private MutableBlockVector3 mutable = new MutableBlockVector3(); private boolean hasNext; - private int X, Z, Y; - private int setX, setY, setZ; + private int X; + private int Z; + private int Y; + private int setX; + private int setY; + private int setZ; { init(); } private void init() { - for (;X < rows.length; X++) { + for (; X < rows.length; X++) { IRow nullRowX = rows[X]; if (nullRowX instanceof RowX) { RowX rowx = (RowX) nullRowX; - for (;Z < rowx.rows.length; Z++) { + for (; Z < rowx.rows.length; Z++) { IRow nullRowZ = rowx.rows[Z]; if (nullRowZ instanceof RowZ) { RowZ rowz = (RowZ) nullRowZ; - for (;Y < rowz.rows.length;Y++) { + for (; Y < rowz.rows.length; Y++) { IRow nullRowY = rowz.rows[Y]; if (nullRowY instanceof RowY) { setX = X; @@ -224,7 +232,8 @@ public final class MemBlockSet extends BlockSet { @Override public BlockVector3 next() { - mutable.setComponents(setX + getBlockOffsetX(), setY, setZ + getBlockOffsetX()); + mutable.setComponents( + setX + getBlockOffsetX(), setY, setZ + getBlockOffsetX()); init(); return mutable; } @@ -287,19 +296,22 @@ public final class MemBlockSet extends BlockSet { int maxy = 16; int by = Integer.MAX_VALUE; for (IRow nullRowX : rows) { - if (!(nullRowX instanceof RowX)) + if (!(nullRowX instanceof RowX)) { continue; + } RowX rowx = (RowX) nullRowX; for (int Z = 0; Z < rowx.rows.length; Z++) { IRow nullRowZ = rowx.rows[Z]; - if (!(nullRowZ instanceof RowZ)) + if (!(nullRowZ instanceof RowZ)) { continue; + } RowZ rowz = (RowZ) nullRowZ; outer: for (int Y = 0; Y <= maxY; Y++) { IRow nullRowY = rowz.rows[Y]; - if (!(nullRowY instanceof RowY)) + if (!(nullRowY instanceof RowY)) { continue; + } RowY rowY = (RowY) nullRowY; int localMaxy = Y == maxY ? maxy : 15; for (int y = 0, i = 0; y < localMaxy; y++) { @@ -314,8 +326,9 @@ public final class MemBlockSet extends BlockSet { maxy = y; } by = (Y << 4) + y; - if (by == 0) + if (by == 0) { return 0; + } break outer; } } @@ -332,19 +345,22 @@ public final class MemBlockSet extends BlockSet { int maxy = 0; int by = Integer.MIN_VALUE; for (IRow nullRowX : rows) { - if (!(nullRowX instanceof RowX)) + if (!(nullRowX instanceof RowX)) { continue; + } RowX rowx = (RowX) nullRowX; for (int Z = 0; Z < rowx.rows.length; Z++) { IRow nullRowZ = rowx.rows[Z]; - if (!(nullRowZ instanceof RowZ)) + if (!(nullRowZ instanceof RowZ)) { continue; + } RowZ rowz = (RowZ) nullRowZ; outer: for (int Y = 15; Y >= maxY; Y--) { IRow nullRowY = rowz.rows[Y]; - if (!(nullRowY instanceof RowY)) + if (!(nullRowY instanceof RowY)) { continue; + } RowY rowY = (RowY) nullRowY; int localMaxy = Y == maxY ? maxy : 0; for (int y = 15, i = 63; y >= localMaxy; y--) { @@ -359,8 +375,9 @@ public final class MemBlockSet extends BlockSet { maxy = y + 1; } by = (Y << 4) + y; - if (by == FaweCache.IMP.WORLD_MAX_Y) + if (by == FaweCache.IMP.WORLD_MAX_Y) { return FaweCache.IMP.WORLD_MAX_Y; + } break outer; } } @@ -377,12 +394,16 @@ public final class MemBlockSet extends BlockSet { int tz = Integer.MIN_VALUE; for (int X = rows.length - 1; X >= 0; X--) { IRow nullRowX = rows[X]; - if (!(nullRowX instanceof RowX)) continue; + if (!(nullRowX instanceof RowX)) { + continue; + } RowX rowx = (RowX) nullRowX; outer: - for (int Z = rowx.rows.length - 1; Z >= maxChunkZ ; Z--) { + for (int Z = rowx.rows.length - 1; Z >= maxChunkZ; Z--) { IRow nullRowZ = rowx.rows[Z]; - if (!(nullRowZ instanceof RowZ)) continue; + if (!(nullRowZ instanceof RowZ)) { + continue; + } RowZ rowz = (RowZ) nullRowZ; if (Z != maxChunkZ) { maxChunkZ = Z; @@ -390,7 +411,9 @@ public final class MemBlockSet extends BlockSet { } for (int Y = rowz.rows.length - 1; Y >= 0; Y--) { IRow nullRowY = rowz.rows[Y]; - if (!(nullRowY instanceof RowY)) continue; + if (!(nullRowY instanceof RowY)) { + continue; + } RowY rowY = (RowY) nullRowY; for (int y = 15, i1 = 63; y >= 0; y--, i1 -= 4) { for (int z = 12, i = i1; z > maxz - 3; z -= 4, i--) { @@ -419,21 +442,29 @@ public final class MemBlockSet extends BlockSet { public int getMaxX() { for (int X = rows.length - 1; X >= 0; X--) { IRow nullRowX = rows[X]; - if (!(nullRowX instanceof RowX)) continue; + if (!(nullRowX instanceof RowX)) { + continue; + } int tx = (X << 4); RowX rowx = (RowX) nullRowX; long or = 0; - for (int Z = rowx.rows.length - 1; Z >= 0 ; Z--) { + for (int Z = rowx.rows.length - 1; Z >= 0; Z--) { IRow nullRowZ = rowx.rows[Z]; - if (!(nullRowZ instanceof RowZ)) continue; + if (!(nullRowZ instanceof RowZ)) { + continue; + } RowZ rowz = (RowZ) nullRowZ; for (int Y = rowz.rows.length - 1; Y >= 0; Y--) { IRow nullRowY = rowz.rows[Y]; - if (!(nullRowY instanceof RowY)) continue; + if (!(nullRowY instanceof RowY)) { + continue; + } RowY rowY = (RowY) nullRowY; or |= Arrays.stream(rowY.bits).reduce(0, (a, b) -> a | b); or = (or & 0xFFFF) | ((or >> 16) & 0xFFFF) | ((or >> 32) & 0xFFFF) | ((or >> 48) & 0xFFFF); - if (highestBit(or) == 15) return tx + 15; + if (highestBit(or) == 15) { + return tx + 15; + } } } int highest = highestBit(or); @@ -449,14 +480,16 @@ public final class MemBlockSet extends BlockSet { int maxz = 16; int bz = Integer.MAX_VALUE; for (IRow nullRowX : rows) { - if (!(nullRowX instanceof RowX)) + if (!(nullRowX instanceof RowX)) { continue; + } RowX rowx = (RowX) nullRowX; outer: for (int Z = 0; Z <= maxChunkZ; Z++) { IRow nullRowZ = rowx.rows[Z]; - if (!(nullRowZ instanceof RowZ)) + if (!(nullRowZ instanceof RowZ)) { continue; + } RowZ rowz = (RowZ) nullRowZ; if (Z != maxChunkZ) { maxChunkZ = Z; @@ -464,8 +497,9 @@ public final class MemBlockSet extends BlockSet { } for (int Y = 0; Y < rowz.rows.length; Y++) { IRow nullRowY = rowz.rows[Y]; - if (!(nullRowY instanceof RowY)) + if (!(nullRowY instanceof RowY)) { continue; + } RowY rowY = (RowY) nullRowY; for (int y = 0, i1 = 0; y < 16; y++, i1 += 4) { for (int z = 0, i = i1; z < maxz; z += 4, i++) { @@ -494,21 +528,29 @@ public final class MemBlockSet extends BlockSet { public int getMinX() { for (int X = 0; X < rows.length; X++) { IRow nullRowX = rows[X]; - if (!(nullRowX instanceof RowX)) continue; + if (!(nullRowX instanceof RowX)) { + continue; + } int bx = X << 4; RowX rowx = (RowX) nullRowX; long or = 0; for (int Z = 0; Z < rowx.rows.length; Z++) { IRow nullRowZ = rowx.rows[Z]; - if (!(nullRowZ instanceof RowZ)) continue; + if (!(nullRowZ instanceof RowZ)) { + continue; + } RowZ rowz = (RowZ) nullRowZ; for (int Y = 0; Y < rowz.rows.length; Y++) { IRow nullRowY = rowz.rows[Y]; - if (!(nullRowY instanceof RowY)) continue; + if (!(nullRowY instanceof RowY)) { + continue; + } RowY rowY = (RowY) nullRowY; or |= Arrays.stream(rowY.bits).reduce(0, (a, b) -> a | b); or = (or & 0xFFFF) | ((or >> 16) & 0xFFFF) | ((or >> 32) & 0xFFFF) | ((or >> 48) & 0xFFFF); - if (lowestBit(or) == 0) return bx; + if (lowestBit(or) == 0) { + return bx; + } } } int lowest = lowestBit(or); @@ -522,17 +564,23 @@ public final class MemBlockSet extends BlockSet { public void iterate(BlockIterator iterator) { for (int X = 0; X < rows.length; X++) { IRow nullRowX = rows[X]; - if (!(nullRowX instanceof RowX)) continue; + if (!(nullRowX instanceof RowX)) { + continue; + } int bx = getBlockOffsetX() + (X << 4); RowX rowx = (RowX) nullRowX; for (int Z = 0; Z < rowx.rows.length; Z++) { IRow nullRowZ = rowx.rows[Z]; - if (!(nullRowZ instanceof RowZ)) continue; + if (!(nullRowZ instanceof RowZ)) { + continue; + } int bz = getBlockOffsetZ() + (Z << 4); RowZ rowz = (RowZ) nullRowZ; for (int Y = 0; Y < rowz.rows.length; Y++) { IRow nullRowY = rowz.rows[Y]; - if (!(nullRowY instanceof RowY)) continue; + if (!(nullRowY instanceof RowY)) { + continue; + } int by = Y << 4; RowY rowY = (RowY) nullRowY; for (int y = 0, i = 0; y < 16; y++) { @@ -567,7 +615,11 @@ public final class MemBlockSet extends BlockSet { @Override public Iterator iterator() { return new Iterator() { - private int bx, by, bz, zz, yy; + private int bx; + private int by; + private int bz; + private int zz; + private int yy; private RowX rowX; private RowZ rowZ; private long[] bits; @@ -658,7 +710,7 @@ public final class MemBlockSet extends BlockSet { @Override public BlockVector3 next() { final long lowBit = Long.lowestOneBit(bitBuffer); - final int bitIndex = Long.bitCount(lowBit-1); + final int bitIndex = Long.bitCount(lowBit - 1); mutable.setComponents((bx) + (bitIndex & 15), yy, (zz) + (bitIndex)); bitBuffer = bitBuffer ^ lowBit; nextLong(); @@ -676,22 +728,26 @@ public final class MemBlockSet extends BlockSet { @Override public boolean isEmpty() { for (IRow nullRowX : rows) { - if (!(nullRowX instanceof RowX)) + if (!(nullRowX instanceof RowX)) { continue; + } RowX rowx = (RowX) nullRowX; for (int Z = 0; Z < rowx.rows.length; Z++) { IRow nullRowZ = rowx.rows[Z]; - if (!(nullRowZ instanceof RowZ)) + if (!(nullRowZ instanceof RowZ)) { continue; + } RowZ rowz = (RowZ) nullRowZ; for (int Y = 0; Y < 16; Y++) { IRow nullRowY = rowz.rows[Y]; - if (!(nullRowY instanceof RowY)) + if (!(nullRowY instanceof RowY)) { continue; + } RowY rowY = (RowY) nullRowY; for (long bit : rowY.bits) { - if (bit != 0) + if (bit != 0) { return true; + } } } } @@ -709,13 +765,15 @@ public final class MemBlockSet extends BlockSet { long lastBit = 0; int lastCount = 0; for (IRow nullRowX : rows) { - if (!(nullRowX instanceof RowX)) + if (!(nullRowX instanceof RowX)) { continue; + } RowX rowx = (RowX) nullRowX; for (int z = 0; z < rowx.rows.length; z++) { IRow nullRowZ = rowx.rows[z]; - if (!(nullRowZ instanceof RowZ)) + if (!(nullRowZ instanceof RowZ)) { continue; + } RowZ rowz = (RowZ) nullRowZ; for (int y = 0; y < 16; y++) { IRow nullRowY = rowz.rows[y]; @@ -749,17 +807,24 @@ public final class MemBlockSet extends BlockSet { void apply(int x, int y, int z); } + public interface IRow { - default boolean get(IRow[] rows, int x, int y, int z) { return false; } + default boolean get(IRow[] rows, int x, int y, int z) { + return false; + } + void set(IRow[] rows, int x, int y, int z); + default boolean add(IRow[] rows, int x, int y, int z) { set(rows, x, y, z); return true; } + default boolean remove(IRow[] rows, int x, int y, int z) { remove(rows, x, y, z); return false; } + default void clear(IRow[] rows, int x, int y, int z) { } } @@ -796,7 +861,9 @@ public final class MemBlockSet extends BlockSet { public RowX(int size) { this.rows = new IRow[size]; - for (int i = 0; i < size; i++) rows[i] = NULL_ROW_Z; + for (int i = 0; i < size; i++) { + rows[i] = NULL_ROW_Z; + } } @Override @@ -876,7 +943,9 @@ public final class MemBlockSet extends BlockSet { } public void reset() { - for (int i = 0; i < FaweCache.IMP.CHUNK_LAYERS; i++) rows[i] = NULL_ROW_Y; + for (int i = 0; i < FaweCache.IMP.CHUNK_LAYERS; i++) { + rows[i] = NULL_ROW_Y; + } } } @@ -940,7 +1009,9 @@ public final class MemBlockSet extends BlockSet { int len = arr.length; int newLen = len == 1 ? 1 : Integer.highestOneBit(len - 1) * 2; IRow[] copy = Arrays.copyOf(arr, newLen, IRow[].class); - for (int i = len; i < newLen; i++) copy[i] = def; + for (int i = len; i < newLen; i++) { + copy[i] = def; + } return copy; } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/MutablePair.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/MutablePair.java index e0196a6e6..923a5b8a3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/MutablePair.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/MutablePair.java @@ -5,6 +5,7 @@ import java.util.Map; public class MutablePair implements Map.Entry { private K key; private V value; + @Override public K getKey() { return key; @@ -17,9 +18,8 @@ public class MutablePair implements Map.Entry { @Override public V setValue(V value) { - V old = value; this.value = value; - return old; + return value; } public void setKey(K key) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SimpleRandomCollection.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SimpleRandomCollection.java index b3f7cdd76..8e90d0ea3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SimpleRandomCollection.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SimpleRandomCollection.java @@ -27,7 +27,9 @@ public class SimpleRandomCollection extends RandomCollection { } public void add(double weight, E result) { - if (weight <= 0) return; + if (weight <= 0) { + return; + } total += weight; map.put(total, result); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SparseBitSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SparseBitSet.java index 0aa67d72d..8be9d0940 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SparseBitSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SparseBitSet.java @@ -1,4 +1,3 @@ -// CHECKSTYLE:OFF package com.boydti.fawe.object.collection; /*- This software is the work of Paladin Software International, Incorporated, @@ -805,7 +804,7 @@ public class SparseBitSet implements Cloneable, Serializable * public int hashCode() * { * long hash = 1234L; - * for( int i = bits.length; --i >= 0; ) + * for ( int i = bits.length; --i >= 0; ) * hash ^= bits[i] * (i + 1); * return (int)((h >> 32) ^ h); * } @@ -965,7 +964,7 @@ public class SparseBitSet implements Cloneable, Serializable * sbs, use the following loop: * *
-     *  for( int i = sbbits.nextSetBit(0); i >= 0; i = sbbits.nextSetBit(i+1) )
+     *  for ( int i = sbbits.nextSetBit(0); i >= 0; i = sbbits.nextSetBit(i+1) )
      *  {
      *      // operate on index i here
      *  }
diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SummedColorTable.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SummedColorTable.java index 95b51dd4e..11ae981de 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SummedColorTable.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SummedColorTable.java @@ -6,10 +6,13 @@ import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; /** - * Efficient blur / average color over an image + * Efficient blur / average color over an image. */ public class SummedColorTable { - private final long[] reds, greens, blues, alpha; + private final long[] reds; + private final long[] greens; + private final long[] blues; + private final long[] alpha; private final int[] hasAlpha; private final int length; private final int width; @@ -38,7 +41,9 @@ public class SummedColorTable { for (int j = 0; j < width; j++, index++) { int color = raw[index]; int alpha = (color >> 24) & 0xFF; - int red, green, blue; + int red; + int green; + int blue; switch (alpha) { case 0: red = green = blue = 0; @@ -68,7 +73,10 @@ public class SummedColorTable { for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++, index++) { int color = raw[index]; - int red, green, blue, alpha; + int red; + int green; + int blue; + int alpha; if (((color >> 24) != 0)) { alpha = 1; red = (color >> 16) & 0xFF; @@ -122,7 +130,9 @@ public class SummedColorTable { area += hasAlpha[pos]; } - if (area == 0) return 0; + if (area == 0) { + return 0; + } float factor = this.areaInverses[area - 1]; return (255 << 24) + (((int) (totRed * factor)) << 16) + (((int) (totGreen * factor)) << 8) + (((int) (totBlue * factor)) << 0); } @@ -166,7 +176,9 @@ public class SummedColorTable { area += hasAlpha[pos]; } - if (totAlpha == 0) return 0; + if (totAlpha == 0) { + return 0; + } float factor = this.areaInverses[area - 1]; float alpha = (totAlpha * factor); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/exception/FaweException.java b/worldedit-core/src/main/java/com/boydti/fawe/object/exception/FaweException.java index 930862283..d9b749c27 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/exception/FaweException.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/exception/FaweException.java @@ -10,7 +10,7 @@ public class FaweException extends RuntimeException { // DEBUG public static final FaweException _enableQueue = new FaweException("enableQueue"); public static final FaweException _disableQueue = new FaweException("disableQueue"); - + private final Component message; public FaweException(String reason) { @@ -42,9 +42,9 @@ public class FaweException extends RuntimeException { } /** - * Faster exception throwing/handling if you don't fill the stacktrace + * Faster exception throwing/handling if you don't fill the stacktrace. * - * @return + * @return a reference to this {@code Throwable} instance. */ @Override public Throwable fillInStackTrace() { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/BlockTranslateExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/BlockTranslateExtent.java index 945910086..4b4c230fd 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/BlockTranslateExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/BlockTranslateExtent.java @@ -11,7 +11,9 @@ import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; public class BlockTranslateExtent extends AbstractDelegateExtent { - private final int dx, dy, dz; + private final int dx; + private final int dy; + private final int dz; private MutableBlockVector3 mutable = new MutableBlockVector3(); public BlockTranslateExtent(Extent extent, int dx, int dy, int dz) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ExtentHeightCacher.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ExtentHeightCacher.java index 560e9f841..71e6a7123 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ExtentHeightCacher.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ExtentHeightCacher.java @@ -11,6 +11,7 @@ public class ExtentHeightCacher extends PassthroughExtent { private transient int cacheBotZ = Integer.MIN_VALUE; private transient byte[] cacheHeights; private transient int lastY; + public ExtentHeightCacher(Extent extent) { super(extent); } 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 86aac2e94..51c315f6a 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 @@ -15,7 +15,8 @@ import java.util.concurrent.Future; public class HeightBoundExtent extends FaweRegionExtent { - private final int min, max; + private final int min; + private final int max; private int lastY = -1; private boolean lastResult; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/NullExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/NullExtent.java index 433ba7ff3..24e5ed955 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/NullExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/NullExtent.java @@ -182,18 +182,18 @@ public class NullExtent extends FaweRegionExtent implements IBatchProcessor { @Override public int getHighestTerrainBlock(int x, int z, int minY, int maxY, Mask filter) { - throw reason; - } + throw reason; + } @Override public boolean contains(int x, int z) { - throw reason; - } + throw reason; + } @Override public boolean contains(int x, int y, int z) { - throw reason; - } + throw reason; + } @Override public Collection getRegions() { @@ -273,13 +273,13 @@ public class NullExtent extends FaweRegionExtent implements IBatchProcessor { @Override public int getNearestSurfaceTerrainBlock(int x, int z, int y, int minY, int maxY, boolean ignoreAir) { - throw reason; - } + throw reason; + } @Override public int getNearestSurfaceTerrainBlock(int x, int z, int y, int minY, int maxY) { - throw reason; - } + throw reason; + } @Override public int getNearestSurfaceTerrainBlock(int x, int z, int y, int minY, int maxY, int failedMin, int failedMax) { @@ -303,8 +303,8 @@ public class NullExtent extends FaweRegionExtent implements IBatchProcessor { @Override public void generate(Region region, GenBase gen) throws WorldEditException { - throw reason; - } + throw reason; + } @Override public void addSchems(Region region, Mask mask, List clipboards, int rarity, boolean rotate) throws WorldEditException { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/OffsetExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/OffsetExtent.java index 7eff78973..32117eba1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/OffsetExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/OffsetExtent.java @@ -10,7 +10,9 @@ import com.sk89q.worldedit.world.block.BlockStateHolder; public class OffsetExtent extends ResettableExtent { - private final int dx, dy, dz; + private final int dx; + private final int dy; + private final int dz; private transient MutableBlockVector2 mutable = new MutableBlockVector2(); public OffsetExtent(Extent parent, int dx, int dy, int dz) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/RandomOffsetTransform.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/RandomOffsetTransform.java index ce11bb8da..f275d4d45 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/RandomOffsetTransform.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/RandomOffsetTransform.java @@ -12,7 +12,9 @@ import java.util.SplittableRandom; public class RandomOffsetTransform extends ResettableExtent { - private final int dx, dy, dz; + private final int dx; + private final int dy; + private final int dz; private transient SplittableRandom random; private transient MutableBlockVector2 mutable = new MutableBlockVector2(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ScaleTransform.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ScaleTransform.java index 2512f3b55..2e3364543 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ScaleTransform.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ScaleTransform.java @@ -15,7 +15,9 @@ import javax.annotation.Nullable; public class ScaleTransform extends ResettableExtent { - private final double dx, dy, dz; + private final double dx; + private final double dy; + private final double dz; private transient MutableBlockVector3 mutable = new MutableBlockVector3(); private transient int maxy; private transient BlockVector3 min; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/StripNBTExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/StripNBTExtent.java index c46e663e0..19b3df573 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/StripNBTExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/StripNBTExtent.java @@ -47,9 +47,13 @@ public class StripNBTExtent extends AbstractDelegateExtent { } public > B stripBlockNBT(B block) { - if(!(block instanceof BaseBlock)) return block; - BaseBlock localBlock = (BaseBlock)block; - if (!localBlock.hasNbtData()) return block; + if (!(block instanceof BaseBlock)) { + return block; + } + BaseBlock localBlock = (BaseBlock) block; + if (!localBlock.hasNbtData()) { + return block; + } CompoundTag nbt = localBlock.getNbtData(); Map value = nbt.getValue(); for (String key : strip) { @@ -59,7 +63,9 @@ public class StripNBTExtent extends AbstractDelegateExtent { } public T stripEntityNBT(T entity) { - if (!entity.hasNbtData()) return entity; + if (!entity.hasNbtData()) { + return entity; + } CompoundTag nbt = entity.getNbtData(); Map value = nbt.getValue(); for (String key : strip) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/TemporalExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/TemporalExtent.java index 2d17e477d..71f21c554 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/TemporalExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/TemporalExtent.java @@ -10,10 +10,13 @@ import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; public class TemporalExtent extends PassthroughExtent { - private int x, y, z = Integer.MAX_VALUE; + private int x; + private int y; + private int z = Integer.MAX_VALUE; private BlockStateHolder block = BlockTypes.AIR.getDefaultState(); - private int bx, bz = Integer.MAX_VALUE; + private int bx; + private int bz = Integer.MAX_VALUE; private BiomeType biome = null; /** @@ -58,8 +61,8 @@ public class TemporalExtent extends PassthroughExtent { @Override public BaseBlock getFullBlock(BlockVector3 position) { if (position.getX() == x && position.getY() == y && position.getZ() == z) { - if(block instanceof BaseBlock) { - return (BaseBlock)block; + if (block instanceof BaseBlock) { + return (BaseBlock) block; } else { return block.toBaseBlock(); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/function/block/BiomeCopy.java b/worldedit-core/src/main/java/com/boydti/fawe/object/function/block/BiomeCopy.java index ebed874f9..0ac08f970 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/function/block/BiomeCopy.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/function/block/BiomeCopy.java @@ -24,7 +24,7 @@ public class BiomeCopy implements RegionFunction { int x = position.getBlockX(); int y = position.getBlockY(); int z = position.getBlockZ(); - if (x != mutableVector.getBlockX() || z != mutableVector.getBlockZ()|| y != mutableVector + if (x != mutableVector.getBlockX() || z != mutableVector.getBlockZ() || y != mutableVector .getBlockY()) { mutableVector.setComponents(x, y, z); return destination.setBiome(mutableVector, source.getBiome(mutableVector)); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/function/block/CombinedBlockCopy.java b/worldedit-core/src/main/java/com/boydti/fawe/object/function/block/CombinedBlockCopy.java index c42f69fb8..19092ec75 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/function/block/CombinedBlockCopy.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/function/block/CombinedBlockCopy.java @@ -20,7 +20,7 @@ public class CombinedBlockCopy implements RegionFunction { @Override public boolean apply(BlockVector3 position) throws WorldEditException { -// BlockStateHolder block = source.getBlock(position); + // BlockStateHolder block = source.getBlock(position); BaseBlock block = source.getFullBlock(position); function.apply(position); return destination.setBlock(position, block); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/io/AsyncBufferedOutputStream.java b/worldedit-core/src/main/java/com/boydti/fawe/object/io/AsyncBufferedOutputStream.java index 10d150982..10a7cdbf3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/io/AsyncBufferedOutputStream.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/io/AsyncBufferedOutputStream.java @@ -9,13 +9,14 @@ import java.util.concurrent.ConcurrentLinkedDeque; * BufferedOutputStream that asynchronously flushes to disk, so callers don't * have to wait until the flush happens. Buffers are put into a queue that is * written asynchronously to disk once it is really available. - *

- * This class is thread-safe. + * *

* The error handling (as all stream ops are done asynchronously) is done during * write and close. Exceptions on the asynchronous thread will be thrown to the * caller either while writing or closing this stream. + *

* + * @apiNote This class is thread-safe. * @author thomas.jungblut */ public final class AsyncBufferedOutputStream extends FilterOutputStream { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/io/BufferedRandomAccessFile.java b/worldedit-core/src/main/java/com/boydti/fawe/object/io/BufferedRandomAccessFile.java index 1c81ede2e..d96b7d43f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/io/BufferedRandomAccessFile.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/io/BufferedRandomAccessFile.java @@ -1,21 +1,3 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - *

- * http://www.apache.org/licenses/LICENSE-2.0 - *

- * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package com.boydti.fawe.object.io; import java.io.File; @@ -26,16 +8,14 @@ import java.util.Arrays; /** - * A BufferedRandomAccessFile is like a - * RandomAccessFile, but it uses a private buffer so that most + * A {@code BufferedRandomAccessFile} is like a + * {@code RandomAccessFile}, but it uses a private buffer so that most * operations do not require a disk access. - *

* - * Note: The operations on this class are unmonitored. Also, the correct - * functioning of the RandomAccessFile methods that are not - * overridden here relies on the implementation of those methods in the - * superclass. - * Author : Avinash Lakshman ( alakshman@facebook.com) & Prashant Malik ( pmalik@facebook.com ) + * @author Avinash Lakshman ( alakshman@facebook.com) & Prashant Malik ( pmalik@facebook.com ) + * @apiNote The operations on this class are unmonitored. Also, the correct + * functioning of the {@code RandomAccessFile} methods that are not + * overridden here relies on the implementation of those methods in the superclass. */ public class BufferedRandomAccessFile extends RandomAccessFile { @@ -50,7 +30,8 @@ public class BufferedRandomAccessFile extends RandomAccessFile { private boolean dirty_; // true iff unflushed bytes exist private boolean closed_; // true iff the file is closed private long curr_; // current position in file - private long lo_, hi_; // bounds on characters in "buff" + private long lo_; // bounds on characters in "buff" + private long hi_; // bounds on characters in "buff" private byte[] buff_; // local buffer private long maxHi_; // this.lo + this.buff.length private boolean hitEOF_; // buffer contains last file block? @@ -110,8 +91,8 @@ public class BufferedRandomAccessFile extends RandomAccessFile { */ /** - * Open a new BufferedRandomAccessFile on file - * in mode mode, which should be "r" for reading only, or + * Open a new {@code BufferedRandomAccessFile} on {@code file} + * in mode {@code mode}, which should be "r" for reading only, or * "rw" for reading and writing. */ public BufferedRandomAccessFile(File file, String mode) throws IOException { @@ -125,8 +106,8 @@ public class BufferedRandomAccessFile extends RandomAccessFile { } /** - * Open a new BufferedRandomAccessFile on the file named - * name in mode mode, which should be "r" for + * Open a new {@code BufferedRandomAccessFile} on the file named + * {@code name} in mode {@code mode}, which should be "r" for * reading only, or "rw" for reading and writing. */ public BufferedRandomAccessFile(String name, String mode) throws IOException { @@ -176,8 +157,9 @@ public class BufferedRandomAccessFile extends RandomAccessFile { /* Flush any dirty bytes in the buffer to disk. */ private void flushBuffer() throws IOException { if (this.dirty_) { - if (this.diskPos_ != this.lo_) + if (this.diskPos_ != this.lo_) { super.seek(this.lo_); + } int len = (int) (this.curr_ - this.lo_); super.write(this.buff_, 0, len); this.diskPos_ = this.curr_; @@ -195,8 +177,9 @@ public class BufferedRandomAccessFile extends RandomAccessFile { int rem = this.buff_.length; while (rem > 0) { int n = super.read(this.buff_, cnt, rem); - if (n < 0) + if (n < 0) { break; + } cnt += n; rem -= n; } @@ -277,13 +260,15 @@ public class BufferedRandomAccessFile extends RandomAccessFile { if (this.curr_ >= this.hi_) { // test for EOF // if (this.hi < this.maxHi) return -1; - if (this.hitEOF_) + if (this.hitEOF_) { return -1; + } // slow path -- read another buffer this.seek(this.curr_); - if (this.curr_ == this.hi_) + if (this.curr_ == this.hi_) { return -1; + } } byte res = this.buff_[(int) (this.curr_ - this.lo_)]; this.curr_++; @@ -294,13 +279,15 @@ public class BufferedRandomAccessFile extends RandomAccessFile { if (this.curr_ >= this.hi_) { // test for EOF // if (this.hi < this.maxHi) return -1; - if (this.hitEOF_) + if (this.hitEOF_) { return -1; + } // slow path -- read another buffer this.seek(this.curr_); - if (this.curr_ == this.hi_) + if (this.curr_ == this.hi_) { return -1; + } } byte res = this.buff_[(int) (this.curr_ - this.lo_)]; this.curr_++; @@ -317,13 +304,15 @@ public class BufferedRandomAccessFile extends RandomAccessFile { if (this.curr_ >= this.hi_) { // test for EOF // if (this.hi < this.maxHi) return -1; - if (this.hitEOF_) + if (this.hitEOF_) { return -1; + } // slow path -- read another buffer this.seek(this.curr_); - if (this.curr_ == this.hi_) + if (this.curr_ == this.hi_) { return -1; + } } len = Math.min(len, (int) (this.hi_ - this.curr_)); int buffOff = (int) (this.curr_ - this.lo_); @@ -336,13 +325,15 @@ public class BufferedRandomAccessFile extends RandomAccessFile { if (this.curr_ >= this.hi_) { // test for EOF // if (this.hi < this.maxHi) return -1; - if (this.hitEOF_) + if (this.hitEOF_) { return -1; + } // slow path -- read another buffer this.seek(this.curr_); - if (this.curr_ == this.hi_) + if (this.curr_ == this.hi_) { return -1; + } } return this.buff_[(int) (this.curr_ - this.lo_)]; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/io/LittleEndianOutputStream.java b/worldedit-core/src/main/java/com/boydti/fawe/object/io/LittleEndianOutputStream.java index 4f2115e5e..32cc40ba5 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/io/LittleEndianOutputStream.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/io/LittleEndianOutputStream.java @@ -66,8 +66,11 @@ public class LittleEndianOutputStream extends FilterOutputStream implements Data @Override public void writeBoolean(boolean b) throws IOException { - if (b) this.write(1); - else this.write(0); + if (b) { + this.write(1); + } else { + this.write(0); + } } @@ -249,12 +252,18 @@ public class LittleEndianOutputStream extends FilterOutputStream implements Data for (int i = 0 ; i < numchars ; i++) { int c = s.charAt(i); - if ((c >= 0x0001) && (c <= 0x007F)) numbytes++; - else if (c > 0x07FF) numbytes += 3; - else numbytes += 2; + if ((c >= 0x0001) && (c <= 0x007F)) { + numbytes++; + } else if (c > 0x07FF) { + numbytes += 3; + } else { + numbytes += 2; + } } - if (numbytes > 65535) throw new UTFDataFormatException(); + if (numbytes > 65535) { + throw new UTFDataFormatException(); + } out.write((numbytes >>> 8) & 0xFF); out.write(numbytes & 0xFF); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/io/PGZIPOutputStream.java b/worldedit-core/src/main/java/com/boydti/fawe/object/io/PGZIPOutputStream.java index 89eaea7ea..a7a350e85 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/io/PGZIPOutputStream.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/io/PGZIPOutputStream.java @@ -35,7 +35,7 @@ public class PGZIPOutputStream extends FilterOutputStream { // private static final Logger LOG = LoggerFactory.getLogger(PGZIPOutputStream.class); - private final static int GZIP_MAGIC = 0x8b1f; + private static final int GZIP_MAGIC = 0x8b1f; // todo: remove after block guessing is implemented // array list that contains the block sizes @@ -175,10 +175,12 @@ public class PGZIPOutputStream extends FilterOutputStream { for (; ; ) { Future future = emitQueue.peek(); // LOG.info("Peeked future " + future); - if (future == null) + if (future == null) { return; - if (!future.isDone()) + } + if (!future.isDone()) { return; + } // It's an ordered queue. This MUST be the same element as above. emitQueue.remove(); byte[] toWrite = future.get(); @@ -215,8 +217,9 @@ public class PGZIPOutputStream extends FilterOutputStream { @Override public void flush() throws IOException { // LOG.info("Flush: " + block); - if (block.in_length > 0) + if (block.in_length > 0) { submit(); + } emitUntil(0); super.flush(); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/CachedMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/CachedMask.java index 1734fb53b..a7e0adcb9 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/CachedMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/CachedMask.java @@ -52,16 +52,22 @@ public class CachedMask extends AbstractDelegateMask implements ResettableMask { return cache_results.contains(x, y, z); } boolean result = getMask().test(mutable.setComponents(x, y, z)); - if (result) cache_results.add(x, y, z); + if (result) { + cache_results.add(x, y, z); + } return result; } catch (UnsupportedOperationException ignored) { boolean result = getMask().test(mutable.setComponents(x, y, z)); - if (y < 0 || y > 255) return result; + if (y < 0 || y > 255) { + return result; + } resetCache(); cache_checked.setOffset(x, z); cache_results.setOffset(x, z); cache_checked.add(x, y, z); - if (result) cache_results.add(x, y, z); + if (result) { + cache_results.add(x, y, z); + } return result; } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ExtremaMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ExtremaMask.java index 674d5eaa5..1ca577d48 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ExtremaMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ExtremaMask.java @@ -10,7 +10,8 @@ public class ExtremaMask extends AngleMask { @Override protected boolean testSlope(Extent extent, int x, int y, int z) { - double slope, tmp; + double slope; + double tmp; boolean aboveMin; lastY = y; @@ -19,13 +20,19 @@ public class ExtremaMask extends AngleMask { slope = getHeight(extent, base, x, y, z, 1, 0, distance) * ADJACENT_MOD; tmp = getHeight(extent, base, x, y, z, 0, 1, distance) * ADJACENT_MOD; - if (Math.abs(tmp) > Math.abs(slope)) slope = tmp; + if (Math.abs(tmp) > Math.abs(slope)) { + slope = tmp; + } tmp = getHeight(extent, base, x, y, z, 1, 1, distance) * DIAGONAL_MOD; - if (Math.abs(tmp) > Math.abs(slope)) slope = tmp; + if (Math.abs(tmp) > Math.abs(slope)) { + slope = tmp; + } tmp = getHeight(extent, base, x, y, z, 1, -1, distance) * DIAGONAL_MOD; - if (Math.abs(tmp) > Math.abs(slope)) slope = tmp; + if (Math.abs(tmp) > Math.abs(slope)) { + slope = tmp; + } return lastValue = (slope > min && slope < max); } @@ -35,7 +42,8 @@ public class ExtremaMask extends AngleMask { int lastHeight1 = base; int lastHeight2 = base; - int cox = OX, coz = OZ; + int cox = OX; + int coz = OZ; for (int i = 0; i < iterations; i++, cox += OX, coz += OZ) { int x1 = x + cox; int z1 = z + coz; @@ -49,11 +57,18 @@ public class ExtremaMask extends AngleMask { int sign2 = Integer.signum(diff2); if (sign == 0) { - if (sign1 != 0) sign = sign1; - else if (sign2 != 0) sign = sign2; + if (sign1 != 0) { + sign = sign1; + } else if (sign2 != 0) { + sign = sign2; + } + } + if (sign1 == 0) { + sign1 = sign; + } + if (sign2 == 0) { + sign2 = sign; } - if (sign1 == 0) sign1 = sign; - if (sign2 == 0) sign2 = sign; if (sign1 != sign2) { return (lastHeight1 - base) + (lastHeight2 - base); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/MaskedTargetBlock.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/MaskedTargetBlock.java index 88b94072e..789c8cab3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/MaskedTargetBlock.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/MaskedTargetBlock.java @@ -27,7 +27,9 @@ public class MaskedTargetBlock extends TargetBlock { if (lastBlock.getBlockY() <= 0 || lastBlock.getBlockY() >= world.getMaxY()) { searchForLastBlock = false; } - } else if (current.getBlockY() <= 0) break; + } else if (current.getBlockY() <= 0) { + break; + } } else { break; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/PlaneMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/PlaneMask.java index 385c16e30..98639ec4c 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/PlaneMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/PlaneMask.java @@ -7,7 +7,9 @@ import com.sk89q.worldedit.math.BlockVector3; public class PlaneMask extends AbstractMask implements ResettableMask { private transient int mode = -1; - private transient int originX = Integer.MAX_VALUE, originY = Integer.MAX_VALUE, originZ = Integer.MAX_VALUE; + private transient int originX = Integer.MAX_VALUE; + private transient int originY = Integer.MAX_VALUE; + private transient int originZ = Integer.MAX_VALUE; @Override public boolean test(BlockVector3 vector) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ROCAngleMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ROCAngleMask.java index bd9771fab..0e11ae3fe 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ROCAngleMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ROCAngleMask.java @@ -20,15 +20,21 @@ public class ROCAngleMask extends AngleMask { double tmp = (getHeight(extent, x, y, z + distance) - base - (base - getHeight(extent, x, y, z - distance))) * ADJACENT_MOD; - if (Math.abs(tmp) > Math.abs(slope)) slope = tmp; + if (Math.abs(tmp) > Math.abs(slope)) { + slope = tmp; + } tmp = (getHeight(extent, x + distance, y, z + distance) - base - (base - getHeight(extent, x - distance, y, z - distance))) * DIAGONAL_MOD; - if (Math.abs(tmp) > Math.abs(slope)) slope = tmp; + if (Math.abs(tmp) > Math.abs(slope)) { + slope = tmp; + } tmp = (getHeight(extent, x - distance, y, z + distance) - base - (base - getHeight(extent, x + distance, y, z - distance))) * DIAGONAL_MOD; - if (Math.abs(tmp) > Math.abs(slope)) slope = tmp; + if (Math.abs(tmp) > Math.abs(slope)) { + slope = tmp; + } return lastValue = slope >= min && slope <= max; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/RadiusMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/RadiusMask.java index 5ba49fe35..eb95e1d8f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/RadiusMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/RadiusMask.java @@ -7,7 +7,8 @@ import com.sk89q.worldedit.math.BlockVector3; public class RadiusMask extends AbstractMask implements ResettableMask { private transient BlockVector3 pos; - private final int minSqr, maxSqr; + private final int minSqr; + private final int maxSqr; public RadiusMask(int min, int max) { this.minSqr = min * min; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SimplexMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SimplexMask.java index 554a7dbd7..b2e9a5940 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SimplexMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SimplexMask.java @@ -6,7 +6,9 @@ import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.math.BlockVector3; public class SimplexMask extends AbstractMask { - private final double min, max, scale; + private final double min; + private final double max; + private final double scale; public SimplexMask(double scale, double min, double max) { this.scale = scale; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/WallMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/WallMask.java index a431043a7..3463e2478 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/WallMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/WallMask.java @@ -6,46 +6,47 @@ import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.MutableBlockVector3; public class WallMask extends AbstractMask { - private final int min, max; + private final int min; + private final int max; private final Mask mask; - private MutableBlockVector3 v; + private MutableBlockVector3 vector; public WallMask(Mask mask, int requiredMin, int requiredMax) { this.mask = mask; this.min = requiredMin; this.max = requiredMax; - this.v = new MutableBlockVector3(); + this.vector = new MutableBlockVector3(); } @Override public boolean test(BlockVector3 bv) { - v.setComponents(bv); + vector.setComponents(bv); int count = 0; - double x = v.getX(); - double y = v.getY(); - double z = v.getZ(); - v.mutX(x + 1); - if (mask.test(v) && ++count == min && max >= 8) { - v.mutX(x); + double x = vector.getX(); + double y = vector.getY(); + double z = vector.getZ(); + vector.mutX(x + 1); + if (mask.test(vector) && ++count == min && max >= 8) { + vector.mutX(x); return true; } - v.mutX(x - 1); - if (mask.test(v) && ++count == min && max >= 8) { - v.mutX(x); + vector.mutX(x - 1); + if (mask.test(vector) && ++count == min && max >= 8) { + vector.mutX(x); return true; } - v.mutX(x); - v.mutZ(z + 1); - if (mask.test(v) && ++count == min && max >= 8) { - v.mutZ(z); + vector.mutX(x); + vector.mutZ(z + 1); + if (mask.test(vector) && ++count == min && max >= 8) { + vector.mutZ(z); return true; } - v.mutZ(z - 1); - if (mask.test(v) && ++count == min && max >= 8) { - v.mutZ(z); + vector.mutZ(z - 1); + if (mask.test(vector) && ++count == min && max >= 8) { + vector.mutZ(z); return true; } - v.mutZ(z); + vector.mutZ(z); return count >= min && count <= max; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/AngleColorPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/AngleColorPattern.java index 223a683f7..8617bb8e5 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/AngleColorPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/AngleColorPattern.java @@ -29,21 +29,6 @@ public class AngleColorPattern extends DataAnglePattern { return (((color >> 24) & 0xFF) << 24) + (newRed << 16) + (newGreen << 8) + (newBlue << 0); } - @Override - public BaseBlock apply(BlockVector3 position) { - BaseBlock block = extent.getFullBlock(position); - int slope = getSlope(block, position, extent); - if (slope == -1) { - return block; - } - int color = holder.getTextureUtil().getColor(block.getBlockType()); - if (color == 0) { - return block; - } - int newColor = getColor(color, slope); - return holder.getTextureUtil().getNearestBlock(newColor).getDefaultState().toBaseBlock(); - } - @Override public > int getSlope(T block, BlockVector3 vector, Extent extent) { int slope = super.getSlope(block, vector, extent); @@ -62,6 +47,21 @@ public class AngleColorPattern extends DataAnglePattern { return slope; } + @Override + public BaseBlock apply(BlockVector3 position) { + BaseBlock block = extent.getFullBlock(position); + int slope = getSlope(block, position, extent); + if (slope == -1) { + return block; + } + int color = holder.getTextureUtil().getColor(block.getBlockType()); + if (color == 0) { + return block; + } + int newColor = getColor(color, slope); + return holder.getTextureUtil().getNearestBlock(newColor).getDefaultState().toBaseBlock(); + } + @Override public boolean apply(Extent extent, BlockVector3 get, BlockVector3 set) throws WorldEditException { BlockState block = get.getBlock(extent); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/AverageColorPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/AverageColorPattern.java index 6ef3b1a7f..5f5546682 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/AverageColorPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/AverageColorPattern.java @@ -34,10 +34,14 @@ public class AverageColorPattern extends AbstractExtentPattern { BlockType blockType = get.getBlock(extent).getBlockType(); TextureUtil util = holder.getTextureUtil(); int currentColor = util.getColor(blockType); - if (currentColor == 0) return false; + if (currentColor == 0) { + return false; + } int newColor = util.averageColor(currentColor, color); BlockType newBlock = util.getNearestBlock(newColor); - if (newBlock == blockType) return false; + if (newBlock == blockType) { + return false; + } return set.setBlock(extent, newBlock.getDefaultState()); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BufferedPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BufferedPattern.java index 0c5d72078..29a497242 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BufferedPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BufferedPattern.java @@ -24,7 +24,9 @@ public class BufferedPattern extends AbstractPattern implements ResettablePatter public BufferedPattern(Actor actor, Pattern parent) { this.uuid = actor.getUniqueId(); long[] tmp = actor.getMeta("lastActionTime"); - if (tmp == null) actor.setMeta("lastActionTime", tmp = new long[2]); + if (tmp == null) { + actor.setMeta("lastActionTime", tmp = new long[2]); + } actionTime = tmp; this.pattern = parent; this.timer = Fawe.get().getTimer(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/OffsetPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/OffsetPattern.java index 366f17bc7..86ff92615 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/OffsetPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/OffsetPattern.java @@ -10,7 +10,9 @@ import com.sk89q.worldedit.world.block.BaseBlock; public class OffsetPattern extends AbstractPattern { - private final int dx, dy, dz; + private final int dx; + private final int dy; + private final int dz; private transient MutableBlockVector3 mutable = new MutableBlockVector3(); private final Pattern pattern; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PatternTraverser.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PatternTraverser.java index ed0235ac7..aae740003 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PatternTraverser.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PatternTraverser.java @@ -32,7 +32,7 @@ public class PatternTraverser { Field field = current.getDeclaredField("extent"); field.setAccessible(true); field.set(pattern, newExtent); - } catch (NoSuchFieldException | IllegalAccessException | ClassCastException ignore) { + } catch (NoSuchFieldException | IllegalAccessException | ClassCastException ignored) { } } try { @@ -40,21 +40,21 @@ public class PatternTraverser { field.setAccessible(true); Object next = field.get(pattern); reset(next, newExtent); - } catch (NoSuchFieldException | IllegalAccessException | ClassCastException ignore) { + } catch (NoSuchFieldException | IllegalAccessException | ClassCastException ignored) { } try { Field field = current.getDeclaredField("mask"); field.setAccessible(true); Object next = field.get(pattern); reset(next, newExtent); - } catch (NoSuchFieldException | IllegalAccessException ignore) { + } catch (NoSuchFieldException | IllegalAccessException ignored) { } try { Field field = current.getDeclaredField("material"); field.setAccessible(true); Pattern next = (Pattern) field.get(pattern); reset(next, newExtent); - } catch (NoSuchFieldException | IllegalAccessException | ClassCastException ignore) { + } catch (NoSuchFieldException | IllegalAccessException | ClassCastException ignored) { } try { Field field = current.getDeclaredField("patterns"); @@ -63,7 +63,7 @@ public class PatternTraverser { for (Pattern next : patterns) { reset(next, newExtent); } - } catch (NoSuchFieldException | IllegalAccessException | ClassCastException ignore) { + } catch (NoSuchFieldException | IllegalAccessException | ClassCastException ignored) { } current = current.getSuperclass(); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PropertyPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PropertyPattern.java index e350617a2..55ba7325f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PropertyPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PropertyPattern.java @@ -62,7 +62,9 @@ public class PropertyPattern extends AbstractExtentPattern { } private void add(BlockType type, PropertyKey key, Operator operator, MutableCharSequence value, boolean wrap) { - if (!type.hasProperty(key)) return; + if (!type.hasProperty(key)) { + return; + } AbstractProperty property = (AbstractProperty) type.getProperty(key); BlockState defaultState = type.getDefaultState(); int valueInt; @@ -78,9 +80,14 @@ public class PropertyPattern extends AbstractExtentPattern { for (int i = 0; i < values.size(); i++) { int result = operator.apply(length, valueInt, i); - if (wrap) result = MathMan.wrap(result, 0, length - 1); - else result = Math.max(Math.min(result, length - 1), 0); - if (result == i) continue; + if (wrap) { + result = MathMan.wrap(result, 0, length - 1); + } else { + result = Math.max(Math.min(result, length - 1), 0); + } + if (result == i) { + continue; + } int internalId = valueInt + i; @@ -88,7 +95,9 @@ public class PropertyPattern extends AbstractExtentPattern { if (type.getProperties().size() > 1) { ArrayList properties = new ArrayList<>(type.getProperties().size() - 1); for (Property current : type.getProperties()) { - if (current == property) continue; + if (current == property) { + continue; + } properties.add(current); } applyRecursive(type, property, properties, 0, state, result); @@ -124,7 +133,9 @@ public class PropertyPattern extends AbstractExtentPattern { public PropertyPattern addRegex(String input) { if (input.charAt(input.length() - 1) == ']') { int propStart = StringMan.findMatchingBracket(input, input.length() - 1); - if (propStart == -1) return this; + if (propStart == -1) { + return this; + } MutableCharSequence charSequence = MutableCharSequence.getTemporal(); charSequence.setString(input); @@ -142,7 +153,9 @@ public class PropertyPattern extends AbstractExtentPattern { blockTypeList.add(myType); } } - if (blockTypeList.size() == 1) type = blockTypeList.get(0); + if (blockTypeList.size() == 1) { + type = blockTypeList.get(0); + } } PropertyKey key = null; @@ -157,14 +170,17 @@ public class PropertyPattern extends AbstractExtentPattern { case '{': case '(': int next = StringMan.findMatchingBracket(input, i); - if (next != -1) i = next; + if (next != -1) { + i = next; + } break; case ']': case ',': { charSequence.setSubstring(last, i); char firstChar = input.charAt(last + 1); - if (type != null) add(type, key, operator, charSequence, wrap); - else { + if (type != null) { + add(type, key, operator, charSequence, wrap); + } else { for (BlockType myType : blockTypeList) { add(myType, key, operator, charSequence, wrap); } @@ -180,8 +196,12 @@ public class PropertyPattern extends AbstractExtentPattern { char cp = input.charAt(i + 1); boolean extra = cp == '='; wrap = cp == '~'; - if (extra || wrap) i++; - if (charSequence.length() > 0) key = PropertyKey.get(charSequence); + if (extra || wrap) { + i++; + } + if (charSequence.length() > 0) { + key = PropertyKey.get(charSequence); + } last = i + 1; } break; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomOffsetPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomOffsetPattern.java index 29081cf48..f954113c3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomOffsetPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomOffsetPattern.java @@ -11,10 +11,14 @@ import com.sk89q.worldedit.world.block.BaseBlock; import java.util.SplittableRandom; public class RandomOffsetPattern extends AbstractPattern { - private final int dx, dy, dz; + private final int dx; + private final int dy; + private final int dz; private final Pattern pattern; - private transient int dx2, dy2, dz2; + private transient int dx2; + private transient int dy2; + private transient int dz2; private transient MutableBlockVector3 mutable = new MutableBlockVector3(); private transient SplittableRandom r; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SaturatePattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SaturatePattern.java index 244c1b46b..19b608aa9 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SaturatePattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SaturatePattern.java @@ -37,10 +37,14 @@ public class SaturatePattern extends AbstractPattern { BlockType block = get.getBlock(extent).getBlockType(); TextureUtil util = holder.getTextureUtil(); int currentColor = util.getColor(block); - if (currentColor == 0) return false; + if (currentColor == 0) { + return false; + } int newColor = util.multiplyColor(currentColor, color); BlockType newBlock = util.getNearestBlock(newColor); - if (newBlock.equals(block)) return false; + if (newBlock.equals(block)) { + return false; + } return set.setBlock(extent, newBlock.getDefaultState()); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SolidRandomOffsetPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SolidRandomOffsetPattern.java index a6283fd65..9d0c15ab9 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SolidRandomOffsetPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SolidRandomOffsetPattern.java @@ -14,10 +14,14 @@ import com.sk89q.worldedit.world.block.BlockTypesCache; import java.util.SplittableRandom; public class SolidRandomOffsetPattern extends AbstractPattern { - private final int dx, dy, dz; + private final int dx; + private final int dy; + private final int dz; private final Pattern pattern; - private final int dx2, dy2, dz2; + private final int dx2; + private final int dy2; + private final int dz2; private final MutableBlockVector3 mutable; private SplittableRandom r; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/regions/FuzzyRegion.java b/worldedit-core/src/main/java/com/boydti/fawe/object/regions/FuzzyRegion.java index ed672da39..09cd656da 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/regions/FuzzyRegion.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/regions/FuzzyRegion.java @@ -18,7 +18,12 @@ public class FuzzyRegion extends AbstractRegion { private final Mask mask; private BlockVectorSet set = new BlockVectorSet(); - private int minX, minY, minZ, maxX, maxY, maxZ; + private int minX; + private int minY; + private int minZ; + private int maxX; + private int maxY; + private int maxZ; private Extent extent; { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/regions/PolyhedralRegion.java b/worldedit-core/src/main/java/com/boydti/fawe/object/regions/PolyhedralRegion.java index 3c1e8b07f..c80362d41 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/regions/PolyhedralRegion.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/regions/PolyhedralRegion.java @@ -281,12 +281,24 @@ public class PolyhedralRegion extends AbstractRegion { final int z = position.getBlockZ(); final BlockVector3 min = getMinimumPoint(); final BlockVector3 max = getMaximumPoint(); - if (x < min.getBlockX()) return false; - if (x > max.getBlockX()) return false; - if (z < min.getBlockZ()) return false; - if (z > max.getBlockZ()) return false; - if (y < min.getBlockY()) return false; - if (y > max.getBlockY()) return false; + if (x < min.getBlockX()) { + return false; + } + if (x > max.getBlockX()) { + return false; + } + if (z < min.getBlockZ()) { + return false; + } + if (z > max.getBlockZ()) { + return false; + } + if (y < min.getBlockY()) { + return false; + } + if (y > max.getBlockY()) { + return false; + } return containsRaw(position); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/regions/Triangle.java b/worldedit-core/src/main/java/com/boydti/fawe/object/regions/Triangle.java index 7066564c9..04e1c9cd5 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/regions/Triangle.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/regions/Triangle.java @@ -93,7 +93,8 @@ public class Triangle { private boolean axisTestX01(double a, double b, double fa, double fb) { double p0 = a * v0[1] - b * v0[2]; double p2 = a * v2[1] - b * v2[2]; - double min, max; + double min; + double max; if (p0 < p2) { min = p0; max = p2; @@ -108,7 +109,8 @@ public class Triangle { private boolean axisTestX2(double a, double b, double fa, double fb) { double p0 = a * v0[1] - b * v0[2]; double p1 = a * v1[1] - b * v1[2]; - double min, max; + double min; + double max; if (p0 < p1) { min = p0; max = p1; @@ -123,7 +125,8 @@ public class Triangle { private boolean axisTestY02(double a, double b, double fa, double fb) { double p0 = -a * v0[0] + b * v0[2]; double p2 = -a * v2[0] + b * v2[2]; - double min, max; + double min; + double max; if (p0 < p2) { min = p0; max = p2; @@ -138,7 +141,8 @@ public class Triangle { private boolean axisTestY1(double a, double b, double fa, double fb) { double p0 = -a * v0[0] + b * v0[2]; double p1 = -a * v1[0] + b * v1[2]; - double min, max; + double min; + double max; if (p0 < p1) { min = p0; max = p1; @@ -153,7 +157,8 @@ public class Triangle { private boolean axisTestZ12(double a, double b, double fa, double fb) { double p1 = a * v1[0] - b * v1[1]; double p2 = a * v2[0] - b * v2[1]; - double min, max; + double min; + double max; if (p2 < p1) { min = p2; max = p1; @@ -168,7 +173,8 @@ public class Triangle { private boolean axisTestZ0(double a, double b, double fa, double fb) { double p0 = a * v0[0] - b * v0[1]; double p1 = a * v1[0] - b * v1[1]; - double min, max; + double min; + double max; if (p0 < p1) { min = p0; max = p1; @@ -182,7 +188,11 @@ public class Triangle { private boolean overlaps(double[] boxcenter, double[] boxhalfsize, double[][] triverts) { - double min, max, fex, fey, fez; + double min; + double max; + double fex; + double fey; + double fez; sub(v0, triverts[0], boxcenter); sub(v1, triverts[1], boxcenter); sub(v2, triverts[2], boxcenter); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/MinecraftStructure.java b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/MinecraftStructure.java index bfe0acb6a..ac253155c 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/MinecraftStructure.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/MinecraftStructure.java @@ -187,7 +187,9 @@ public class MinecraftStructure implements ClipboardReader, ClipboardWriter { for (AbstractProperty property : (List>) type.getProperties()) { int propIndex = property.getIndex(block.getInternalId()); if (propIndex != 0) { - if (properties == null) properties = new HashMap<>(); + if (properties == null) { + properties = new HashMap<>(); + } Object value = property.getValues().get(propIndex); properties.put(property.getName(), value.toString()); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/PNGWriter.java b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/PNGWriter.java index 2a1b6c2b3..78f0b8331 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/PNGWriter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/PNGWriter.java @@ -65,7 +65,10 @@ public class PNGWriter implements ClipboardWriter { boolean fill = length * 4 < imageSize && width * 4 < imageSize; - MutableBlockVector3 mutable, mutableTop, mutableRight, mutableLeft; + MutableBlockVector3 mutable; + MutableBlockVector3 mutableTop; + MutableBlockVector3 mutableRight; + MutableBlockVector3 mutableLeft; mutable = mutableTop = mutableRight = mutableLeft = new MutableBlockVector3(0, 0, 0); // Vector mutableTop = new Vector(0, 0, 0); // Vector mutableRight = new Vector(0, 0, 0); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/visualizer/SchemVis.java b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/visualizer/SchemVis.java index 33ffc9696..93295efae 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/visualizer/SchemVis.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/visualizer/SchemVis.java @@ -129,7 +129,7 @@ // URI uri = file.toURI(); // ClipboardFormat format = ClipboardFormats.findByFile(file); // format.hold(player, uri, new FileInputStream(file)); -// player.print(TranslatableComponent.of("fawe.worldedit.schematic.schematic.loaded" , filename)); +// player.print(TranslatableComponent.of("fawe.worldedit.schematic.schematic.loaded", filename)); // session.setVirtualWorld(null); // return; // } @@ -165,7 +165,7 @@ // MultiClipboardHolder multi = new MultiClipboardHolder(URI.create(""), new LazyClipboardHolder(uri, source, format, null)); // session.addClipboard(multi); // select.put(clicked, true); -// player.print(TranslatableComponent.of("fawe.worldedit.schematic.schematic.loaded" , file.getName())); +// player.print(TranslatableComponent.of("fawe.worldedit.schematic.schematic.loaded", file.getName())); // } // } // // Resend relevant chunks @@ -590,28 +590,4 @@ // } // } // } -// -// @Override -// public boolean playEffect(Vector3 position, int type, int data) { -// // TODO Auto-generated method stub -// return false; -// } -// -// @Override -// public boolean setBiome(BlockVector2 position, BiomeType biome) { -// // TODO Auto-generated method stub -// return false; -// } -// -// @Override -// public boolean notifyAndLightBlock(BlockVector3 position, BlockState previousType) throws WorldEditException { -// // TODO Auto-generated method stub -// return false; -// } -// -// @Override -// public BlockVector3 getSpawnPosition() { -// // TODO Auto-generated method stub -// return null; -// } //} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/string/JoinedCharSequence.java b/worldedit-core/src/main/java/com/boydti/fawe/object/string/JoinedCharSequence.java index 5b134a468..8c494c830 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/string/JoinedCharSequence.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/string/JoinedCharSequence.java @@ -61,7 +61,9 @@ public class JoinedCharSequence implements CharSequence { CharSequence anotherString = (CharSequence) obj; if (length == anotherString.length()) { for (int i = length - 1; i >= 0; i--) { - if (charAt(i) != anotherString.charAt(i)) return false; + if (charAt(i) != anotherString.charAt(i)) { + return false; + } } return true; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/string/MutableCharSequence.java b/worldedit-core/src/main/java/com/boydti/fawe/object/string/MutableCharSequence.java index 5785f9885..05c00c434 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/string/MutableCharSequence.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/string/MutableCharSequence.java @@ -2,7 +2,8 @@ package com.boydti.fawe.object.string; public class MutableCharSequence implements CharSequence { private String str; - private int start, length; + private int start; + private int length; private static final ThreadLocal mutableChar = ThreadLocal.withInitial(MutableCharSequence::new); @@ -16,7 +17,8 @@ public class MutableCharSequence implements CharSequence { this.length = length; } - public MutableCharSequence() {} + public MutableCharSequence() { + } public void setSubstring(int start, int end) { this.start = start; @@ -58,7 +60,9 @@ public class MutableCharSequence implements CharSequence { public int indexOf(char c) { for (int i = 0; i < length; i++) { - if (charAt(i) == c) return i; + if (charAt(i) == c) { + return i; + } } return -1; } @@ -68,7 +72,9 @@ public class MutableCharSequence implements CharSequence { CharSequence anotherString = (CharSequence) obj; if (length == anotherString.length()) { for (int i = length - 1; i >= 0; i--) { - if (charAt(i) != anotherString.charAt(i)) return false; + if (charAt(i) != anotherString.charAt(i)) { + return false; + } } return true; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/task/AsyncNotifyQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/object/task/AsyncNotifyQueue.java index 9dccb56d7..16ed7c4e8 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/task/AsyncNotifyQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/task/AsyncNotifyQueue.java @@ -44,14 +44,18 @@ public class AsyncNotifyQueue implements Closeable { return task.call(); } catch (Throwable e) { handler.uncaughtException(Thread.currentThread(), e); - if (self[0] != null) self[0].cancel(true); + if (self[0] != null) { + self[0].cancel(true); + } } } } finally { lock.unlock(); } } - if (self[0] != null) self[0].cancel(true); + if (self[0] != null) { + self[0].cancel(true); + } return null; }; self[0] = Fawe.get().getQueueHandler().async(wrapped); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/task/SingleThreadIntervalQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/object/task/SingleThreadIntervalQueue.java index 5271a7e32..887b3c14f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/task/SingleThreadIntervalQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/task/SingleThreadIntervalQueue.java @@ -30,8 +30,11 @@ public abstract class SingleThreadIntervalQueue { } } synchronized (objMap) { - if (!objMap.isEmpty()) TaskManager.IMP.laterAsync(this, interval); - else queued.set(false); + if (!objMap.isEmpty()) { + TaskManager.IMP.laterAsync(this, interval); + } else { + queued.set(false); + } } } }; 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 5d6b9d05d..bd6b7e06c 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 @@ -156,7 +156,9 @@ public abstract class DFSVisitor implements Operation { public static final class Node { - private int x, y, z; + private int x; + private int y; + private int z; public Node(int x, int y, int z) { this.x = x; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/FaweMaskManager.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/FaweMaskManager.java index 7653db67e..dcc7a5994 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/FaweMaskManager.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/FaweMaskManager.java @@ -4,18 +4,19 @@ import com.boydti.fawe.config.Settings; import com.boydti.fawe.regions.general.RegionFilter; import com.sk89q.worldedit.entity.Player; +import java.util.Locale; + public abstract class FaweMaskManager { public enum MaskType { OWNER, - MEMBER - - ; + MEMBER; public static MaskType getDefaultMaskType() { try { - return MaskType.valueOf(Settings.IMP.REGION_RESTRICTIONS_OPTIONS.MODE.toUpperCase()); - } catch (Exception ignore) { + return MaskType + .valueOf(Settings.IMP.REGION_RESTRICTIONS_OPTIONS.MODE.toUpperCase(Locale.ROOT)); + } catch (Exception ignored) { return MEMBER; } } @@ -24,7 +25,7 @@ public abstract class FaweMaskManager { private final String key; public FaweMaskManager(final String plugin) { - this.key = plugin.toLowerCase(); + this.key = plugin.toLowerCase(Locale.ROOT); } public String getKey() { @@ -36,7 +37,9 @@ public abstract class FaweMaskManager { return this.key; } - public FaweMask getMask(final Player player, MaskType type){ return null; } + public FaweMask getMask(final Player player, MaskType type) { + return null; + } public boolean isValid(FaweMask mask) { return true; 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 550c722e9..48e4ce78d 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 @@ -29,44 +29,56 @@ public final class BrushCache { private static final ThreadLocal RECURSION = new ThreadLocal<>(); public static final BrushTool getTool(Player player, LocalSession session, BaseItem item) { - if (!item.hasNbtData()) return null; + if (!item.hasNbtData()) { + return null; + } Object key = getKey(item); - if (key == null) return null; + if (key == null) { + return null; + } BrushTool cached = brushCache.get(key); - if (cached != null) return cached; + if (cached != null) { + return cached; + } CompoundTag nbt = item.getNbtData(); - if (nbt == null) return null; + if (nbt == null) { + return null; + } StringTag json = (StringTag) nbt.getValue().get("weBrushJson"); - // TODO: Ping @MattBDev to reimplement 2020-02-04 -// if (json != null) { -// try { -// if (RECURSION.get() != null) return null; -// RECURSION.set(true); -// -// BrushTool tool = BrushTool.fromString(player, session, json.getValue()); -// tool.setHolder(item); -// brushCache.put(key, tool); -// return tool; -// } catch (Exception throwable) { -// getLogger(BrushCache.class).debug("Invalid brush for " + player + " holding " + item.getType() + ": " + json.getValue(), throwable); -// item.setNbtData(null); -// brushCache.remove(key); -// } finally { -// RECURSION.remove(); -// } -// } + // TODO: Write a Brush standard format + /* if (json != null) { + try { + if (RECURSION.get() != null) return null; + RECURSION.set(true); + + BrushTool tool = BrushTool.fromString(player, session, json.getValue()); + tool.setHolder(item); + brushCache.put(key, tool); + return tool; + } catch (Exception throwable) { + getLogger(BrushCache.class).debug("Invalid brush for " + player + " holding " + item.getType() + ": " + json.getValue(), throwable); + item.setNbtData(null); + brushCache.remove(key); + } finally { + RECURSION.remove(); + } + }*/ return null; } public static BrushTool getCachedTool(BaseItem item) { Object key = getKey(item); - if (key != null) return brushCache.get(key); + if (key != null) { + return brushCache.get(key); + } return null; } public static final BrushTool setTool(BaseItem item, BrushTool tool) { - if (item.getNativeItem() == null) return null; + if (item.getNativeItem() == null) { + return null; + } CompoundTag nbt = item.getNbtData(); Map map; 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 21a3d4de1..d093a0707 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 @@ -21,6 +21,7 @@ public class CachedMathMan { } private static float[] ANGLES = new float[65536]; + static { for (int i = 0; i < 65536; ++i) { ANGLES[i] = (float) Math.sin((double) i * Math.PI * 2.0D / 65536.0D); @@ -28,6 +29,7 @@ public class CachedMathMan { } private static char[] SQRT = new char[65536]; + static { for (int i = 0; i < SQRT.length; i++) { SQRT[i] = (char) Math.round(Math.sqrt(i)); @@ -35,8 +37,8 @@ public class CachedMathMan { } /** - * Optimized for i elem 0,65536 (characters) - * @param i + * Optimized for i elem 0,65536 (characters). + * * @return square root */ protected static int usqrt(int i) { @@ -51,24 +53,25 @@ public class CachedMathMan { return ANGLES[(int) (paramFloat * 10430.378F + 16384.0F) & 0xFFFF]; } - protected static float atan2(float y, float x) { - float add, mul; + protected static float atan2(float i, float j) { + float add; + float mul; - if (x < 0.0f) { - if (y < 0.0f) { - x = -x; - y = -y; + if (j < 0.0f) { + if (i < 0.0f) { + j = -j; + i = -i; mul = 1.0f; } else { - x = -x; + j = -j; mul = -1.0f; } add = (float) -Math.PI; } else { - if (y < 0.0f) { - y = -y; + if (i < 0.0f) { + i = -i; mul = -1.0f; } else { mul = 1.0f; @@ -77,10 +80,10 @@ public class CachedMathMan { add = 0.0f; } - float invDiv = 1.0f / ((Math.max(x, y)) * INV_ATAN2_DIM_MINUS_1); + float invDiv = 1.0f / ((Math.max(j, i)) * INV_ATAN2_DIM_MINUS_1); - int xi = (int) (x * invDiv); - int yi = (int) (y * invDiv); + int xi = (int) (j * invDiv); + int yi = (int) (i * invDiv); return (atan2[(yi * ATAN2_DIM) + xi] + add) * mul; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/CleanTextureUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/CleanTextureUtil.java index 53d72efef..31de561f5 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/CleanTextureUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/CleanTextureUtil.java @@ -4,7 +4,8 @@ import java.io.FileNotFoundException; import java.util.Arrays; public class CleanTextureUtil extends TextureUtil { - private final int min, max; + private final int min; + private final int max; public CleanTextureUtil(TextureUtil parent, int minPercent, int maxPercent) throws FileNotFoundException { super(parent.getFolder()); @@ -14,8 +15,12 @@ public class CleanTextureUtil extends TextureUtil { int maxIndex = (parent.distances.length - 1) * maxPercent / 100; long min = parent.distances[minIndex]; long max = parent.distances[maxIndex]; - for (; minIndex > 0 && parent.distances[minIndex - 1] == min; minIndex--) ; - for (; maxIndex < parent.distances.length - 1 && parent.distances[maxIndex + 1] == max; maxIndex++) ; + for (; minIndex > 0 && parent.distances[minIndex - 1] == min; minIndex--) { + ; + } + for (; maxIndex < parent.distances.length - 1 && parent.distances[maxIndex + 1] == max; maxIndex++) { + ; + } int num = maxIndex - minIndex + 1; this.validMixBiomeColors = parent.validMixBiomeColors; this.validMixBiomeIds = parent.validMixBiomeIds; 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 70f53c47a..70cc320c9 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 @@ -103,9 +103,9 @@ public class ColorUtil { } else { Color col = null; try { - Field field = Color.class.getField(color.toLowerCase()); + Field field = Color.class.getField(color.toLowerCase(Locale.ROOT)); col = (Color) field.get(null); - } catch (Throwable ignore) { + } catch (Throwable ignored) { } if (col != null) { return col; 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 f09d7a42e..a892f5384 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 @@ -2,7 +2,6 @@ package com.boydti.fawe.util; import com.boydti.fawe.Fawe; import com.boydti.fawe.FaweCache; -import com.boydti.fawe.beta.IBatchProcessor; import com.boydti.fawe.beta.IQueueChunk; import com.boydti.fawe.beta.IQueueExtent; import com.boydti.fawe.beta.implementation.processors.LimitExtent; @@ -30,7 +29,6 @@ import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.extent.EditSessionEvent; -import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.regions.Region; @@ -41,6 +39,7 @@ import com.sk89q.worldedit.world.World; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; +import java.util.Locale; import java.util.UUID; import static com.google.common.base.Preconditions.checkNotNull; @@ -126,12 +125,6 @@ public class EditSessionBuilder { return this; } - /** - * @param disk If it should be stored on disk - * @param uuid The uuid to store it under (if on disk) - * @param compression Compression level (0-9) - * @return - */ public EditSessionBuilder changeSet(boolean disk, @Nullable UUID uuid, int compression) { if (disk) { if (Settings.IMP.HISTORY.USE_DATABASE) { @@ -218,13 +211,13 @@ public class EditSessionBuilder { return new NullExtent(extent, FaweCache.MANUAL); } final Extent toReturn = event.getExtent(); - if(toReturn instanceof com.sk89q.worldedit.extent.NullExtent) { + if (toReturn instanceof com.sk89q.worldedit.extent.NullExtent) { return new NullExtent(toReturn, FaweCache.MANUAL); } if (toReturn != extent) { - String className = toReturn.getClass().getName().toLowerCase(); + String className = toReturn.getClass().getName().toLowerCase(Locale.ROOT); for (String allowed : Settings.IMP.EXTENT.ALLOWED_PLUGINS) { - if (className.contains(allowed.toLowerCase())) { + if (className.contains(allowed.toLowerCase(Locale.ROOT))) { this.wrapped = true; return toReturn; } @@ -253,7 +246,9 @@ public class EditSessionBuilder { private boolean wrapped; public EditSessionBuilder compile() { - if (compiled) return this; + if (compiled) { + return this; + } compiled = true; wrapped = false; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/FilteredTextureUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/FilteredTextureUtil.java index 62ea7eea7..1956540b0 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/FilteredTextureUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/FilteredTextureUtil.java @@ -23,7 +23,9 @@ public class FilteredTextureUtil extends TextureUtil { int num = 0; for (int i = 0; i < parent.validBlockIds.length; i++) { BlockType block = BlockTypes.get(parent.validBlockIds[i]); - if (blocks.contains(block)) num++; + if (blocks.contains(block)) { + num++; + } } this.validBlockIds = new int[num]; this.validColors = new int[num]; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/IOUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/IOUtil.java index 8430a9720..48367a076 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/IOUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/IOUtil.java @@ -18,8 +18,9 @@ public final class IOUtil { int ch2 = in.read(); int ch3 = in.read(); int ch4 = in.read(); - if ((ch1 | ch2 | ch3 | ch4) < 0) + if ((ch1 | ch2 | ch3 | ch4) < 0) { throw new EOFException(); + } return (ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/MainUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/MainUtil.java index 90e36a915..5cbad4b7f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/MainUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/MainUtil.java @@ -67,6 +67,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Scanner; import java.util.UUID; @@ -149,7 +150,9 @@ public class MainUtil { } public static File resolveRelative(File file) { - if (!file.exists()) return new File(relativize(file.getPath())); + if (!file.exists()) { + return new File(relativize(file.getPath())); + } return file; } @@ -159,11 +162,15 @@ public class MainUtil { int skip = 0; int len = split.length - 1; for (int i = len; i >= 0; i--) { - if (skip > 0) skip--; - else { + if (skip > 0) { + skip--; + } else { String arg = split[i]; - if (arg.equals("..")) skip++; - else out.insert(0, arg + (i == len ? "" : File.separator)); + if (arg.equals("..")) { + skip++; + } else { + out.insert(0, arg + (i == len ? "" : File.separator)); + } } } return out.toString(); @@ -171,9 +178,13 @@ public class MainUtil { public static void forEachFile(Path path, final RunnableVal2 onEach, Comparator comparator) { File dir = path.toFile(); - if (!dir.exists()) return; + if (!dir.exists()) { + return; + } File[] files = path.toFile().listFiles(); - if (comparator != null) Arrays.sort(files, comparator); + if (comparator != null) { + Arrays.sort(files, comparator); + } for (File file : files) { Path filePath = file.toPath(); try { @@ -194,9 +205,13 @@ public class MainUtil { val = StringMan.toInteger(name, 0, name.length()); } else { int i = name.lastIndexOf('.'); - if (i != -1) val = StringMan.toInteger(name, 0, i); + if (i != -1) { + val = StringMan.toInteger(name, 0, i); + } + } + if (val != null && val > max[0]) { + max[0] = val; } - if (val != null && val > max[0]) max[0] = val; return false; }); return max[0] + 1; @@ -273,7 +288,9 @@ public class MainUtil { ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (!inflater.finished()) { int n = inflater.inflate(buffer); - if (n != 0) baos.write(buffer, 0, n); + if (n != 0) { + baos.write(buffer, 0, n); + } } return baos.toByteArray(); } @@ -536,7 +553,9 @@ public class MainUtil { } public static BufferedImage toRGB(BufferedImage src) { - if (src == null) return src; + if (src == null) { + return src; + } BufferedImage img = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.drawImage(src, 0, 0, null); @@ -646,18 +665,26 @@ public class MainUtil { } if (allowDir) { File file = MainUtil.resolveRelative(new File(dir, filename)); - if (file.exists() && file.isDirectory()) return file; + if (file.exists() && file.isDirectory()) { + return file; + } } for (ClipboardFormat f : ClipboardFormats.getAll()) { File file = MainUtil.resolveRelative(new File(dir, filename + "." + f.getPrimaryFileExtension())); - if (file.exists()) return file; + if (file.exists()) { + return file; + } } return null; } public static boolean isInSubDirectory(File dir, File file) throws IOException { - if (file == null) return false; - if (file.equals(dir)) return true; + if (file == null) { + return false; + } + if (file.equals(dir)) { + return true; + } file = file.getCanonicalFile(); dir = dir.getCanonicalFile(); return isInSubDirectory(dir, file.getParentFile()); @@ -779,7 +806,7 @@ public class MainUtil { if (MathMan.isInteger(string)) { return Long.parseLong(string); } - string = string.toLowerCase().trim().toLowerCase(); + string = string.toLowerCase(Locale.ROOT).trim().toLowerCase(Locale.ROOT); if (string.equalsIgnoreCase("false")) { return 0; } @@ -830,7 +857,9 @@ public class MainUtil { if (age > timeDiff) { pool.submit(file::delete); Component msg = TranslatableComponent.of("worldedit.schematic.delete.deleted"); - if (printDebug) Fawe.debug(msg); + if (printDebug) { + Fawe.debug(msg); + } } }); pool.shutdown(); 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 4aa8b1047..a411f9943 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 @@ -3,15 +3,16 @@ package com.boydti.fawe.util; public class MathMan { /** - * Optimized for i elem 0,65536 (characters) - * @param i - * @return square root + * An optimized version of {@link Math#sqrt(double)} that accepts integers. + * @param a a value + * @return the positive square root of {@code a}. + * If the argument is NaN or less than zero, the result is NaN. */ - public static int usqrt(int i) { - if (i < 65536) { - return CachedMathMan.usqrt(i); + public static int usqrt(int a) { + if (a < 65536) { + return CachedMathMan.usqrt(a); } - return (int) Math.round(Math.sqrt(i)); + return (int) Math.round(Math.sqrt(a)); } public static float sinInexact(double paramFloat) { @@ -52,23 +53,11 @@ public class MathMan { } public static int min(int... values) { - int min = Integer.MAX_VALUE; - for (int d : values) { - if (d < min) { - min = d; - } - } - return min; + return Math.min(Math.min(values[0], values[1]), values[2]); } public static double min(double... values) { - double min = Double.MAX_VALUE; - for (double d : values) { - if (d < min) { - min = d; - } - } - return min; + return Math.min(Math.min(values[0], values[1]), values[2]); } public static int ceilZero(float floatNumber) { @@ -138,8 +127,8 @@ public class MathMan { return (short) (hash & 0xFFFF); } - public static short pairByte(int x, int y) { - return (short) ((x << 8) | (y & 0xFF)); + public static short pairByte(int a, int b) { + return (short) ((a << 8) | (b & 0xFF)); } public static byte unpairShortX(short pair) { @@ -150,8 +139,14 @@ public class MathMan { return (byte) pair; } - public static long pairInt(int x, int y) { - return ((long) x << 32) | (y & 0xffffffffL); + /** + * Used to convert a set of coordinates into a packed long. + * @param a typically, represents the x coordinate + * @param b typically, represents the y coordinate + * @return the packed coordinates + */ + public static long pairInt(int a, int b) { + return ((long) a << 32) | (b & 0xffffffffL); } public static long tripleWorldCoord(int x, int y, int z) { @@ -200,8 +195,7 @@ public class MathMan { return ((b1 & 0xFF) + ((b2 & 0x7F) << 8) + ((b3 & 0xFF) << 15) - + ((b4 & 0xFF) << 23)) - ; + + ((b4 & 0xFF) << 23)); } public static int pairSearchCoords(int x, int y) { @@ -304,11 +298,7 @@ public class MathMan { } /** - * Returns [x, y, z] - * - * @param yaw - * @param pitch - * @return + * Returns [x, y, z]. */ public static float[] getDirection(float yaw, float pitch) { double pitch_sin = Math.sin(pitch); @@ -320,20 +310,15 @@ public class MathMan { } /** - * Returns [ pitch, yaw ] - * - * @param x - * @param y - * @param z - * @return + * Returns [ pitch, yaw ]. */ public static float[] getPitchAndYaw(float x, float y, float z) { float distance = sqrtApprox((z * z) + (x * x)); return new float[]{atan2(y, distance), atan2(x, z)}; } - public static float atan2(float y, float x) { - return CachedMathMan.atan2(y, x); + public static float atan2(float i, float j) { + return CachedMathMan.atan2(i, j); } public static float sqrtApprox(float f) { @@ -341,7 +326,7 @@ public class MathMan { } public static double sqrtApprox(double d) { - return Double.longBitsToDouble(((Double.doubleToLongBits(d) - (1l << 52)) >> 1) + (1l << 61)); + return Double.longBitsToDouble(((Double.doubleToLongBits(d) - (1L << 52)) >> 1) + (1L << 61)); } public static float invSqrt(float x) { @@ -397,21 +382,21 @@ public class MathMan { return (value ^ (value >> 8)) - (value >> 8); } - public static int mod(int x, int y) { - if (isPowerOfTwo(y)) { - return x & (y - 1); + public static int mod(int a, int b) { + if (isPowerOfTwo(b)) { + return a & (b - 1); } - return x % y; + return a % b; } - public static int unsignedmod(int x, int y) { - if (isPowerOfTwo(y)) { - return x & (y - 1); + public static int unsignedMod(int a, int b) { + if (isPowerOfTwo(b)) { + return a & (b - 1); } - return x % y; + return a % b; } - public static boolean isPowerOfTwo(int x) { - return (x & (x - 1)) == 0; + public static boolean isPowerOfTwo(int a) { + return (a & a - 1) == 0; } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/MemUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/MemUtil.java index 7cb9a5aa7..7f16c78e5 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/MemUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/MemUtil.java @@ -55,13 +55,15 @@ public class MemUtil { private static Queue memoryPlentifulTasks = new ConcurrentLinkedQueue<>(); public static void addMemoryLimitedTask(Runnable run) { - if (run != null) + if (run != null) { memoryLimitedTasks.add(run); + } } public static void addMemoryPlentifulTask(Runnable run) { - if (run != null) + if (run != null) { memoryPlentifulTasks.add(run); + } } public static void memoryLimitedTask() { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/RandomTextureUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/RandomTextureUtil.java index d87f00310..bb2b23076 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/RandomTextureUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/RandomTextureUtil.java @@ -50,7 +50,9 @@ public class RandomTextureUtil extends CachedTextureUtil { mix[3] = average; biomeMixes.put(color, mix); } - if (++index > 2) index = 0; + if (++index > 2) { + index = 0; + } int biomeId = mix[index]; int biomeAvColor = mix[3]; int blockColor = getColor(block); @@ -73,7 +75,9 @@ public class RandomTextureUtil extends CachedTextureUtil { mix[3] = average; biomeMixes.put(color, mix); } - if (++index > 2) index = 0; + if (++index > 2) { + index = 0; + } int biomeId = mix[index]; return getBiome(biomeId); } @@ -87,7 +91,9 @@ public class RandomTextureUtil extends CachedTextureUtil { offsetColor = color; } BlockType res = super.getNearestBlock(offsetColor); - if (res == null) return null; + if (res == null) { + return null; + } int newColor = getColor(res); byte dr = (byte) (((color >> 16) & 0xFF) - ((newColor >> 16) & 0xFF)); byte dg = (byte) (((color >> 8) & 0xFF) - ((newColor >> 8) & 0xFF)); 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 8be037b13..869d5dce8 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 @@ -25,8 +25,7 @@ public class ReflectionUtils { return ReflectionUtils9.addEnum(enumType, enumName); } - public static void setAccessibleNonFinal(Field field) - throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { + public static void setAccessibleNonFinal(Field field) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { // let's make the field accessible field.setAccessible(true); @@ -48,26 +47,22 @@ public class ReflectionUtils { } } - public static void setFailsafeFieldValue(Field field, Object target, Object value) - throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { - + public static void setFailsafeFieldValue(Field field, Object target, Object value) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { setAccessibleNonFinal(field); field.set(target, value); } - private static void blankField(Class enumClass, String fieldName) - throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { + private static void blankField(Class enumClass, String fieldName) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { for (Field field : Class.class.getDeclaredFields()) { if (field.getName().contains(fieldName)) { - AccessibleObject.setAccessible(new Field[]{field}, true); + AccessibleObject.setAccessible(new Field[] { field }, true); setFailsafeFieldValue(field, enumClass, null); break; } } } - static void cleanEnumCache(Class enumClass) - throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { + static void cleanEnumCache(Class enumClass) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6 blankField(enumClass, "enumConstants"); // IBM JDK } @@ -175,12 +170,11 @@ public class ReflectionUtils { return null; } - public static Method findMethod(Class clazz, Class returnType, Class... params) { + public static Method findMethod(Class clazz, Class returnType, Class... params) { return findMethod(clazz, 0, returnType, params); } - public static Method findMethod(Class clazz, int index, int hasMods, int noMods, - Class returnType, Class... params) { + public static Method findMethod(Class clazz, int index, int hasMods, int noMods, Class returnType, Class... params) { outer: for (Method method : sortMethods(clazz.getDeclaredMethods())) { if (returnType == null || method.getReturnType() == returnType) { @@ -213,6 +207,10 @@ public class ReflectionUtils { return null; } + public static Method findMethod(Class clazz, int index, Class returnType, Class... params) { + return findMethod(clazz, index, 0, 0, returnType, params); + } + public static Method[] sortMethods(Method[] methods) { Arrays.sort(methods, Comparator.comparing(Method::getName)); return methods; @@ -223,11 +221,6 @@ public class ReflectionUtils { return fields; } - public static Method findMethod(Class clazz, int index, Class returnType, - Class... params) { - return findMethod(clazz, index, 0, 0, returnType, params); - } - public static T setAccessible(T ao) { ao.setAccessible(true); return ao; @@ -270,7 +263,7 @@ public class ReflectionUtils { /** - * get RefClass object by real class + * Get a {@link RefClass} object by its original {@link Class}. * * @param clazz class * @return RefClass based on passed class @@ -280,7 +273,7 @@ public class ReflectionUtils { } /** - * RefClass - utility to simplify work with reflections. + * A utility to simplify work with reflections. */ public static class RefClass { @@ -290,17 +283,12 @@ public class ReflectionUtils { this.clazz = clazz; } - /** - * get passed class - * - * @return class - */ - public Class getRealClass() { + public Class getClazz() { return this.clazz; } /** - * see {@link Class#isInstance(Object)} + * See {@link Class#isInstance(Object)}. * * @param object the object to check * @return true if object is an instance of this class @@ -310,14 +298,15 @@ public class ReflectionUtils { } /** - * get existing method by name and types + * Get an existing method by name and types. The {@code types} parameter accepts both {@link Class} + * and {@link RefClass} objects. * * @param name name - * @param types method parameters. can be Class or RefClass + * @param types method parameters * @return RefMethod object * @throws RuntimeException if method not found */ - public RefMethod getMethod(String name, Object... types) throws NoSuchMethodException { + public RefMethod getMethod(String name, Object... types) { try { final Class[] classes = new Class[types.length]; int i = 0; @@ -325,7 +314,7 @@ public class ReflectionUtils { if (e instanceof Class) { classes[i++] = (Class) e; } else if (e instanceof RefClass) { - classes[i++] = ((RefClass) e).getRealClass(); + classes[i++] = ((RefClass) e).getClazz(); } else { classes[i++] = e.getClass(); } @@ -341,9 +330,10 @@ public class ReflectionUtils { } /** - * get existing constructor by types + * Get an existing constructor by types.The {@code types} parameter accepts both {@link Class} + * and {@link RefClass} objects. * - * @param types parameters. can be Class or RefClass + * @param types parameters * @return RefMethod object * @throws RuntimeException if constructor not found */ @@ -355,7 +345,7 @@ public class ReflectionUtils { if (e instanceof Class) { classes[i++] = (Class) e; } else if (e instanceof RefClass) { - classes[i++] = ((RefClass) e).getRealClass(); + classes[i++] = ((RefClass) e).getClazz(); } else { classes[i++] = e.getClass(); } @@ -371,9 +361,10 @@ public class ReflectionUtils { } /** - * find method by type parameters + * Find a method by type parameters. The {@code types} parameter accepts both {@link Class} + * and {@link RefClass} objects. * - * @param types parameters. can be Class or RefClass + * @param types parameters * @return RefMethod object * @throws RuntimeException if method not found */ @@ -384,7 +375,7 @@ public class ReflectionUtils { if (e instanceof Class) { classes[t++] = (Class) e; } else if (e instanceof RefClass) { - classes[t++] = ((RefClass) e).getRealClass(); + classes[t++] = ((RefClass) e).getClazz(); } else { classes[t++] = e.getClass(); } @@ -409,7 +400,7 @@ public class ReflectionUtils { } /** - * find method by name + * Find a method by name. * * @param names possible names of method * @return RefMethod object @@ -430,7 +421,7 @@ public class ReflectionUtils { } /** - * find method by return value + * Find a method by return value. * * @param type type of returned value * @return RefMethod @@ -441,7 +432,7 @@ public class ReflectionUtils { } /** - * find method by return value + * Find a method by return value. * * @param type type of returned value * @return RefMethod @@ -463,7 +454,7 @@ public class ReflectionUtils { } /** - * find constructor by number of arguments + * Find the constructor by the number of arguments. * * @param number number of arguments * @return RefConstructor @@ -482,7 +473,7 @@ public class ReflectionUtils { } /** - * get field by name + * Get the field by name. * * @param name field name * @return RefField @@ -501,24 +492,24 @@ public class ReflectionUtils { } /** - * find field by type + * Find the field by type. * * @param type field type * @return RefField - * @throws RuntimeException if field not found + * @throws NoSuchFieldException if field not found */ - public RefField findField(RefClass type) { + public RefField findField(RefClass type) throws NoSuchFieldException { return this.findField(type.clazz); } /** - * find field by type + * Find the field by type. * * @param type field type * @return RefField * @throws RuntimeException if field not found */ - public RefField findField(Class type) { + public RefField findField(Class type) throws NoSuchFieldException { if (type == null) { type = void.class; } @@ -530,12 +521,13 @@ public class ReflectionUtils { return new RefField(f); } } - throw new RuntimeException("no such field"); + throw new NoSuchFieldException(); } } + /** - * Method wrapper + * Method reflection wrapper. */ public static class RefMethod { @@ -546,29 +538,20 @@ public class ReflectionUtils { method.setAccessible(true); } - /** - * @return passed method - */ - public Method getRealMethod() { + public Method getMethod() { return this.method; } - /** - * @return owner class of method - */ public RefClass getRefClass() { return new RefClass(this.method.getDeclaringClass()); } - /** - * @return class of method return type - */ public RefClass getReturnRefClass() { return new RefClass(this.method.getReturnType()); } /** - * apply method to object + * Apply method to object. * * @param e object to which the method is applied * @return RefExecutor with method call(...) @@ -578,7 +561,7 @@ public class ReflectionUtils { } /** - * call static method + * Call static method. * * @param params sent parameters * @return return value @@ -593,14 +576,14 @@ public class ReflectionUtils { public class RefExecutor { - final Object e; + final Object executor; - public RefExecutor(Object e) { - this.e = e; + public RefExecutor(Object executor) { + this.executor = executor; } /** - * apply method for selected object + * Invokes the method on the selected object. * * @param params sent parameters * @return return value @@ -608,7 +591,7 @@ public class ReflectionUtils { */ public Object call(Object... params) { try { - return RefMethod.this.method.invoke(this.e, params); + return RefMethod.this.method.invoke(this.executor, params); } catch (Exception e) { throw new RuntimeException(e); } @@ -616,8 +599,9 @@ public class ReflectionUtils { } } + /** - * Constructor wrapper + * Constructor wrapper. */ public static class RefConstructor { @@ -628,22 +612,16 @@ public class ReflectionUtils { constructor.setAccessible(true); } - /** - * @return passed constructor - */ - public Constructor getRealConstructor() { + public Constructor getConstructor() { return this.constructor; } - /** - * @return owner class of method - */ public RefClass getRefClass() { return new RefClass(this.constructor.getDeclaringClass()); } /** - * create new instance with constructor + * Create and initialize a new instance of constructor's declaring class. * * @param params parameters for constructor * @return new object @@ -658,6 +636,7 @@ public class ReflectionUtils { } } + public static class RefField { private final Field field; @@ -667,29 +646,23 @@ public class ReflectionUtils { field.setAccessible(true); } - /** - * @return passed field - */ - public Field getRealField() { + public Field getField() { return this.field; } - /** - * @return owner class of field - */ public RefClass getRefClass() { return new RefClass(this.field.getDeclaringClass()); } /** - * @return type of field + * Returns a wrapper to the class of the field's returning type. */ public RefClass getFieldRefClass() { return new RefClass(this.field.getType()); } /** - * Apply field for object + * Apply the field on object. * * @param e applied object * @return RefExecutor with getter and setter @@ -700,33 +673,33 @@ public class ReflectionUtils { public class RefExecutor { - final Object e; + final Object executor; public RefExecutor(Object e) { - this.e = e; + this.executor = e; } /** - * Set field value for applied object + * Set field value for applied object. * * @param param value */ public void set(Object param) { try { - RefField.this.field.set(this.e, param); + RefField.this.field.set(this.executor, param); } catch (Exception e) { throw new RuntimeException(e); } } /** - * Get field value for the applied object.. + * Get field value for the applied object. * * @return value of field */ public Object get() { try { - return RefField.this.field.get(this.e); + return RefField.this.field.get(this.executor); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/StringMan.java b/worldedit-core/src/main/java/com/boydti/fawe/util/StringMan.java index 47a33911e..c75f34919 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/StringMan.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/StringMan.java @@ -6,6 +6,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.List; +import java.util.Locale; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; @@ -20,8 +21,9 @@ public class StringMan { public static boolean containsIgnoreCase(String haystack, String needle) { final int length = needle.length(); - if (length == 0) + if (length == 0) { return true; // Empty string is contained + } final char firstLo = Character.toLowerCase(needle.charAt(0)); final char firstUp = Character.toUpperCase(needle.charAt(0)); @@ -29,11 +31,13 @@ public class StringMan { for (int i = haystack.length() - length; i >= 0; i--) { // Quick check before calling the more expensive regionMatches() method: final char ch = haystack.charAt(i); - if (ch != firstLo && ch != firstUp) + if (ch != firstLo && ch != firstUp) { continue; + } - if (haystack.regionMatches(true, i, needle, 0, length)) + if (haystack.regionMatches(true, i, needle, 0, length)) { return true; + } } return false; @@ -42,7 +46,9 @@ public class StringMan { public static int findMatchingBracket(CharSequence sequence, int index) { char startC = sequence.charAt(index); char lookC = getMatchingBracket(startC); - if (lookC == startC) return -1; + if (lookC == startC) { + return -1; + } boolean forward = isBracketForwards(startC); int increment = forward ? 1 : -1; int end = forward ? sequence.length() : -1; @@ -70,10 +76,17 @@ public class StringMan { } public static String prettyFormat(double d) { - if (d == Double.MIN_VALUE || d == Double.NEGATIVE_INFINITY) return "-∞"; - if (d == Double.MAX_VALUE || d == Double.POSITIVE_INFINITY) return "∞"; - if(d == (long) d) return String.format("%d",(long)d); - else return String.format("%s",d); + if (d == Double.MIN_VALUE || d == Double.NEGATIVE_INFINITY) { + return "-∞"; + } + if (d == Double.MAX_VALUE || d == Double.POSITIVE_INFINITY) { + return "∞"; + } + if (d == (long) d) { + return String.format("%d", (long) d); + } else { + return String.format("%s", d); + } } public static boolean isBracketForwards(char c) { @@ -140,15 +153,16 @@ public class StringMan { public static int indexOf(String input, int start, char... values) { for (int i = start; i < input.length(); i++) { for (char c : values) { - if (c == input.charAt(i)) return i; + if (c == input.charAt(i)) { + return i; + } } } return -1; } public static String toProperCase(String s) { - return s.substring(0, 1).toUpperCase() + - s.substring(1); + return s.substring(0, 1).toUpperCase(Locale.ROOT) + s.substring(1); } public static List split(String input, char delim) { @@ -160,11 +174,15 @@ public class StringMan { char currentChar = input.charAt(current); boolean atLastChar = current == input.length() - 1; if (!atLastChar && (bracket > 0 || currentChar == '{' && ++bracket > 0 - || current == '}' && --bracket <= 0)) + || current == '}' && --bracket <= 0)) { continue; - if (currentChar == '\"') inQuotes = !inQuotes; // toggle state - if (atLastChar) result.add(input.substring(start)); - else if (currentChar == delim && !inQuotes) { + } + if (currentChar == '\"') { + inQuotes = !inQuotes; // toggle state + } + if (atLastChar) { + result.add(input.substring(start)); + } else if (currentChar == delim && !inQuotes) { String toAdd = input.substring(start, current); if (toAdd.startsWith("\"")) { toAdd = toAdd.substring(1, toAdd.length() - 1); @@ -339,7 +357,9 @@ public class StringMan { char ai = input.charAt(i); outer: while (true) { - if (j >= item.length()) return Integer.MAX_VALUE; + if (j >= item.length()) { + return Integer.MAX_VALUE; + } char bj = item.charAt(j++); if (sequentail) { @@ -347,7 +367,9 @@ public class StringMan { case ':': case '_': sequentail = false; - if (bj == ai) break outer; + if (bj == ai) { + break outer; + } continue; } continue; @@ -447,8 +469,9 @@ public class StringMan { if (char0 == '-') { negative = true; start++; + } else { + negative = false; } - else negative = false; for (int i = start; i < end; i++) { char c = string.charAt(i); switch (c) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/TaskManager.java b/worldedit-core/src/main/java/com/boydti/fawe/util/TaskManager.java index 9ab14751c..cad8fc63f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/TaskManager.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/TaskManager.java @@ -297,7 +297,7 @@ public abstract class TaskManager { throw new RuntimeException(e); } } - + /** * Run a task on the main thread when the TPS is high enough, and wait for execution to finish. * - Useful if you need to access something from the Bukkit API from another thread
diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/TextureUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/TextureUtil.java index 1cd7af233..1c961db99 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/TextureUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/TextureUtil.java @@ -333,7 +333,8 @@ public class TextureUtil implements TextureHolder { new BiomeColor(252, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), new BiomeColor(253, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), new BiomeColor(254, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(255, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F),}; + new BiomeColor(255, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F) + }; private BlockType[] layerBuffer = new BlockType[2]; public TextureUtil() throws FileNotFoundException { @@ -458,10 +459,7 @@ public class TextureUtil implements TextureHolder { } /** - * Returns the block combined ids as an array - * - * @param color - * @return + * Returns the block combined ids as an array. */ public BlockType[] getNearestLayer(int color) { int[] closest = null; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/WEManager.java b/worldedit-core/src/main/java/com/boydti/fawe/util/WEManager.java index 10f821331..eeba5e412 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/WEManager.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/WEManager.java @@ -26,7 +26,7 @@ public class WEManager { private static final Logger log = LoggerFactory.getLogger(WEManager.class); - public final static WEManager IMP = new WEManager(); + public static final WEManager IMP = new WEManager(); public final ArrayDeque managers = new ArrayDeque<>(); @@ -53,10 +53,7 @@ public class WEManager { } /** - * Get a player's mask - * - * @param player - * @return + * Get a player's mask. */ public Region[] getMask(Player player, FaweMaskManager.MaskType type) { if (!Settings.IMP.REGION_RESTRICTIONS || player.hasPermission("fawe.bypass") || player.hasPermission("fawe.bypass.regions")) { @@ -98,7 +95,9 @@ public class WEManager { } } } - if (!removed) return regions.toArray(new Region[0]); + if (!removed) { + return regions.toArray(new Region[0]); + } masks.clear(); } } @@ -106,12 +105,16 @@ public class WEManager { for (FaweMaskManager manager : managers) { if (player.hasPermission("fawe." + manager.getKey())) { try { - if (manager.isExclusive() && !masks.isEmpty()) continue; + if (manager.isExclusive() && !masks.isEmpty()) { + continue; + } final FaweMask mask = manager.getMask(player, FaweMaskManager.MaskType.getDefaultMaskType()); if (mask != null) { regions.add(mask.getRegion()); masks.add(mask); - if (manager.isExclusive()) break; + if (manager.isExclusive()) { + break; + } } } catch (Throwable e) { e.printStackTrace(); @@ -139,9 +142,8 @@ public class WEManager { BlockVector3 rg2P1 = region2.getMinimumPoint(); BlockVector3 rg2P2 = region2.getMaximumPoint(); - return rg1P1.getBlockX() <= rg2P2.getBlockX() && rg1P2.getBlockX() >= rg2P1.getBlockX() && - rg1P1.getBlockZ() <= rg2P2.getBlockZ() && - rg1P2.getBlockZ() >= rg2P1.getBlockZ(); + return rg1P1.getBlockX() <= rg2P2.getBlockX() && rg1P2.getBlockX() >= rg2P1.getBlockX() + && rg1P1.getBlockZ() <= rg2P2.getBlockZ() && rg1P2.getBlockZ() >= rg2P1.getBlockZ(); } public boolean regionContains(Region selection, HashSet mask) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/image/ImageUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/image/ImageUtil.java index 0a67f42cf..390e701d0 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/image/ImageUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/image/ImageUtil.java @@ -31,7 +31,8 @@ public class ImageUtil { int type = image.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage scaledImage = image; - int width, height; + int width; + int height; if (higherQuality) { /* Use multi-step technique: start with original size, then scale down in multiple passes with drawImage() diff --git a/worldedit-core/src/main/java/com/boydti/fawe/web/SchemSync.java b/worldedit-core/src/main/java/com/boydti/fawe/web/SchemSync.java index e4e35b203..2f0467306 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/web/SchemSync.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/web/SchemSync.java @@ -23,7 +23,7 @@ import java.util.UUID; public class SchemSync implements Runnable { - private final static char PORT = 62522; + private static final char PORT = 62522; private final File tokensFile; private final WorldEdit worldEdit; @@ -37,8 +37,7 @@ public class SchemSync implements Runnable { INVALID_HEADER_LENGTH, TOKEN_REJECTED, FILE_NOT_EXIST, - NO_FILE_PERMISSIONS, - ; + NO_FILE_PERMISSIONS; } @@ -116,11 +115,13 @@ public class SchemSync implements Runnable { if (!file.exists()) { close(Error.FILE_NOT_EXIST); } - + break; + default: + break; // todo send file } } - } catch (FaweException ignore) { + } catch (FaweException ignored) { } } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/wrappers/WorldWrapper.java b/worldedit-core/src/main/java/com/boydti/fawe/wrappers/WorldWrapper.java index f2120a5ae..1a8100ec0 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/wrappers/WorldWrapper.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/wrappers/WorldWrapper.java @@ -45,6 +45,10 @@ public class WorldWrapper extends AbstractWorld { private final World parent; + private WorldWrapper(World parent) { + this.parent = parent; + } + public static WorldWrapper wrap(World world) { if (world == null) { return null; @@ -58,8 +62,7 @@ public class WorldWrapper extends AbstractWorld { public static World unwrap(World world) { if (world instanceof WorldWrapper) { return unwrap(((WorldWrapper) world).getParent()); - } - else if (world instanceof EditSession) { + } else if (world instanceof EditSession) { return unwrap(((EditSession) world).getWorld()); } return world; @@ -77,10 +80,6 @@ public class WorldWrapper extends AbstractWorld { return null; } - private WorldWrapper(World parent) { - this.parent = parent; - } - public World getParent() { return parent instanceof WorldWrapper ? ((WorldWrapper) parent).getParent() : parent; } @@ -90,33 +89,6 @@ public class WorldWrapper extends AbstractWorld { return parent.useItem(position, item, face); } - @Override - public Set applySideEffects(BlockVector3 position, BlockState previousType, SideEffectSet sideEffectSet) - throws WorldEditException{ - return parent.applySideEffects(position, previousType, sideEffectSet); - } - - @Override - public > boolean setBlock(BlockVector3 position, B block, boolean notifyAndLight) throws WorldEditException { - return parent.setBlock(position, block, notifyAndLight); - } - - @Override - public > boolean setBlock(int x, int y, int z, T block) - throws WorldEditException { - return parent.setBlock(x, y, z, block); - } - - @Override - public > boolean setBlock(BlockVector3 position, B block, SideEffectSet sideEffects) throws WorldEditException { - return parent.setBlock(position, block, sideEffects); - } - - @Override - public boolean setTile(int x, int y, int z, CompoundTag tile) throws WorldEditException { - return parent.setTile(x, y, z, tile); - } - @Override public int getMaxY() { return parent.getMaxY(); @@ -132,27 +104,6 @@ public class WorldWrapper extends AbstractWorld { parent.dropItem(pt, item, times); } - @Override - public void simulateBlockMine(BlockVector3 pt) { - TaskManager.IMP.sync(new RunnableVal() { - @Override - public void run(Object value) { - parent.simulateBlockMine(pt); - } - }); - } - - @Override - public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) throws MaxChangedBlocksException { - return TaskManager.IMP.sync(() -> { - try { - return parent.generateTree(type, editSession, position); - } catch (MaxChangedBlocksException e) { - throw new RuntimeException(e); - } - }); - } - @Override public void checkLoadedChunk(BlockVector3 pt) { parent.checkLoadedChunk(pt); @@ -178,6 +129,22 @@ public class WorldWrapper extends AbstractWorld { return parent.queueBlockBreakEffect(server, position, blockType, priority); } + @Override + public BlockVector3 getMinimumPoint() { + return parent.getMinimumPoint(); + } + + @Override + public BlockVector3 getMaximumPoint() { + return parent.getMaximumPoint(); + } + + @Override + @Nullable + public Operation commit() { + return parent.commit(); + } + @Override public WeatherType getWeather() { return null; @@ -199,19 +166,24 @@ public class WorldWrapper extends AbstractWorld { } @Override - public BlockVector3 getMinimumPoint() { - return parent.getMinimumPoint(); + public > boolean setBlock(int x, int y, int z, T block) + throws WorldEditException { + return parent.setBlock(x, y, z, block); } @Override - public BlockVector3 getMaximumPoint() { - return parent.getMaximumPoint(); + public boolean setTile(int x, int y, int z, CompoundTag tile) throws WorldEditException { + return parent.setTile(x, y, z, tile); } @Override - @Nullable - public Operation commit() { - return parent.commit(); + public boolean setBiome(int x, int y, int z, BiomeType biome) { + return parent.setBiome(x, y, z, biome); + } + + @Override + public boolean setBiome(BlockVector3 position, BiomeType biome) { + return parent.setBiome(position, biome); } @Override @@ -219,6 +191,27 @@ public class WorldWrapper extends AbstractWorld { return parent.getName(); } + @Override + public > boolean setBlock(BlockVector3 position, B block, boolean notifyAndLight) throws WorldEditException { + return parent.setBlock(position, block, notifyAndLight); + } + + @Override + public > boolean setBlock(BlockVector3 position, B block, SideEffectSet sideEffects) throws WorldEditException { + return parent.setBlock(position, block, sideEffects); + } + + @Override + public boolean notifyAndLightBlock(BlockVector3 position, BlockState previousType) throws WorldEditException { + return parent.notifyAndLightBlock(position, previousType); + } + + @Override + public Set applySideEffects(BlockVector3 position, BlockState previousType, SideEffectSet sideEffectSet) + throws WorldEditException { + return parent.applySideEffects(position, previousType, sideEffectSet); + } + @Override public int getBlockLightLevel(BlockVector3 position) { return parent.getBlockLightLevel(position); @@ -234,14 +227,50 @@ public class WorldWrapper extends AbstractWorld { parent.dropItem(position, item); } + @Override + public void simulateBlockMine(BlockVector3 pt) { + TaskManager.IMP.sync(new RunnableVal() { + @Override + public void run(Object value) { + parent.simulateBlockMine(pt); + } + }); + } + @Override public boolean regenerate(Region region, EditSession session) { return parent.regenerate(region, session); } @Override - public boolean equals(Object other) { - return parent.equals(other); + public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) throws MaxChangedBlocksException { + return TaskManager.IMP.sync(() -> { + try { + return parent.generateTree(type, editSession, position); + } catch (MaxChangedBlocksException e) { + throw new RuntimeException(e); + } + }); + } + + @Override + public BlockVector3 getSpawnPosition() { + return parent.getSpawnPosition(); + } + + @Override + public void refreshChunk(int chunkX, int chunkZ) { + parent.refreshChunk(chunkX, chunkZ); + } + + @Override + public IChunkGet get(int x, int z) { + return parent.get(x, z); + } + + @Override + public void sendFakeChunk(@Nullable Player player, ChunkPacket packet) { + parent.sendFakeChunk(player, packet); } @Override @@ -250,8 +279,8 @@ public class WorldWrapper extends AbstractWorld { } @Override - public void refreshChunk(int X, int Z) { - parent.refreshChunk(X, Z); + public boolean equals(Object other) { + return parent.equals(other); } @Override @@ -284,34 +313,4 @@ public class WorldWrapper extends AbstractWorld { public BiomeType getBiome(BlockVector3 position) { return parent.getBiome(position); } - - @Override - public boolean setBiome(BlockVector3 position, BiomeType biome) { - return parent.setBiome(position, biome); - } - - @Override - public boolean setBiome(int x, int y, int z, BiomeType biome) { - return parent.setBiome(x, y, z, biome); - } - - @Override - public boolean notifyAndLightBlock(BlockVector3 position, BlockState previousType) throws WorldEditException { - return parent.notifyAndLightBlock(position, previousType); - } - - @Override - public BlockVector3 getSpawnPosition() { - return parent.getSpawnPosition(); - } - - @Override - public IChunkGet get(int x, int z) { - return parent.get(x, z); - } - - @Override - public void sendFakeChunk(@Nullable Player player, ChunkPacket packet) { - parent.sendFakeChunk(player, packet); - } } diff --git a/worldedit-core/src/main/java/com/sk89q/jnbt/CompoundTag.java b/worldedit-core/src/main/java/com/sk89q/jnbt/CompoundTag.java index dd9eee87f..82754e61a 100644 --- a/worldedit-core/src/main/java/com/sk89q/jnbt/CompoundTag.java +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/CompoundTag.java @@ -390,7 +390,9 @@ public class CompoundTag extends Tag { @Override public Map toRaw() { HashMap raw = new HashMap<>(); - if (this.getValue().isEmpty()) return raw; + if (this.getValue().isEmpty()) { + return raw; + } for (Map.Entry entry : getValue().entrySet()) { raw.put(entry.getKey(), entry.getValue().toRaw()); } diff --git a/worldedit-core/src/main/java/com/sk89q/jnbt/CompressedCompoundTag.java b/worldedit-core/src/main/java/com/sk89q/jnbt/CompressedCompoundTag.java index 3a661b437..ca9241ccb 100644 --- a/worldedit-core/src/main/java/com/sk89q/jnbt/CompressedCompoundTag.java +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/CompressedCompoundTag.java @@ -16,7 +16,9 @@ public abstract class CompressedCompoundTag extends CompoundTag { @Override public Map getValue() { - if (in != null) decompress(); + if (in != null) { + decompress(); + } return super.getValue(); } diff --git a/worldedit-core/src/main/java/com/sk89q/jnbt/NBTInputStream.java b/worldedit-core/src/main/java/com/sk89q/jnbt/NBTInputStream.java index f399e7ff6..c2282e9fc 100644 --- a/worldedit-core/src/main/java/com/sk89q/jnbt/NBTInputStream.java +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/NBTInputStream.java @@ -187,7 +187,9 @@ public final class NBTInputStream implements Closeable { return; case NBTConstants.TYPE_BYTE: { ValueReader value = scope.getValueReader(); - if (value == null) value = scope.getElemReader(); + if (value == null) { + value = scope.getElemReader(); + } if (value != null) { value.applyInt(0, is.readByte()); } else { @@ -197,7 +199,9 @@ public final class NBTInputStream implements Closeable { } case NBTConstants.TYPE_SHORT: { ValueReader value = scope.getValueReader(); - if (value == null) value = scope.getElemReader(); + if (value == null) { + value = scope.getElemReader(); + } if (value != null) { value.applyInt(0, is.readShort()); } else { @@ -207,7 +211,9 @@ public final class NBTInputStream implements Closeable { } case NBTConstants.TYPE_INT: { ValueReader value = scope.getValueReader(); - if (value == null) value = scope.getElemReader(); + if (value == null) { + value = scope.getElemReader(); + } if (value != null) { value.applyInt(0, is.readInt()); } else { @@ -217,7 +223,9 @@ public final class NBTInputStream implements Closeable { } case NBTConstants.TYPE_LONG: { ValueReader value = scope.getValueReader(); - if (value == null) value = scope.getElemReader(); + if (value == null) { + value = scope.getElemReader(); + } if (value != null) { value.applyLong(0, is.readLong()); } else { @@ -227,7 +235,9 @@ public final class NBTInputStream implements Closeable { } case NBTConstants.TYPE_FLOAT: { ValueReader value = scope.getValueReader(); - if (value == null) value = scope.getElemReader(); + if (value == null) { + value = scope.getElemReader(); + } if (value != null) { value.applyFloat(0, is.readFloat()); } else { @@ -237,7 +247,9 @@ public final class NBTInputStream implements Closeable { } case NBTConstants.TYPE_DOUBLE: { ValueReader value = scope.getValueReader(); - if (value == null) value = scope.getElemReader(); + if (value == null) { + value = scope.getElemReader(); + } if (value != null) { value.applyDouble(0, is.readDouble()); } else { @@ -247,7 +259,9 @@ public final class NBTInputStream implements Closeable { } case NBTConstants.TYPE_STRING: { ValueReader value = scope.getValueReader(); - if (value == null) value = scope.getElemReader(); + if (value == null) { + value = scope.getElemReader(); + } int length = is.readShort() & 0xFFFF; if (value != null) { byte[] bytes = new byte[length]; @@ -325,7 +339,9 @@ public final class NBTInputStream implements Closeable { case NBTConstants.TYPE_BYTE_ARRAY: { int length = is.readInt(); scope.acceptInfo(length, NBTConstants.TYPE_BYTE); - if (scope.acceptLazy(length, this)) return; + if (scope.acceptLazy(length, this)) { + return; + } ValueReader valueReader = scope.getValueReader(); if (valueReader != null) { byte[] arr = new byte[length]; @@ -360,7 +376,9 @@ public final class NBTInputStream implements Closeable { case NBTConstants.TYPE_INT_ARRAY: { int length = is.readInt(); scope.acceptInfo(length, NBTConstants.TYPE_INT); - if (scope.acceptLazy(length, this)) return; + if (scope.acceptLazy(length, this)) { + return; + } ValueReader valueReader = scope.getValueReader(); if (valueReader != null) { valueReader.apply(0, readIntArrayRaw(length)); @@ -379,7 +397,9 @@ public final class NBTInputStream implements Closeable { case NBTConstants.TYPE_LONG_ARRAY: { int length = is.readInt(); scope.acceptInfo(length, NBTConstants.TYPE_LONG); - if (scope.acceptLazy(length, this)) return; + if (scope.acceptLazy(length, this)) { + return; + } ValueReader valueReader = scope.getValueReader(); if (valueReader != null) { valueReader.apply(0, readLongArrayRaw(length)); diff --git a/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/CommandContext.java b/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/CommandContext.java index 66c476908..c95356a91 100644 --- a/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/CommandContext.java +++ b/worldedit-core/src/main/java/com/sk89q/minecraft/util/commands/CommandContext.java @@ -126,7 +126,9 @@ public class CommandContext { for (endIndex = i; endIndex < args.length; ++endIndex) { final String arg2 = args[endIndex]; if (arg2.charAt(arg2.length() - 1) == quotedChar && arg2.length() > 1) { - if (endIndex != i) build.append(' '); + if (endIndex != i) { + build.append(' '); + } build.append(arg2.substring(endIndex == i ? 1 : 0, arg2.length() - 1)); break; } else if (endIndex == i) { diff --git a/worldedit-core/src/main/java/com/sk89q/util/ReflectionUtil.java b/worldedit-core/src/main/java/com/sk89q/util/ReflectionUtil.java index fec54166f..15a7c6cb9 100644 --- a/worldedit-core/src/main/java/com/sk89q/util/ReflectionUtil.java +++ b/worldedit-core/src/main/java/com/sk89q/util/ReflectionUtil.java @@ -28,10 +28,11 @@ public final class ReflectionUtil { @SuppressWarnings("unchecked") public static T getField(Object from, String name) { - if (from instanceof Class) + if (from instanceof Class) { return getField((Class) from, null, name); - else + } else { return getField(from.getClass(), from, name); + } } @SuppressWarnings("unchecked") diff --git a/worldedit-core/src/main/java/com/sk89q/util/StringUtil.java b/worldedit-core/src/main/java/com/sk89q/util/StringUtil.java index 9f570e521..f7b4bedaf 100644 --- a/worldedit-core/src/main/java/com/sk89q/util/StringUtil.java +++ b/worldedit-core/src/main/java/com/sk89q/util/StringUtil.java @@ -258,8 +258,7 @@ public final class StringUtil { for (i = 1; i <= n; ++i) { cost = s.charAt(i - 1) == tj ? 0 : 1; - // minimum of cell to the left+1, to the top+1, diagonally left - // and up +cost + // minimum of cell to the left+1, to the top+1, diagonally left and up +cost d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost); } diff --git a/worldedit-core/src/main/java/com/sk89q/util/yaml/YAMLNode.java b/worldedit-core/src/main/java/com/sk89q/util/yaml/YAMLNode.java index 154b71c8f..78171ef3a 100644 --- a/worldedit-core/src/main/java/com/sk89q/util/yaml/YAMLNode.java +++ b/worldedit-core/src/main/java/com/sk89q/util/yaml/YAMLNode.java @@ -43,6 +43,57 @@ public class YAMLNode { this.writeDefaults = writeDefaults; } + /** + * Casts a value to an integer. May return null. + * + * @param o the object + * @return an integer or null + */ + @Nullable + private static Integer castInt(Object o) { + if (o == null) { + return null; + } else if (o instanceof Number) { + return ((Number) o).intValue(); + } else { + return null; + } + } + + /** + * Casts a value to a double. May return null. + * + * @param o the object + * @return a double or null + */ + @Nullable + private static Double castDouble(Object o) { + if (o == null) { + return null; + } else if (o instanceof Number) { + return ((Number) o).doubleValue(); + } else { + return null; + } + } + + /** + * Casts a value to a boolean. May return null. + * + * @param o the object + * @return a boolean or null + */ + @Nullable + private static Boolean castBoolean(Object o) { + if (o == null) { + return null; + } else if (o instanceof Boolean) { + return (Boolean) o; + } else { + return null; + } + } + /** * Return the underlying map. * @@ -262,8 +313,8 @@ public class YAMLNode { } /** - * Gets a string at a location. This will either return a Vector - * or the default value. If the object at the particular location is not + * Gets a string at a location. This will either return a Vector, or + * the default value. If the object at the particular location is not * actually a string, it will be converted to its string representation. * * @param path path to node (dot notation) @@ -282,8 +333,8 @@ public class YAMLNode { } /** - * Gets a string at a location. This will either return a String - * or the default value. If the object at the particular location is not + * Gets a string at a location. This will either return a String, or + * the default value. If the object at the particular location is not * actually a string, it will be converted to its string representation. * * @param path path to node (dot notation) @@ -302,13 +353,13 @@ public class YAMLNode { } /** - * Gets an integer at a location. This will either return an integer - * or null. If the object at the particular location is not - * actually a integer, the default value will be returned. However, other - * number types will be casted to an integer. + * Gets an integer at a location. This will either return an Integer, or + * null. If the object at the particular location is not + * actually an Integer, the default value will be returned. However, other + * number types will be casted to an Integer. * * @param path path to node (dot notation) - * @return integer or null + * @return Integer or null */ public Integer getInt(String path) { Integer o = castInt(getProperty(path)); @@ -320,14 +371,14 @@ public class YAMLNode { } /** - * Gets an integer at a location. This will either return an integer - * or the default value. If the object at the particular location is not - * actually a integer, the default value will be returned. However, other + * Gets an integer at a location. This will either return an Integer, or + * the default value. If the object at the particular location is not + * actually an Integer, the default value will be returned. However, other * number types will be casted to an integer. * * @param path path to node (dot notation) * @param def default value - * @return int or default + * @return Integer or default */ public int getInt(String path, int def) { Integer o = castInt(getProperty(path)); @@ -342,13 +393,13 @@ public class YAMLNode { } /** - * Gets a double at a location. This will either return a double - * or null. If the object at the particular location is not - * actually a double, the default value will be returned. However, other - * number types will be casted to a double. + * Gets a double at a location. This will either return a Double, or + * null. If the object at the particular location is not + * actually a Double, the default value will be returned. However, other + * number types will be casted to a Double. * * @param path path to node (dot notation) - * @return double or null + * @return Double or null */ public Double getDouble(String path) { Double o = castDouble(getProperty(path)); @@ -360,14 +411,14 @@ public class YAMLNode { } /** - * Gets a double at a location. This will either return a double - * or the default value. If the object at the particular location is not - * actually a double, the default value will be returned. However, other - * number types will be casted to a double. + * Gets a double at a location. This will either return a Double, or + * the default value. If the object at the particular location is not + * actually a Double, the default value will be returned. However, other + * number types will be casted to a Double. * * @param path path to node (dot notation) * @param def default value - * @return double or default + * @return Double or default */ public double getDouble(String path, double def) { Double o = castDouble(getProperty(path)); @@ -382,12 +433,12 @@ public class YAMLNode { } /** - * Gets a boolean at a location. This will either return a boolean - * or null. If the object at the particular location is not - * actually a boolean, the default value will be returned. + * Gets a Boolean at a location. This will either return a Boolean, or + * null. If the object at the particular location is not + * actually a Boolean, the default value will be returned. * * @param path path to node (dot notation) - * @return boolean or null + * @return Boolean or null */ public Boolean getBoolean(String path) { Boolean o = castBoolean(getProperty(path)); @@ -399,13 +450,13 @@ public class YAMLNode { } /** - * Gets a boolean at a location. This will either return a boolean - * or the default value. If the object at the particular location is not - * actually a boolean, the default value will be returned. + * Gets a Boolean at a location. This will either return a Boolean, or + * the default value. If the object at the particular location is not + * actually a Boolean, the default value will be returned. * * @param path path to node (dot notation) * @param def default value - * @return boolean or default + * @return Boolean or default */ public boolean getBoolean(String path, boolean def) { Boolean o = castBoolean(getProperty(path)); @@ -421,7 +472,7 @@ public class YAMLNode { /** * Get a list of keys at a location. If the map at the particular location - * does not exist or it is not a map, null will be returned. + * does not exist, or it is not a map, null will be returned. * * @param path path to node (dot notation) * @return list of keys @@ -461,16 +512,16 @@ public class YAMLNode { } /** - * Gets a list of strings. Non-valid entries will not be in the list. + * Gets a list of Strings. Non-valid entries will not be in the list. * There will be no null slots. If the list is not defined, the - * default will be returned. 'null' can be passed for the default - * and an empty list will be returned instead. If an item in the list - * is not a string, it will be converted to a string. The node must be - * an actual list and not just a string. + * default will be returned. 'null' can be passed for the default, and + * an empty list will be returned instead. If an item in the list + * is not a String, it will be converted to a string. The node must be + * an actual list and not just a String. * * @param path path to node (dot notation) * @param def default value or null for an empty list as default - * @return list of strings + * @return list of Strings */ public List getStringList(String path, List def) { List raw = getList(path); @@ -496,13 +547,13 @@ public class YAMLNode { /** * Gets a list of integers. Non-valid entries will not be in the list. * There will be no null slots. If the list is not defined, the - * default will be returned. 'null' can be passed for the default - * and an empty list will be returned instead. The node must be + * default will be returned. 'null' can be passed for the default, and + * an empty list will be returned instead. The node must be * an actual list and not just an integer. * * @param path path to node (dot notation) * @param def default value or null for an empty list as default - * @return list of integers + * @return list of Integers */ public List getIntList(String path, List def) { List raw = getList(path); @@ -525,15 +576,15 @@ public class YAMLNode { } /** - * Gets a list of doubles. Non-valid entries will not be in the list. + * Gets a list of Doubles. Non-valid entries will not be in the list. * There will be no null slots. If the list is not defined, the - * default will be returned. 'null' can be passed for the default - * and an empty list will be returned instead. The node must be - * an actual list and cannot be just a double. + * default will be returned. 'null' can be passed for the default, and + * an empty list will be returned instead. The node must be + * an actual list and cannot be just a Double. * * @param path path to node (dot notation) * @param def default value or null for an empty list as default - * @return list of integers + * @return list of Doubles */ public List getDoubleList(String path, List def) { List raw = getList(path); @@ -556,15 +607,15 @@ public class YAMLNode { } /** - * Gets a list of booleans. Non-valid entries will not be in the list. + * Gets a list of Booleans. Non-valid entries will not be in the list. * There will be no null slots. If the list is not defined, the - * default will be returned. 'null' can be passed for the default - * and an empty list will be returned instead. The node must be - * an actual list and cannot be just a boolean, + * default will be returned. 'null' can be passed for the default, and + * an empty list will be returned instead. The node must be + * an actual list and cannot be just a Boolean. * * @param path path to node (dot notation) * @param def default value or null for an empty list as default - * @return list of integers + * @return list of Booleans */ public List getBooleanList(String path, List def) { List raw = getList(path); @@ -589,13 +640,13 @@ public class YAMLNode { /** * Gets a list of vectors. Non-valid entries will not be in the list. * There will be no null slots. If the list is not defined, the - * default will be returned. 'null' can be passed for the default - * and an empty list will be returned instead. The node must be - * an actual node and cannot be just a vector, + * default will be returned. 'null' can be passed for the default, and + * an empty list will be returned instead. The node must be + * an actual node and cannot be just a vector. * * @param path path to node (dot notation) * @param def default value or null for an empty list as default - * @return list of integers + * @return list of vectors */ public List getVectorList(String path, List def) { List raw = getNodeList(path, null); @@ -619,13 +670,13 @@ public class YAMLNode { /** * Gets a list of 2D vectors. Non-valid entries will not be in the list. * There will be no null slots. If the list is not defined, the - * default will be returned. 'null' can be passed for the default - * and an empty list will be returned instead. The node must be - * an actual node and cannot be just a vector, + * default will be returned. 'null' can be passed for the default, and + * an empty list will be returned instead. The node must be + * an actual node and cannot be just a vector. * * @param path path to node (dot notation) * @param def default value or null for an empty list as default - * @return list of integers + * @return list of vectors */ public List getVector2List(String path, List def) { @@ -649,13 +700,13 @@ public class YAMLNode { /** * Gets a list of 2D vectors. Non-valid entries will not be in the list. * There will be no null slots. If the list is not defined, the - * default will be returned. 'null' can be passed for the default - * and an empty list will be returned instead. The node must be - * an actual node and cannot be just a vector, + * default will be returned. 'null' can be passed for the default, and + * an empty list will be returned instead. The node must be + * an actual node and cannot be just a vector. * * @param path path to node (dot notation) * @param def default value or null for an empty list as default - * @return list of integers + * @return list of vectors */ public List getBlockVector2List(String path, List def) { @@ -679,13 +730,13 @@ public class YAMLNode { /** * Gets a list of nodes. Non-valid entries will not be in the list. * There will be no null slots. If the list is not defined, the - * default will be returned. 'null' can be passed for the default - * and an empty list will be returned instead. The node must be - * an actual node and cannot be just a boolean, + * default will be returned. 'null' can be passed for the default, and + * an empty list will be returned instead. The node must be + * an actual node and cannot be just a {@code YAMLNode}. * * @param path path to node (dot notation) * @param def default value or null for an empty list as default - * @return list of integers + * @return list of nodes */ @SuppressWarnings("unchecked") public List getNodeList(String path, List def) { @@ -708,7 +759,7 @@ public class YAMLNode { } /** - * Get a configuration node at a path. If the node doesn't exist or the + * Get a configuration node at a path. If the node doesn't exist, or the * path does not lead to a node, null will be returned. A node has * key/value mappings. * @@ -728,7 +779,7 @@ public class YAMLNode { /** * Get a list of nodes at a location. If the map at the particular location - * does not exist or it is not a map, null will be returned. + * does not exist, or it is not a map, null will be returned. * * @param path path to node (dot notation) * @return map of nodes @@ -755,57 +806,6 @@ public class YAMLNode { } } - /** - * Casts a value to an integer. May return null. - * - * @param o the object - * @return an integer or null - */ - @Nullable - private static Integer castInt(Object o) { - if (o == null) { - return null; - } else if (o instanceof Number) { - return ((Number) o).intValue(); - } else { - return null; - } - } - - /** - * Casts a value to a double. May return null. - * - * @param o the object - * @return a double or null - */ - @Nullable - private static Double castDouble(Object o) { - if (o == null) { - return null; - } else if (o instanceof Number) { - return ((Number) o).doubleValue(); - } else { - return null; - } - } - - /** - * Casts a value to a boolean. May return null. - * - * @param o the object - * @return a boolean or null - */ - @Nullable - private static Boolean castBoolean(Object o) { - if (o == null) { - return null; - } else if (o instanceof Boolean) { - return (Boolean) o; - } else { - return null; - } - } - /** * Remove the property at a location. This will override existing * configuration data to have it conform to key/value mappings. 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 66042e6d6..15325cd47 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java @@ -176,12 +176,13 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } /** - * Reorder mode for {@link EditSession#setReorderMode(ReorderMode)}. - * NOT FUNCTIONAL IN FAWE AS OF June 3,2019 + * Reorder mode for {@link EditSession#setReorderMode(ReorderMode)}. NOT FUNCTIONAL IN FAWE * + *

* 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"), @@ -256,7 +257,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } /** - * The limit for this specific edit (blocks etc) + * The limit for this specific edit (blocks etc). * * @return The limit */ @@ -273,7 +274,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } /** - * Returns a new limit representing how much of this edit's limit has been used so far + * Returns a new limit representing how much of this edit's limit has been used so far. * * @return Limit remaining */ @@ -291,7 +292,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } /** - * Returns the remaining limits + * Returns the remaining limits. * * @return remaining limits */ @@ -300,7 +301,8 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } /** - * The region extent restricts block placements to allowmaxYed regions + * The region extent restricts block placements to allow max Y regions. + * TODO This doc needs to be rewritten because it may not actually describe what it does. * * @return FaweRegionExtent (may be null) */ @@ -312,6 +314,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { public Extent getBypassAll() { return bypassAll; } + public Extent getBypassHistory() { return bypassHistory; } @@ -321,7 +324,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } /** - * Get the Player or null + * Get the Player or null. * * @return the player */ @@ -436,9 +439,9 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } /** - * Queue certain types of block for better reproduction of those blocks. + * Queue certain types of block for better reproduction of those blocks. Uses + * {@link ReorderMode#MULTI_STAGE}. * - * Uses {@link ReorderMode#MULTI_STAGE} * @deprecated Use {@link EditSession#setReorderMode(ReorderMode)} with MULTI_STAGE instead. */ @Deprecated @@ -480,7 +483,8 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { new ExtentTraverser(this).setNext(transform); } - public @Nullable ResettableExtent getTransform() { + @Nullable + public ResettableExtent getTransform() { ExtentTraverser traverser = new ExtentTraverser<>(getExtent()).find(ResettableExtent.class); if (traverser != null) { return traverser.get(); @@ -710,8 +714,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } /** - * Enable or disable chunk batching. Disabling will - * {@linkplain #flushSession() flush the session}. + * Enable or disable chunk batching. Disabling will flush the session. * * @param batchingChunks {@code true} to enable, {@code false} to disable */ @@ -895,7 +898,8 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } } - @Override @Deprecated + @Override + @Deprecated public > boolean setBlock(BlockVector3 position, B block) throws MaxChangedBlocksException { if (position.getBlockY() < 0 || position.getBlockY() > 255) { return false; @@ -971,6 +975,16 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } } + @Override + public > int setBlocks(Region region, B block) throws MaxChangedBlocksException { + return this.changes = super.setBlocks(region, block); + } + + @Override + public int setBlocks(Region region, Pattern pattern) throws MaxChangedBlocksException { + return this.changes = super.setBlocks(region, pattern); + } + /** * Restores all blocks to their initial state. * @@ -1023,7 +1037,8 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } /** - * Closing an EditSession {@linkplain #flushSession() flushes its buffers}. + * Closing an EditSession flushes its buffers to the world, and performs other + * cleanup tasks. */ @Override public void close() { @@ -1033,7 +1048,10 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { /** * Communicate to the EditSession that all block changes are complete, * and that it should apply them to the world. + * + * @deprecated Replace with {@link #close()} for proper cleanup behavior. */ + @Deprecated public void flushSession() { flushQueue(); } @@ -1048,7 +1066,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { if (used.MAX_FAILS > 0) { if (used.MAX_CHANGES > 0 || used.MAX_ENTITIES > 0) { player.print(Caption.of("fawe.error.worldedit.some.fails", used.MAX_FAILS)); - } else if (new ExtentTraverser<>(getExtent()).findAndGet(FaweRegionExtent.class) != null){ + } else if (new ExtentTraverser<>(getExtent()).findAndGet(FaweRegionExtent.class) != null) { player.printError(TranslatableComponent.of("fawe.cancel.worldedit.cancel.reason.outside.region")); } else { player.printError(TranslatableComponent.of("fawe.cancel.worldedit.cancel.reason.outside.level")); @@ -1096,21 +1114,11 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } } return true; - }); + }); Operations.completeBlindly(visitor); return this.changes; } - @Override - public > int setBlocks(Region region, B block) throws MaxChangedBlocksException { - return this.changes = super.setBlocks(region, block); - } - - @Override - public int setBlocks(Region region, Pattern pattern) throws MaxChangedBlocksException { - return this.changes = super.setBlocks(region, pattern); - } - @Override public > int replaceBlocks(Region region, Set filter, B replacement) throws MaxChangedBlocksException { return this.changes = super.replaceBlocks(region, filter, replacement); @@ -1198,6 +1206,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { Math.max(origin.getBlockY() - depth + 1, getMinimumPoint().getBlockY()), Math.min(getMaxY(), origin.getBlockY())), Masks.negate(new ExistingBlockMask(this))); + // Want to replace blocks BlockReplace replace = new BlockReplace(this, pattern); @@ -1313,7 +1322,9 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { * @param block the block to place * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed + * @deprecated Use {@link EditSession#makeCuboidFaces(Region, Pattern)}. */ + @Deprecated public > int makeCuboidFaces(Region region, B block) throws MaxChangedBlocksException { return makeCuboidFaces(region, block); } @@ -1420,7 +1431,9 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { * @param block the placed block * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed + * @deprecated Use {@link EditSession#overlayCuboidBlocks(Region, Pattern)}. */ + @Deprecated public > int overlayCuboidBlocks(Region region, B block) throws MaxChangedBlocksException { checkNotNull(block); @@ -1573,7 +1586,9 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { ForwardExtentCopy copy = new ForwardExtentCopy(this, region, this, to); - if (replacement == null) replacement = BlockTypes.AIR.getDefaultState(); + if (replacement == null) { + replacement = BlockTypes.AIR.getDefaultState(); + } BlockReplace remove = replacement instanceof ExistingPattern ? null : new BlockReplace(this, replacement); copy.setSourceFunction(remove); // Remove @@ -1649,8 +1664,8 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { Mask liquidMask; if (plants) { - liquidMask = new BlockTypeMask(this, BlockTypes.LAVA, BlockTypes.WATER, - BlockTypes.KELP_PLANT, BlockTypes.KELP, BlockTypes.SEAGRASS, BlockTypes.TALL_SEAGRASS); + liquidMask = new BlockTypeMask(this, BlockTypes.LAVA, BlockTypes.WATER, + BlockTypes.KELP_PLANT, BlockTypes.KELP, BlockTypes.SEAGRASS, BlockTypes.TALL_SEAGRASS); } else { liquidMask = new BlockTypeMask(this, BlockTypes.LAVA, BlockTypes.WATER); } @@ -1660,9 +1675,9 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { liquidMask = new MaskUnion(liquidMask, new BlockStateMask(this, stateMap, true)); } Mask mask = new MaskIntersection( - new BoundedHeightMask(0, getWorld().getMaxY()), - new RegionMask(new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), - liquidMask); + new BoundedHeightMask(0, getWorld().getMaxY()), + new RegionMask(new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), + liquidMask); BlockReplace replace; if (waterlogged) { replace = new BlockReplace(this, new WaterloggedRemover(this)); @@ -1708,6 +1723,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { new RegionMask(new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), blockMask ); + BlockReplace replace = new BlockReplace(this, fluid.getDefaultState()); NonRisingVisitor visitor = new NonRisingVisitor(mask, replace); @@ -1787,7 +1803,8 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { final int ceilRadiusX = (int) Math.ceil(radiusX); final int ceilRadiusZ = (int) Math.ceil(radiusZ); - double xSqr, zSqr; + double xSqr; + double zSqr; double distanceSq; double nextXn = 0; @@ -1910,7 +1927,11 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { LocalBlockVectorSet set = new LocalBlockVectorSet(); double nextXn = 0; - double dx, dy, dz, dxy, dxyz; + double dx; + double dy; + double dz; + double dxy; + double dxyz; forX: for (int x = 0; x <= ceilRadiusX; ++x) { final double xn = nextXn; @@ -1945,22 +1966,30 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } } - if (Math.abs((x) * nx + (y) * ny + (z) * nz) < threshold) + if (Math.abs((x) * nx + (y) * ny + (z) * nz) < threshold) { setBlock(mutable.setComponents(px + x, py + y, pz + z), block); - if (Math.abs((-x) * nx + (y) * ny + (z) * nz) < threshold) + } + if (Math.abs((-x) * nx + (y) * ny + (z) * nz) < threshold) { setBlock(mutable.setComponents(px - x, py + y, pz + z), block); - if (Math.abs((x) * nx + (-y) * ny + (z) * nz) < threshold) + } + if (Math.abs((x) * nx + (-y) * ny + (z) * nz) < threshold) { setBlock(mutable.setComponents(px + x, py - y, pz + z), block); - if (Math.abs((x) * nx + (y) * ny + (-z) * nz) < threshold) + } + if (Math.abs((x) * nx + (y) * ny + (-z) * nz) < threshold) { setBlock(mutable.setComponents(px + x, py + y, pz - z), block); - if (Math.abs((-x) * nx + (-y) * ny + (z) * nz) < threshold) + } + if (Math.abs((-x) * nx + (-y) * ny + (z) * nz) < threshold) { setBlock(mutable.setComponents(px - x, py - y, pz + z), block); - if (Math.abs((x) * nx + (-y) * ny + (-z) * nz) < threshold) + } + if (Math.abs((x) * nx + (-y) * ny + (-z) * nz) < threshold) { setBlock(mutable.setComponents(px + x, py - y, pz - z), block); - if (Math.abs((-x) * nx + (y) * ny + (-z) * nz) < threshold) + } + if (Math.abs((-x) * nx + (y) * ny + (-z) * nz) < threshold) { setBlock(mutable.setComponents(px - x, py + y, pz - z), block); - if (Math.abs((-x) * nx + (-y) * ny + (-z) * nz) < threshold) + } + if (Math.abs((-x) * nx + (-y) * ny + (-z) * nz) < threshold) { setBlock(mutable.setComponents(px - x, py - y, pz - z), block); + } } } } @@ -2050,18 +2079,26 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { yy = py + y; if (yy <= maxY) { this.setBlock(px + x, py + y, pz + z, block); - if (x != 0) this.setBlock(px - x, py + y, pz + z, block); + if (x != 0) { + this.setBlock(px - x, py + y, pz + z, block); + } if (z != 0) { this.setBlock(px + x, py + y, pz - z, block); - if (x != 0) this.setBlock(px - x, py + y, pz - z, block); + if (x != 0) { + this.setBlock(px - x, py + y, pz - z, block); + } } } if (y != 0 && (yy = py - y) >= 0) { this.setBlock(px + x, yy, pz + z, block); - if (x != 0) this.setBlock(px - x, yy, pz + z, block); + if (x != 0) { + this.setBlock(px - x, yy, pz + z, block); + } if (z != 0) { this.setBlock(px + x, yy, pz - z, block); - if (x != 0) this.setBlock(px - x, yy, pz - z, block); + if (x != 0) { + this.setBlock(px - x, yy, pz - z, block); + } } } } @@ -2114,8 +2151,9 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ + @Deprecated public int thaw(BlockVector3 position, double radius) - throws MaxChangedBlocksException { + throws MaxChangedBlocksException { int affected = 0; double radiusSq = radius * radius; @@ -2164,6 +2202,7 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ + @Deprecated public int simulateSnow(BlockVector3 position, double radius) throws MaxChangedBlocksException { int affected = 0; double radiusSq = radius * radius; @@ -2257,7 +2296,11 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { final BlockType block = getBlockType(x, y, z); switch (block.getInternalId()) { case BlockID.COARSE_DIRT: - if (onlyNormalDirt) break loop; + if (onlyNormalDirt) { + break loop; + } + this.setBlock(x, y, z, grass); + break loop; case BlockID.DIRT: this.setBlock(x, y, z, grass); break loop; @@ -2344,7 +2387,9 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { * @return the results */ public List> getBlockDistribution(Region region, boolean separateStates) { - if (separateStates) return getBlockDistributionWithData(region); + if (separateStates) { + return getBlockDistributionWithData(region); + } List> normalDistr = getBlockDistribution(region); List> distribution = new ArrayList<>(); for (Countable count : normalDistr) { @@ -2363,8 +2408,8 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { * @param expressionString the expression defining the shape * @param hollow whether the shape should be hollow * @return number of blocks changed - * @throws ExpressionException Thrown when there's a problem during any stage of the expression compilation or evaluation. - * @throws MaxChangedBlocksException Thrown when the block limit has been reached + * @throws ExpressionException if there is a problem with the expression + * @throws MaxChangedBlocksException if the maximum block change limit is exceeded */ public int makeShape(final Region region, final Vector3 zero, final Vector3 unit, final Pattern pattern, final String expressionString, final boolean hollow) @@ -2383,11 +2428,11 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { * @param hollow whether the shape should be hollow * @param timeout the time, in milliseconds, to wait for each expression evaluation before halting it. -1 to disable * @return number of blocks changed - * @throws ExpressionException Thrown when there's a problem during any stage of the expression compilation or evaluation. - * @throws MaxChangedBlocksException Thrown when the block limit has been reached + * @throws ExpressionException if there is a problem with the expression + * @throws MaxChangedBlocksException if the maximum block change limit is exceeded */ public int makeShape(final Region region, final Vector3 zero, final Vector3 unit, - final Pattern pattern, final String expressionString, final boolean hollow, final int timeout) + final Pattern pattern, final String expressionString, final boolean hollow, final int timeout) throws ExpressionException, MaxChangedBlocksException { final Expression expression = Expression.compile(expressionString, "x", "y", "z", "type", "data"); expression.optimize(); @@ -2548,63 +2593,64 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { public int hollowOutRegion(Region region, int thickness, Pattern pattern, Mask mask) { try { - final Set outside = new LocalBlockVectorSet(); + final Set outside = new LocalBlockVectorSet(); - final BlockVector3 min = region.getMinimumPoint(); - final BlockVector3 max = region.getMaximumPoint(); + final BlockVector3 min = region.getMinimumPoint(); + final BlockVector3 max = region.getMaximumPoint(); - final int minX = min.getBlockX(); - final int minY = min.getBlockY(); - final int minZ = min.getBlockZ(); - final int maxX = max.getBlockX(); - final int maxY = max.getBlockY(); - final int maxZ = max.getBlockZ(); + final int minX = min.getBlockX(); + final int minY = min.getBlockY(); + final int minZ = min.getBlockZ(); + final int maxX = max.getBlockX(); + final int maxY = max.getBlockY(); + final int maxZ = max.getBlockZ(); - for (int x = minX; x <= maxX; ++x) { - for (int y = minY; y <= maxY; ++y) { - recurseHollow(region, BlockVector3.at(x, y, minZ), outside, mask); - recurseHollow(region, BlockVector3.at(x, y, maxZ), outside, mask); - } - } - - for (int y = minY; y <= maxY; ++y) { - for (int z = minZ; z <= maxZ; ++z) { - recurseHollow(region, BlockVector3.at(minX, y, z), outside, mask); - recurseHollow(region, BlockVector3.at(maxX, y, z), outside, mask); - } - } - - for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { - recurseHollow(region, BlockVector3.at(x, minY, z), outside, mask); - recurseHollow(region, BlockVector3.at(x, maxY, z), outside, mask); + for (int y = minY; y <= maxY; ++y) { + recurseHollow(region, BlockVector3.at(x, y, minZ), outside, mask); + recurseHollow(region, BlockVector3.at(x, y, maxZ), outside, mask); + } + } + + for (int y = minY; y <= maxY; ++y) { + for (int z = minZ; z <= maxZ; ++z) { + recurseHollow(region, BlockVector3.at(minX, y, z), outside, mask); + recurseHollow(region, BlockVector3.at(maxX, y, z), outside, mask); + } + } + + for (int z = minZ; z <= maxZ; ++z) { + for (int x = minX; x <= maxX; ++x) { + recurseHollow(region, BlockVector3.at(x, minY, z), outside, mask); + recurseHollow(region, BlockVector3.at(x, maxY, z), outside, mask); + } + } + + for (int i = 1; i < thickness; ++i) { + 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); } - } - for (int i = 1; i < thickness; ++i) { - 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; - } - } - this.changes++; + this.changes++; pattern.apply(getExtent(), position, position); } } catch (WorldEditException e) { @@ -2632,15 +2678,23 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { * @see #drawLine(Pattern, List, double, boolean) */ public int drawLine(Pattern pattern, BlockVector3 pos1, BlockVector3 pos2, double radius, boolean filled, boolean flat) - throws MaxChangedBlocksException { + throws MaxChangedBlocksException { LocalBlockVectorSet vset = new LocalBlockVectorSet(); boolean notdrawn = true; - int x1 = pos1.getBlockX(), y1 = pos1.getBlockY(), z1 = pos1.getBlockZ(); - int x2 = pos2.getBlockX(), y2 = pos2.getBlockY(), z2 = pos2.getBlockZ(); - int tipx = x1, tipy = y1, tipz = z1; - int dx = Math.abs(x2 - x1), dy = Math.abs(y2 - y1), dz = Math.abs(z2 - z1); + int x1 = pos1.getBlockX(); + int y1 = pos1.getBlockY(); + int z1 = pos1.getBlockZ(); + int x2 = pos2.getBlockX(); + int y2 = pos2.getBlockY(); + int z2 = pos2.getBlockZ(); + int tipx = x1; + int tipy = y1; + int tipz = z1; + int dx = Math.abs(x2 - x1); + int dy = Math.abs(y2 - y1); + int dz = Math.abs(z2 - z1); if (dx + dy + dz == 0) { vset.add(BlockVector3.at(tipx, tipy, tipz)); @@ -2667,8 +2721,8 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } else if (dMax == dz && notdrawn) { for (int domstep = 0; domstep <= dz; domstep++) { tipz = z1 + domstep * (z2 - z1 > 0 ? 1 : -1); - tipy = (int) Math.round(y1 + domstep * (double) dy / (double) dz * (y2-y1>0 ? 1 : -1)); - tipx = (int) Math.round(x1 + domstep * (double) dx / (double) dz * (x2-x1>0 ? 1 : -1)); + tipy = (int) Math.round(y1 + domstep * (double) dy / (double) dz * (y2 - y1 > 0 ? 1 : -1)); + tipx = (int) Math.round(x1 + domstep * (double) dx / (double) dz * (x2 - x1 > 0 ? 1 : -1)); vset.add(BlockVector3.at(tipx, tipy, tipz)); } @@ -2708,10 +2762,18 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { BlockVector3 pos1 = vectors.get(i); BlockVector3 pos2 = vectors.get(i + 1); - int x1 = pos1.getBlockX(), y1 = pos1.getBlockY(), z1 = pos1.getBlockZ(); - int x2 = pos2.getBlockX(), y2 = pos2.getBlockY(), z2 = pos2.getBlockZ(); - int tipx = x1, tipy = y1, tipz = z1; - int dx = Math.abs(x2 - x1), dy = Math.abs(y2 - y1), dz = Math.abs(z2 - z1); + int x1 = pos1.getBlockX(); + int y1 = pos1.getBlockY(); + int z1 = pos1.getBlockZ(); + int x2 = pos2.getBlockX(); + int y2 = pos2.getBlockY(); + int z2 = pos2.getBlockZ(); + int tipx = x1; + int tipy = y1; + int tipz = z1; + int dx = Math.abs(x2 - x1); + int dy = Math.abs(y2 - y1); + int dz = Math.abs(z2 - z1); if (dx + dy + dz == 0) { vset.add(BlockVector3.at(tipx, tipy, tipz)); @@ -2738,8 +2800,8 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { } else /* if (dMax == dz) */ { for (int domstep = 0; domstep <= dz; domstep++) { tipz = z1 + domstep * (z2 - z1 > 0 ? 1 : -1); - tipy = (int) Math.round(y1 + domstep * ((double) dy) / ((double) dz) * (y2-y1>0 ? 1 : -1)); - tipx = (int) Math.round(x1 + domstep * ((double) dx) / ((double) dz) * (x2-x1>0 ? 1 : -1)); + tipy = (int) Math.round(y1 + domstep * ((double) dy) / ((double) dz) * (y2 - y1 > 0 ? 1 : -1)); + tipx = (int) Math.round(x1 + domstep * ((double) dx) / ((double) dz) * (x2 - x1 > 0 ? 1 : -1)); vset.add(BlockVector3.at(tipx, tipy, tipz)); } @@ -2815,7 +2877,9 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { int ceilrad = (int) Math.ceil(radius); for (BlockVector3 v : vset) { - int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ(); + int tipx = v.getBlockX(); + int tipy = v.getBlockY(); + int tipz = v.getBlockZ(); for (int loopx = tipx - ceilrad; loopx <= tipx + ceilrad; loopx++) { for (int loopy = tipy - ceilrad; loopy <= tipy + ceilrad; loopy++) { @@ -2837,7 +2901,9 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { final LocalBlockVectorSet returnset = new LocalBlockVectorSet(); final int ceilrad = (int) Math.ceil(radius); for (BlockVector3 v : vset) { - final int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ(); + final int tipx = v.getBlockX(); + final int tipy = v.getBlockY(); + final int tipz = v.getBlockZ(); for (int loopx = tipx - ceilrad; loopx <= tipx + ceilrad; loopx++) { for (int loopz = tipz - ceilrad; loopz <= tipz + ceilrad; loopz++) { if (MathMan.hypot(loopx - tipx, 0, loopz - tipz) <= radius) { @@ -2854,11 +2920,13 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { final LocalBlockVectorSet newset = new LocalBlockVectorSet(); newset.addAll(vset); for (BlockVector3 v : newset) { - final int x = v.getX(), y = v.getY(), z = v.getZ(); - if (!(newset.contains(x + 1, y, z) && - newset.contains(x - 1, y, z) && - newset.contains(x, y, z + 1) && - newset.contains(x, y, z - 1))) { + final int x = v.getX(); + final int y = v.getY(); + final int z = v.getZ(); + if (!(newset.contains(x + 1, y, z) + && newset.contains(x - 1, y, z) + && newset.contains(x, y, z + 1) + && newset.contains(x, y, z - 1))) { returnset.add(v); } } @@ -2870,13 +2938,15 @@ public class EditSession extends PassthroughExtent implements AutoCloseable { final LocalBlockVectorSet newset = new LocalBlockVectorSet(); newset.addAll(vset); for (BlockVector3 v : newset) { - final int x = v.getX(), y = v.getY(), z = v.getZ(); - if (!(newset.contains(x + 1, y, z) && - newset.contains(x - 1, y, z) && - newset.contains(x, y + 1, z) && - newset.contains(x, y - 1, z) && - newset.contains(x, y, z + 1) && - newset.contains(x, y, z - 1))) { + final int x = v.getX(); + final int y = v.getY(); + final int z = v.getZ(); + if (!(newset.contains(x + 1, y, z) + && newset.contains(x - 1, y, z) + && newset.contains(x, y + 1, z) + && newset.contains(x, y - 1, z) + && newset.contains(x, y, z + 1) + && newset.contains(x, y, z - 1))) { returnset.add(v); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java b/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java index 477e446e6..4b8345798 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java @@ -137,7 +137,7 @@ public class LocalSession implements TextureHolder { private transient final Object clipboardLock = new Object(); private transient boolean superPickaxe = false; private transient BlockTool pickaxeMode = new SinglePickaxe(); - private transient final Int2ObjectOpenHashMap tools = new Int2ObjectOpenHashMap<>(0); + private final transient Int2ObjectOpenHashMap tools = new Int2ObjectOpenHashMap<>(0); private transient int maxBlocksChanged = -1; private transient int maxTimeoutTime; private transient boolean useInventory; @@ -245,9 +245,13 @@ public class LocalSession implements TextureHolder { } else { int i = name.lastIndexOf('.'); - if (i != -1) val = StringMan.toInteger(name, 0, i); + if (i != -1) { + val = StringMan.toInteger(name, 0, i); + } + } + if (val != null) { + set.set(val); } - if (val != null) set.set(val); return false; }); } @@ -402,7 +406,9 @@ public class LocalSession implements TextureHolder { checkNotNull(editSession); // Don't store anything if no changes were made - if (editSession.size() == 0) return; + if (editSession.size() == 0) { + return; + } Player player = editSession.getPlayer(); int limit = player == null ? Integer.MAX_VALUE : player.getLimit().MAX_HISTORY; @@ -721,7 +727,8 @@ public class LocalSession implements TextureHolder { return selector.getRegion(); } - public @Nullable VirtualWorld getVirtualWorld() { + @Nullable + public VirtualWorld getVirtualWorld() { synchronized (dirty) { return virtual; } @@ -814,8 +821,9 @@ public class LocalSession implements TextureHolder { */ public void setClipboard(@Nullable ClipboardHolder clipboard) { synchronized (clipboardLock) { - if (this.clipboard == clipboard) + if (this.clipboard == clipboard) { return; + } if (this.clipboard != null) { if (clipboard == null || !clipboard.contains(this.clipboard.getClipboard())) { @@ -990,7 +998,8 @@ public class LocalSession implements TextureHolder { * * @return the snapshot */ - public @Nullable Snapshot getSnapshotExperimental() { + @Nullable + public Snapshot getSnapshotExperimental() { return snapshotExperimental; } @@ -1051,7 +1060,9 @@ public class LocalSession implements TextureHolder { public Tool getTool(BaseItem item, Player player) { if (Settings.IMP.EXPERIMENTAL.PERSISTENT_BRUSHES && item.getNativeItem() != null) { BrushTool tool = BrushCache.getTool(player, this, item); - if (tool != null) return tool; + if (tool != null) { + return tool; + } } loadDefaults(player, false); return getTool(item.getType()); @@ -1244,7 +1255,9 @@ public class LocalSession implements TextureHolder { * @param actor the actor */ public void tellVersion(Actor actor) { - if (hasBeenToldVersion) return; + if (hasBeenToldVersion) { + return; + } hasBeenToldVersion = true; actor.sendAnnouncements(); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEditManifest.java b/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEditManifest.java index 757a58d13..4c0e4cbb3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEditManifest.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEditManifest.java @@ -42,7 +42,8 @@ public class WorldEditManifest { ); } - private static @Nullable Attributes readAttributes() { + @Nullable + private static Attributes readAttributes() { Class clazz = WorldEditManifest.class; String className = clazz.getSimpleName() + ".class"; String classPath = clazz.getResource(className).toString(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BaseItem.java b/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BaseItem.java index 5bf6238c1..6ca95e2f9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BaseItem.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BaseItem.java @@ -62,7 +62,8 @@ public class BaseItem implements NbtValued { } @Deprecated - public @Nullable Object getNativeItem() { + @Nullable + public Object getNativeItem() { return null; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ApplyBrushCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ApplyBrushCommands.java index 2105d2aa1..ad2e993a0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ApplyBrushCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ApplyBrushCommands.java @@ -62,12 +62,12 @@ import static org.enginehub.piston.part.CommandParts.arg; @CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class) public class ApplyBrushCommands { - private static final CommandArgument REGION_FACTORY = arg(TranslatableComponent.of("shape") , TranslatableComponent.of("worldedit.brush.apply.shape")) + private static final CommandArgument REGION_FACTORY = arg(TranslatableComponent.of("shape"), TranslatableComponent.of("worldedit.brush.apply.shape")) .defaultsTo(ImmutableList.of()) .ofTypes(ImmutableList.of(Key.of(RegionFactory.class))) .build(); - private static final CommandArgument RADIUS = arg(TranslatableComponent.of("radius") , TranslatableComponent.of("worldedit.brush.apply.radius")) + private static final CommandArgument RADIUS = arg(TranslatableComponent.of("radius"), TranslatableComponent.of("worldedit.brush.apply.radius")) .defaultsTo(ImmutableList.of("5")) .ofTypes(ImmutableList.of(Key.of(double.class))) .build(); @@ -86,7 +86,7 @@ public class ApplyBrushCommands { builder.condition(new PermissionCondition(ImmutableSet.of("worldedit.brush.apply"))); builder.addParts(REGION_FACTORY, RADIUS); - builder.addPart(SubCommandPart.builder(TranslatableComponent.of("type") , TranslatableComponent.of("worldedit.brush.apply.type")) + builder.addPart(SubCommandPart.builder(TranslatableComponent.of("type"), TranslatableComponent.of("worldedit.brush.apply.type")) .withCommands(manager.getAllCommands().collect(Collectors.toList())) .required() .build()); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/BrushCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/BrushCommands.java index 4221717ce..9d97eb8a8 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/BrushCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/BrushCommands.java @@ -153,207 +153,251 @@ public class BrushCommands { this.worldEdit = worldEdit; } - @Command(name = "none", - aliases = "unbind", - desc = "Unbind a bound brush from your current item") + @Command( + name = "none", + aliases = "unbind", + desc = "Unbind a bound brush from your current item" + ) void none(Player player, LocalSession session) throws WorldEditException { ToolCommands.setToolNone(player, session, true); } @Command(name = "blendball", - aliases = { - "bb", - "blend" - }, - desc = "Smooths and blends terrain", - descFooter = "Smooths and blends terrain\n" - + "Pic: https://i.imgur.com/cNUQUkj.png → https://i.imgur.com/hFOFsNf.png") + aliases = { + "bb", + "blend" + }, + desc = "Smooths and blends terrain", + descFooter = "Smooths and blends terrain\n" + + "Pic: https://i.imgur.com/cNUQUkj.png → https://i.imgur.com/hFOFsNf.png" + ) @CommandPermissions("worldedit.brush.blendball") public void blendBallBrush(InjectedValueAccess context, - @Arg(desc = "The radius to sample for blending", - def = "5") Expression radius) throws WorldEditException { + @Arg(desc = "The radius to sample for blending", def = "5") + Expression radius) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new BlendBall()).setSize(radius); } - @Command(name = "erode", - desc = "Erodes terrain") + @Command( + name = "erode", + desc = "Erodes terrain" + ) @CommandPermissions("worldedit.brush.erode") - public void erodeBrush(InjectedValueAccess context, @Arg(desc = "The radius for eroding", - def = "5") Expression radius, - @Arg(desc = "erodeFaces", - def = "2") int erodefaces, @Arg(desc = "erodeRec", - def = "1") int erodeRec, @Arg(desc = "fillFaces", - def = "5") int fillFaces, - @Arg(desc = "fillRec", - def = "1") int fillRec) throws WorldEditException { + public void erodeBrush(InjectedValueAccess context, + @Arg(desc = "The radius for eroding", def = "5") + Expression radius, + @Arg(desc = "erodeFaces", def = "2") + int erodefaces, + @Arg(desc = "erodeRec", def = "1") + int erodeRec, + @Arg(desc = "fillFaces", def = "5") + int fillFaces, + @Arg(desc = "fillRec", def = "1") + int fillRec) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new ErodeBrush(erodefaces, erodeRec, fillFaces, fillRec)).setSize(radius); } - @Command(name = "pull", - desc = "Pull terrain towards you") + @Command( + name = "pull", + desc = "Pull terrain towards you" + ) @CommandPermissions("worldedit.brush.pull") public void pullBrush(InjectedValueAccess context, - @Arg(desc = "The radius to sample for blending", - def = "5") Expression radius, @Arg(desc = "erodeFaces", - def = "6") int erodefaces, @Arg(desc = "erodeRec", - def = "0") - int erodeRec, @Arg(desc = "fillFaces", - def = "1") int fillFaces, @Arg(desc = "fillRec", - def = "1") int fillRec) - throws WorldEditException { + @Arg(desc = "The radius to sample for blending", def = "5") + Expression radius, + @Arg(desc = "erodeFaces", def = "6") + int erodefaces, + @Arg(desc = "erodeRec", def = "0") + int erodeRec, + @Arg(desc = "fillFaces", def = "1") + int fillFaces, + @Arg(desc = "fillRec", def = "1") + int fillRec) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new RaiseBrush(erodefaces, erodeRec, fillFaces, fillRec)).setSize(radius); } - @Command(name = "circle", - desc = "Creates a circle, which revolves around your facing direction") + @Command( + name = "circle", + desc = "Creates a circle, which revolves around your facing direction" + ) @CommandPermissions("worldedit.brush.sphere") public void circleBrush(Player player, InjectedValueAccess context, - @Arg(desc = "Pattern") Pattern fill, @Arg(desc = "The radius to sample for blending", - def = "5") Expression radius) - throws WorldEditException { + @Arg(desc = "Pattern") + Pattern fill, + @Arg(desc = "The radius to sample for blending", def = "5") + Expression radius) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new CircleBrush(player)).setSize(radius).setFill(fill); } - @Command(name = "recursive", - aliases = { - "recurse", - "r" - }, - desc = "Set all connected blocks", - descFooter = "Set all connected blocks\n" - + "Note: Set a mask to recurse along specific blocks") + @Command( + name = "recursive", + aliases = { + "recurse", + "r" + }, + desc = "Set all connected blocks", + descFooter = "Set all connected blocks\n" + + "Note: Set a mask to recurse along specific blocks" + ) @CommandPermissions("worldedit.brush.recursive") public void recursiveBrush(InjectedValueAccess context, EditSession editSession, - @Arg(desc = "Pattern") Pattern fill, @Arg(desc = "The radius to sample for blending", - def = "5") Expression radius, @Switch(name = 'd', - desc = "Apply in depth first order") - boolean depthFirst) throws WorldEditException { + @Arg(desc = "Pattern") + Pattern fill, + @Arg(desc = "The radius to sample for blending", def = "5") + Expression radius, + @Switch(name = 'd', desc = "Apply in depth first order") + boolean depthFirst) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new RecurseBrush(depthFirst)).setSize(radius).setFill(fill) - .setMask(new IdMask(editSession)); + .setMask(new IdMask(editSession)); } - @Command(name = "line", - aliases = { "l" }, - desc = "Create lines") + @Command( + name = "line", + aliases = { "l" }, + desc = "Create lines" + ) @CommandPermissions("worldedit.brush.line") public void lineBrush(InjectedValueAccess context, - @Arg(desc = "Pattern") Pattern fill, @Arg(desc = "The radius to sample for blending", - def = "0") Expression radius, @Switch(name = 'h', - desc = "Create only a shell") - boolean shell, @Switch(name = 's', - desc = "Selects the clicked point after drawing") boolean select, - @Switch(name = 'f', - desc = "Create a flat line") boolean flat) throws WorldEditException { + @Arg(desc = "Pattern") + Pattern fill, + @Arg(desc = "The radius to sample for blending", def = "0") + Expression radius, + @Switch(name = 'h', desc = "Create only a shell") + boolean shell, + @Switch(name = 's', desc = "Selects the clicked point after drawing") boolean select, + @Switch(name = 'f', desc = "Create a flat line") + boolean flat) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new LineBrush(shell, select, flat)).setSize(radius).setFill(fill); } - @Command(name = "spline", - aliases = { - "spl", - "curve" - }, - desc = "Join multiple objects together in a curve", - descFooter = - "Click to select some objects,click the same block twice to connect the objects.\n" - + "Insufficient brush radius, or clicking the the wrong spot will result in undesired shapes. The shapes must be simple lines or loops.\n" - + "Pic1: http://i.imgur.com/CeRYAoV.jpg -> http://i.imgur.com/jtM0jA4.png\n" - + "Pic2: http://i.imgur.com/bUeyc72.png -> http://i.imgur.com/tg6MkcF.png" - + "Tutorial: https://www.planetminecraft.com/blog/fawe-tutorial/") + @Command( + name = "spline", + aliases = { + "spl", + "curve" + }, + desc = "Join multiple objects together in a curve", + descFooter = + "Click to select some objects,click the same block twice to connect the objects.\n" + + "Insufficient brush radius, or clicking the the wrong spot will result in undesired shapes. The shapes must be simple lines or loops.\n" + + "Pic1: http://i.imgur.com/CeRYAoV.jpg -> http://i.imgur.com/jtM0jA4.png\n" + + "Pic2: http://i.imgur.com/bUeyc72.png -> http://i.imgur.com/tg6MkcF.png" + + "Tutorial: https://www.planetminecraft.com/blog/fawe-tutorial/" + ) @CommandPermissions("worldedit.brush.spline") public void splineBrush(Player player, InjectedValueAccess context, - @Arg(desc = "Pattern") Pattern fill, @Arg(desc = "The radius to sample for blending", - def = "25") Expression radius) + @Arg(desc = "Pattern") + Pattern fill, + @Arg(desc = "The radius to sample for blending", def = "25") + Expression radius) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); player.print(Caption.of("fawe.worldedit.brush.brush.spline", (radius))); set(context, new SplineBrush(player)).setSize(radius).setFill(fill); } - @Command(name = "sweep", - aliases = { - "sw", - "vaesweep" - }, - desc = "Sweep your clipboard content along a curve", - descFooter = "Sweeps your clipboard content along a curve.\n" - + "Define a curve by selecting the individual points with a brush\n" - + "Set [copies] to a value > 0 if you want to have your selection pasted a limited amount of times equally spaced on the curve") + @Command( + name = "sweep", + aliases = { + "sw", + "vaesweep" + }, + desc = "Sweep your clipboard content along a curve", + descFooter = "Sweeps your clipboard content along a curve.\n" + + "Define a curve by selecting the individual points with a brush\n" + + "Set [copies] to a value > 0 if you want to have your selection pasted a limited amount of times equally spaced on the curve" + ) @CommandPermissions("worldedit.brush.sweep") - public void sweepBrush(Player player, InjectedValueAccess context, @Arg(desc = "int", - def = "-1") int copies) - throws WorldEditException { + public void sweepBrush(Player player, InjectedValueAccess context, + @Arg(desc = "int", def = "-1") + int copies) throws WorldEditException { player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.spline")); set(context, new SweepBrush(copies)); } - @Command(name = "catenary", - aliases = { - "cat", - "gravityline", - "saggedline" - }, - desc = "Create a hanging line between two points") + @Command( + name = "catenary", + aliases = { + "cat", + "gravityline", + "saggedline" + }, + desc = "Create a hanging line between two points" + ) @CommandPermissions("worldedit.brush.spline") public void catenaryBrush(InjectedValueAccess context, - @Arg(desc = "Pattern") Pattern fill, @Arg(def = "1.2", - desc = "Length of wire compared to distance between points") - @Range(from = 1, - to = Integer.MAX_VALUE) double lengthFactor, - @Arg(desc = "The radius to sample for blending", - def = "0") Expression radius, @Switch(name = 'h', - desc = "Create only a shell") boolean shell, - @Switch(name = 's', - desc = "Select the clicked point after drawing") boolean select, @Switch(name = 'd', - desc = "sags the catenary toward the facing direction") - boolean facingDirection) throws WorldEditException { + @Arg(desc = "Pattern") + Pattern fill, + @Arg(def = "1.2", desc = "Length of wire compared to distance between points") + @Range(from = 1, to = Integer.MAX_VALUE) + double lengthFactor, + @Arg(desc = "The radius to sample for blending", def = "0") + Expression radius, + @Switch(name = 'h', desc = "Create only a shell") + boolean shell, + @Switch(name = 's', desc = "Select the clicked point after drawing") + boolean select, + @Switch(name = 'd', desc = "sags the catenary toward the facing direction") + boolean facingDirection) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); Brush brush = new CatenaryBrush(shell, select, facingDirection, lengthFactor); set(context, new CatenaryBrush(shell, select, facingDirection, lengthFactor)) .setSize(radius).setFill(fill); } - @Command(name = "surfacespline", - aliases = { - "sspline", - "sspl" - }, - desc = "Draws a spline (curved line) on the surface", - descFooter = "Create a spline on the surface\n" - + "Video: https://www.youtube.com/watch?v=zSN-2jJxXlM") + @Command( + name = "surfacespline", + aliases = { + "sspline", + "sspl" + }, + desc = "Draws a spline (curved line) on the surface", + descFooter = "Create a spline on the surface\n" + + "Video: https://www.youtube.com/watch?v=CukvVOi4jv8" + ) @CommandPermissions("worldedit.brush.surfacespline") // 0, 0, 0, 10, 0, public void surfaceSpline(Player player, InjectedValueAccess context, - @Arg(desc = "Pattern") Pattern fill, @Arg(desc = "The radius to sample for blending", - def = "0") Expression radius, - @Arg(desc = "double", - def = "0") double tension, @Arg(desc = "double", - def = "0") double bias, @Arg(desc = "double", - def = "0") - double continuity, @Arg(desc = "double", - def = "10") double quality) throws WorldEditException { + @Arg(desc = "Pattern") + Pattern fill, + @Arg(desc = "The radius to sample for blending", def = "0") + Expression radius, + @Arg(desc = "double", def = "0") + double tension, + @Arg(desc = "double", def = "0") + double bias, + @Arg(desc = "double", def = "0") + double continuity, + @Arg(desc = "double", def = "10") + double quality) throws WorldEditException { player.print(Caption.of("fawe.worldedit.brush.brush.spline", (radius))); worldEdit.checkMaxBrushRadius(radius); set(context, new SurfaceSpline(tension, bias, continuity, quality)).setSize(radius) .setFill(fill); } - @Command(name = "rock", - aliases = { "blob" }, - desc = "Creates a distorted sphere") + @Command( + name = "rock", + aliases = { "blob" }, + desc = "Creates a distorted sphere" + ) @CommandPermissions("worldedit.brush.rock") public void blobBrush(InjectedValueAccess context, - @Arg(desc = "Pattern") Pattern fill, @Arg(desc = "Vector3", - def = "10") Vector3 radius, @Arg(desc = "double", - def = "100") - double sphericity, @Arg(desc = "double", - def = "30") double frequency, @Arg(desc = "double", - def = "50") double amplitude) - throws WorldEditException { + @Arg(desc = "Pattern") + Pattern fill, + @Arg(desc = "radius", def = "10") + Vector3 radius, + @Arg(name = "roundness", desc = "roundness", def = "100") + double sphericity, + @Arg(desc = "double", def = "30") + double frequency, + @Arg(desc = "double", def = "50") + double amplitude) throws WorldEditException { double max = MathMan.max(radius.getX(), radius.getY(), radius.getZ()); worldEdit.checkMaxBrushRadius(max); Brush brush = @@ -361,18 +405,21 @@ public class BrushCommands { set(context, brush).setSize(max).setFill(fill); } - @Command(name = "sphere", - aliases = { "s" }, - desc = "Choose the sphere brush") + @Command( + name = "sphere", + aliases = { "s" }, + desc = "Choose the sphere brush" + ) @CommandPermissions("worldedit.brush.sphere") public void sphereBrush(Player player, InjectedValueAccess context, - @Arg(desc = "The pattern of blocks to set") Pattern pattern, - @Arg(desc = "The radius of the sphere", - def = "2") Expression radius, @Switch(name = 'h', - desc = "Create hollow spheres instead") - boolean hollow, @Switch(name = 'f', - desc = "Create falling spheres instead") boolean falling) - throws WorldEditException { + @Arg(desc = "The pattern of blocks to set") + Pattern pattern, + @Arg(desc = "The radius of the sphere", def = "2") + Expression radius, + @Switch(name = 'h', desc = "Create hollow spheres instead") + boolean hollow, + @Switch(name = 'f', desc = "Create falling spheres instead") + boolean falling) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); Brush brush; if (hollow) { @@ -386,6 +433,9 @@ public class BrushCommands { player.print( TranslatableComponent.of("fawe.worldedit.brush.brush.try.other")); falling = true; + break; + default: + break; } } if (falling) { @@ -398,41 +448,48 @@ public class BrushCommands { set(context, brush).setSize(radius).setFill(pattern); } - @Command(name = "shatter", - aliases = { - "partition", - "split" - }, - desc = "Creates random lines to break the terrain into pieces", - descFooter = "Creates uneven lines separating terrain into multiple pieces\n" - + "Pic: https://i.imgur.com/2xKsZf2.png") + @Command( + name = "shatter", + aliases = { "partition", "split"}, + desc = "Creates random lines to break the terrain into pieces", + descFooter = "Creates uneven lines separating terrain into multiple pieces\n" + + "Pic: https://i.imgur.com/2xKsZf2.png" + ) @CommandPermissions("worldedit.brush.shatter") public void shatterBrush(EditSession editSession, InjectedValueAccess context, - @Arg(desc = "Pattern") Pattern fill, @Arg(desc = "The radius to sample for blending", - def = "10") Expression radius, - @Arg(desc = "Lines", - def = "10") int count) throws WorldEditException { + @Arg(desc = "Pattern") + Pattern fill, + @Arg(desc = "The radius to sample for blending", def = "10") + Expression radius, + @Arg(desc = "Lines", def = "10") + int count) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new ShatterBrush(count)).setSize(radius).setFill(fill) .setMask(new ExistingBlockMask(editSession)); } - @Command(name = "stencil", - desc = "Use a height map to paint a surface", - descFooter = "Use a height map to paint any surface.\n") + @Command( + name = "stencil", + desc = "Use a height map to paint a surface", + descFooter = "Use a height map to paint any surface." + ) @CommandPermissions("worldedit.brush.stencil") public void stencilBrush(LocalSession session, InjectedValueAccess context, - @Arg(desc = "Pattern") Pattern fill, @Arg(desc = "Expression", - def = "5") Expression radius, - @Arg(desc = "String", - def = "") String image, @Arg(def = "0", - desc = "rotation") @Range(from = 0, - to = 360) int rotation, - @Arg(desc = "double", - def = "1") double yscale, @Switch(name = 'w', - desc = "Apply at maximum saturation") - boolean onlyWhite, @Switch(name = 'r', - desc = "Apply random rotation") boolean randomRotate) + @Arg(desc = "Pattern") + Pattern fill, + @Arg(desc = "Expression", def = "5") + Expression radius, + @Arg(desc = "String", def = "") + String image, + @Arg(def = "0", desc = "rotation") + @Range(from = 0, to = 360) + int rotation, + @Arg(desc = "double", def = "1") + double yscale, + @Switch(name = 'w', desc = "Apply at maximum saturation") + boolean onlyWhite, + @Switch(name = 'r', desc = "Apply random rotation") + boolean randomRotate) throws WorldEditException, FileNotFoundException { worldEdit.checkMaxBrushRadius(radius); InputStream stream = getHeightmapStream(image); @@ -440,9 +497,8 @@ public class BrushCommands { try { brush = new StencilBrush(stream, rotation, yscale, onlyWhite, "#clipboard".equalsIgnoreCase(image) - ? session.getClipboard().getClipboard() : - null); - } catch (EmptyClipboardException ignore) { + ? session.getClipboard().getClipboard() : null); + } catch (EmptyClipboardException ignored) { brush = new StencilBrush(stream, rotation, yscale, onlyWhite, null); } if (randomRotate) { @@ -458,13 +514,14 @@ public class BrushCommands { ) @CommandPermissions("worldedit.brush.stencil") public void imageBrush(LocalSession session, InjectedValueAccess context, - @Arg(desc = "The size of the brush", - def = "5") Expression radius, ProvideBindings.ImageUri imageUri, @Arg(def = "1", - desc = "scale height") - double yscale, @Switch(name = 'a', - desc = "Use image Alpha") boolean alpha, @Switch(name = 'f', - desc = "Blend the image with existing terrain") - boolean fadeOut) throws WorldEditException, IOException { + @Arg(desc = "The size of the brush", def = "5") + Expression radius, ProvideBindings.ImageUri imageUri, + @Arg(def = "1", desc = "scale height") + double yscale, + @Switch(name = 'a', desc = "Use image Alpha") + boolean alpha, + @Switch(name = 'f', desc = "Blend the image with existing terrain") + boolean fadeOut) throws WorldEditException, IOException { BufferedImage image = imageUri.load(); worldEdit.checkMaxBrushRadius(radius); if (yscale != 1) { @@ -479,35 +536,41 @@ public class BrushCommands { set(context, brush).setSize(radius); } - @Command(name = "surface", - aliases = { "surf" }, - desc = "Use a height map to paint a surface", - descFooter = "Use a height map to paint any surface.\n" - + "The -w flag will only apply at maximum saturation\n" - + "The -r flag will apply random rotation") + @Command( + name = "surface", + aliases = { "surf" }, + desc = "Use a height map to paint a surface", + descFooter = "Use a height map to paint any surface." + ) @CommandPermissions("worldedit.brush.surface") public void surfaceBrush(InjectedValueAccess context, - @Arg(desc = "Pattern") Pattern fill, @Arg(desc = "Expression", - def = "5") Expression radius) - throws WorldEditException { + @Arg(desc = "Pattern") + Pattern fill, + @Arg(desc = "Expression", def = "5") + Expression radius) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new SurfaceSphereBrush()).setFill(fill).setSize(radius); } - @Command(name = "scatter", - desc = "Scatter a pattern on a surface", - descFooter = - "Set a number of blocks randomly on a surface each a certain distance apart.\n" - + "Video: https://youtu.be/RPZIaTbqoZw?t=34s") + @Command( + name = "scatter", + desc = "Scatter a pattern on a surface", + descFooter = + "Set a number of blocks randomly on a surface each a certain distance apart.\n" + + "Video: https://youtu.be/RPZIaTbqoZw?t=34s" + ) @CommandPermissions("worldedit.brush.scatter") public void scatterBrush(InjectedValueAccess context, - @Arg(desc = "Pattern") Pattern fill, @Arg(desc = "radius", - def = "5") Expression radius, - @Arg(desc = "points", - def = "5") double points, @Arg(desc = "distance", - def = "1") double distance, @Switch(name = 'o', - desc = "Overlay the block") - boolean overlay) throws WorldEditException { + @Arg(desc = "Pattern") + Pattern fill, + @Arg(desc = "radius", def = "5") + Expression radius, + @Arg(desc = "points", def = "5") + double points, + @Arg(desc = "distance", def = "1") + double distance, + @Switch(name = 'o', desc = "Overlay the block") + boolean overlay) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); Brush brush; if (overlay) { @@ -518,23 +581,28 @@ public class BrushCommands { set(context, brush).setSize(radius).setFill(fill); } - @Command(name = "populateschematic", - aliases = { - "populateschem", - "popschem", - "pschem", - "ps" - }, - desc = "Scatter a schematic on a surface") + @Command( + name = "populateschematic", + aliases = { + "populateschem", + "popschem", + "pschem", + "ps" + }, + desc = "Scatter a schematic on a surface" + ) @CommandPermissions("worldedit.brush.populateschematic") public void scatterSchemBrush(Player player, InjectedValueAccess context, - @Arg(desc = "Mask") Mask mask, @Arg(name = "clipboard", - desc = "Clipboard uri") String clipboardStr, - @Arg(desc = "Expression", - def = "30") Expression radius, @Arg(desc = "double", - def = "50") double density, @Switch(name = 'r', - desc = "Apply random rotation") - boolean rotate) throws WorldEditException { + @Arg(desc = "Mask") + Mask mask, + @Arg(name = "clipboard", desc = "Clipboard uri") + String clipboardStr, + @Arg(desc = "Expression", def = "30") + Expression radius, + @Arg(desc = "double", def = "50") + double density, + @Switch(name = 'r', desc = "Apply random rotation") + boolean rotate) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); try { MultiClipboardHolder clipboards = @@ -555,55 +623,68 @@ public class BrushCommands { } } - @Command(name = "layer", - desc = "Replaces terrain with a layer.", - descFooter = "Replaces terrain with a layer.\n" - + "Example: /br layer 5 95:1 95:2 35:15 - Places several layers on a surface\n" - + "Pic: https://i.imgur.com/XV0vYoX.png") + @Command( + name = "layer", + desc = "Replaces terrain with a layer.", + descFooter = "Replaces terrain with a layer.\n" + + "Example: /br layer oak_planks orange_stained_glass magenta_stained_glass black_wool - Places several layers on a surface\n" + + "Pic: https://i.imgur.com/XV0vYoX.png" + ) @CommandPermissions("worldedit.brush.layer") public void surfaceLayer(InjectedValueAccess context, - @Arg(desc = "Expression") Expression radius, List blockLayers) + @Arg(desc = "Expression") + Expression radius, List blockLayers) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new LayerBrush(blockLayers.toArray(new BlockState[0]))).setSize(radius); } - @Command(name = "splatter", - desc = "Splatter a pattern on a surface", - descFooter = "Sets a bunch of blocks randomly on a surface.\n" - + "Pic: https://i.imgur.com/hMD29oO.png\n" - + "Example: /br splatter stone,dirt 30 15\n" - + "Note: The seeds define how many splotches there are, recursion defines how large, solid defines whether the pattern is applied per seed, else per block.") + @Command( + name = "splatter", + desc = "Splatter a pattern on a surface", + descFooter = "Sets a bunch of blocks randomly on a surface.\n" + + "Pic: https://i.imgur.com/hMD29oO.png\n" + + "Example: /br splatter stone,dirt 30 15\n" + + "Note: The seeds define how many splotches there are, recursion defines how large, " + + "solid defines whether the pattern is applied per seed, else per block." + ) @CommandPermissions("worldedit.brush.splatter") public void splatterBrush(InjectedValueAccess context, - @Arg(desc = "Pattern") Pattern fill, @Arg(desc = "Expression", - def = "5") Expression radius, - @Arg(desc = "double", - def = "1") double points, @Arg(desc = "double", - def = "5") double recursion, @Arg(desc = "boolean", - def = "true") - boolean solid) throws WorldEditException { + @Arg(desc = "Pattern") + Pattern fill, + @Arg(desc = "Expression", def = "5") + Expression radius, + @Arg(desc = "double", def = "1") + double points, + @Arg(desc = "double", def = "5") + double recursion, + @Arg(desc = "boolean", def = "true") + boolean solid) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new SplatterBrush((int) points, (int) recursion, solid)).setSize(radius) .setFill(fill); } - @Command(name = "scattercommand", - aliases = { - "scattercmd", - "scmd", - "scommand" - }, - desc = "Run commands at random points on a surface", - descFooter = "Run commands at random points on a surface\n" - + " - Your selection will be expanded to the specified size around each point\n" - + " - Placeholders: {x}, {y}, {z}, {world}, {size}") + @Command( + name = "scattercommand", + aliases = { + "scattercmd", + "scmd", + "scommand" + }, + desc = "Run commands at random points on a surface", + descFooter = "Run commands at random points on a surface\n" + + " - Your selection will be expanded to the specified size around each point\n" + + " - Placeholders: {x}, {y}, {z}, {world}, {size}" + ) @CommandPermissions("worldedit.brush.scattercommand") public void scatterCommandBrush(Player player, InjectedValueAccess context, - @Arg(desc = "The minimum distance between each point") Expression radius, - @Arg(desc = "double", - def = "1") double points, @Arg(desc = "double", - def = "1") double distance, List commandStr) + @Arg(desc = "The minimum distance between each point") + Expression radius, + @Arg(desc = "double", def = "1") + double points, + @Arg(desc = "double", def = "1") + double distance, List commandStr) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, @@ -611,20 +692,21 @@ public class BrushCommands { .setSize(radius); } - @Command(name = "cylinder", - aliases = { - "cyl", - "c" - }, - desc = "Choose the cylinder brush") + @Command( + name = "cylinder", + aliases = { "cyl", "c" }, + desc = "Choose the cylinder brush" + ) @CommandPermissions("worldedit.brush.cylinder") public void cylinderBrush(InjectedValueAccess context, - @Arg(desc = "The pattern of blocks to set") Pattern pattern, - @Arg(desc = "The radius of the cylinder", - def = "2") Expression radius, @Arg(desc = "The height of the cylinder", - def = "1") int height, @Switch(name = 'h', - desc = "Create hollow cylinders instead") - boolean hollow) throws WorldEditException { + @Arg(desc = "The pattern of blocks to set") + Pattern pattern, + @Arg(desc = "The radius of the cylinder", def = "2") + Expression radius, + @Arg(desc = "The height of the cylinder", def = "1") + int height, + @Switch(name = 'h', desc = "Create hollow cylinders instead") + boolean hollow) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); worldEdit.checkMaxBrushRadius(height); @@ -637,24 +719,28 @@ public class BrushCommands { settings.setSize(radius).setFill(pattern); } - @Command(name = "clipboard", - desc = "@Deprecated use instead: `/br copypaste`)", - descFooter = "Choose the clipboard brush.\n" - + "Without the -p flag, the paste will appear centered at the target location. " - + "With the flag, then the paste will appear relative to where you had " - + "stood relative to the copied area when you copied it.") + @Command( + name = "clipboard", + desc = "@Deprecated use instead: `/br copypaste`)", + descFooter = "Choose the clipboard brush.\n" + + "Without the -p flag, the paste will appear centered at the target location. " + + "With the flag, then the paste will appear relative to where you had " + + "stood relative to the copied area when you copied it." + ) @Deprecated @CommandPermissions("worldedit.brush.clipboard") - public void clipboardBrush(Player player, LocalSession session, @Switch(name = 'a', - desc = "Don't paste air from the clipboard") - boolean ignoreAir, @Switch(name = 'o', - desc = "Paste starting at the target location, instead of centering on it") - boolean usingOrigin, @Switch(name = 'e', - desc = "Paste entities if available") boolean pasteEntities, - @Switch(name = 'b', - desc = "Paste biomes if available") boolean pasteBiomes, @ArgFlag(name = 'm', - desc = "Skip blocks matching this mask in the clipboard") - @ClipboardMask Mask sourceMask, InjectedValueAccess context) throws WorldEditException { + public void clipboardBrush(Player player, LocalSession session, + @Switch(name = 'a', desc = "Don't paste air from the clipboard") + boolean ignoreAir, + @Switch(name = 'o', desc = "Paste starting at the target location, instead of centering on it") + boolean usingOrigin, + @Switch(name = 'e', desc = "Paste entities if available") + boolean pasteEntities, + @Switch(name = 'b', desc = "Paste biomes if available") + boolean pasteBiomes, + @ArgFlag(name = 'm', desc = "Skip blocks matching this mask in the clipboard") + @ClipboardMask + Mask sourceMask, InjectedValueAccess context) throws WorldEditException { ClipboardHolder holder = session.getClipboard(); Clipboard clipboard = holder.getClipboard(); @@ -672,16 +758,20 @@ public class BrushCommands { sourceMask)); } - @Command(name = "smooth", - desc = "Choose the terrain softener brush", - descFooter = "Example: '/brush smooth 2 4 grass_block,dirt,stone'") + @Command( + name = "smooth", + desc = "Choose the terrain softener brush", + descFooter = "Example: '/brush smooth 2 4 grass_block,dirt,stone'" + ) @CommandPermissions("worldedit.brush.smooth") public void smoothBrush(Player player, LocalSession session, - @Arg(desc = "The radius to sample for softening", - def = "2") Expression radius, @Arg(desc = "The number of iterations to perform", - def = "4") int iterations, - @Arg(desc = "The mask of blocks to use for the heightmap", - def = "") Mask maskOpt, InjectedValueAccess context) throws WorldEditException { + @Arg(desc = "The radius to sample for softening", def = "2") + Expression radius, + @Arg(desc = "The number of iterations to perform", def = "4") + int iterations, + @Arg(desc = "The mask of blocks to use for the heightmap", def = "") + Mask maskOpt, + InjectedValueAccess context) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); FaweLimit limit = Settings.IMP.getLimit(player); @@ -690,104 +780,122 @@ public class BrushCommands { set(context, new SmoothBrush(iterations, maskOpt)).setSize(radius); } - @Command(name = "extinguish", - aliases = { "ex" }, - desc = "Shortcut fire extinguisher brush") + @Command( + name = "extinguish", + aliases = { "ex" }, + desc = "Shortcut fire extinguisher brush" + ) @CommandPermissions("worldedit.brush.ex") public void extinguishBrush(InjectedValueAccess context, EditSession editSession, - @Arg(desc = "The radius to extinguish", - def = "5") Expression radius) throws WorldEditException { + @Arg(desc = "The radius to extinguish", def = "5") + Expression radius) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new SphereBrush()).setSize(radius).setFill(BlockTypes.AIR.getDefaultState()) .setMask(new SingleBlockTypeMask(editSession, BlockTypes.FIRE)); } - @Command(name = "gravity", - aliases = { "grav" }, - desc = "Gravity brush, simulates the effect of gravity") + @Command( + name = "gravity", + aliases = { "grav" }, + desc = "Gravity brush, simulates the effect of gravity" + ) @CommandPermissions("worldedit.brush.gravity") public void gravityBrush(InjectedValueAccess context, - @Arg(desc = "The radius to apply gravity in", - def = "5") Expression radius, @Switch(name = 'h', - desc = "Affect blocks starting at max Y, rather than the target location Y + radius") - boolean fromMaxY) throws WorldEditException { + @Arg(desc = "The radius to apply gravity in", def = "5") + Expression radius, + @Switch(name = 'h', desc = "Affect blocks starting at max Y, rather than the target location Y + radius") + boolean fromMaxY) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); set(context, new GravityBrush(fromMaxY)).setSize(radius); } - @Command(name = "height", - aliases = { "heightmap" }, - desc = "Raise or lower terrain using a heightmap", - descFooter = "This brush raises and lowers land.\n" - + " - The `-r` flag enables random off-axis rotation\n" - + " - The `-l` flag will work on snow layers\n" - + " - The `-s` flag disables smoothing\n" - + "Note: Use a negative yscale to reduce height\n" - + "Snow Pic: https://i.imgur.com/Hrzn0I4.png") + @Command( + name = "height", + aliases = { "heightmap" }, + desc = "Raise or lower terrain using a heightmap", + descFooter = "This brush raises and lowers land.\n" + + "Note: Use a negative yscale to reduce height\n" + + "Snow Pic: https://i.imgur.com/Hrzn0I4.png" + ) @CommandPermissions("worldedit.brush.height") - public void heightBrush(LocalSession session, @Arg(desc = "Expression", - def = "5") Expression radius, - @Arg(desc = "String", - def = "") String image, @Arg(def = "0", - desc = "rotation") @Range(from = 0, - to = 360) int rotation, - @Arg(desc = "double", - def = "1") double yscale, @Switch(name = 'r', - desc = "TODO") boolean randomRotate, - @Switch(name = 'l', - desc = "TODO") boolean layers, @Switch(name = 's', - desc = "TODO") - boolean dontSmooth, InjectedValueAccess context) + public void heightBrush(LocalSession session, + @Arg(desc = "Expression", def = "5") + Expression radius, + @Arg(desc = "String", def = "") + String image, + @Arg(def = "0", desc = "rotation") + @Range(from = 0, to = 360) + int rotation, + @Arg(desc = "double", def = "1") + double yscale, + @Switch(name = 'r', desc = "Random off-axis rotation") + boolean randomRotate, + @Switch(name = 'l', desc = "Work on snow layers") + boolean layers, + @Switch(name = 's', desc = "Disable smoothing") + boolean dontSmooth, InjectedValueAccess context) throws WorldEditException, FileNotFoundException { terrainBrush(session, radius, image, rotation, yscale, false, randomRotate, layers, !dontSmooth, ScalableHeightMap.Shape.CONE, context); } - @Command(name = "cliff", - aliases = { "flatcylinder" }, - desc = "Cliff brush", - descFooter = "This brush flattens terrain and creates cliffs.") + @Command( + name = "cliff", + aliases = { "flatcylinder" }, + desc = "Cliff brush", + descFooter = "This brush flattens terrain and creates cliffs." + ) @CommandPermissions("worldedit.brush.height") - public void cliffBrush(LocalSession session, @Arg(desc = "Expression", - def = "5") Expression radius, - @Arg(desc = "String", - def = "") String image, @Arg(def = "0", - desc = "rotation") @Step(90) @Range(from = 0, - to = 360) int rotation, - @Arg(desc = "double", - def = "1") double yscale, @Switch(name = 'r', - desc = "Enables random off-axis rotation") - boolean randomRotate, @Switch(name = 'l', - desc = "Will work on snow layers") boolean layers, - @Switch(name = 's', - desc = "Disables smoothing") boolean dontSmooth, InjectedValueAccess context) + public void cliffBrush(LocalSession session, + @Arg(desc = "Expression", def = "5") + Expression radius, + @Arg(desc = "String", def = "") + String image, + @Arg(def = "0", desc = "rotation") + @Step(90) + @Range(from = 0, to = 360) + int rotation, + @Arg(desc = "double", def = "1") + double yscale, + @Switch(name = 'r', desc = "Enables random off-axis rotation") + boolean randomRotate, + @Switch(name = 'l', desc = "Will work on snow layers") + boolean layers, + @Switch(name = 's', desc = "Disables smoothing") + boolean dontSmooth, InjectedValueAccess context) throws WorldEditException, FileNotFoundException { terrainBrush(session, radius, image, rotation, yscale, true, randomRotate, layers, !dontSmooth, ScalableHeightMap.Shape.CYLINDER, context); } - @Command(name = "flatten", - aliases = { - "flatmap", - "flat" - }, - desc = "This brush raises or lowers land towards the clicked point") + @Command( + name = "flatten", + aliases = { + "flatmap", + "flat" + }, + desc = "This brush raises or lowers land towards the clicked point" + ) @CommandPermissions("worldedit.brush.height") - public void flattenBrush(LocalSession session, @Arg(desc = "Expression", - def = "5") Expression radius, - @Arg(desc = "String", - def = "") String image, @Arg(def = "0", - desc = "rotation") @Step(90) @Range(from = 0, - to = 360) int rotation, - @Arg(desc = "double", - def = "1") double yscale, @Switch(name = 'r', - desc = "Enables random off-axis rotation") - boolean randomRotate, @Switch(name = 'l', - desc = "Will work on snow layers") boolean layers, - @Switch(name = 's', - desc = "Disables smoothing") boolean dontSmooth, InjectedValueAccess context) + public void flattenBrush(LocalSession session, + @Arg(desc = "Expression", def = "5") + Expression radius, + @Arg(desc = "String", def = "") + String image, + @Arg(def = "0", desc = "rotation") + @Step(90) + @Range(from = 0, to = 360) + int rotation, + @Arg(desc = "double", def = "1") + double yscale, + @Switch(name = 'r', desc = "Enables random off-axis rotation") + boolean randomRotate, + @Switch(name = 'l', desc = "Will work on snow layers") + boolean layers, + @Switch(name = 's', desc = "Disables smoothing") + boolean dontSmooth, InjectedValueAccess context) throws WorldEditException, FileNotFoundException { terrainBrush(session, radius, image, rotation, yscale, true, randomRotate, layers, !dontSmooth, ScalableHeightMap.Shape.CONE, context); @@ -801,19 +909,17 @@ public class BrushCommands { if (flat) { try { brush = new FlattenBrush(stream, rotation, yscale, layers, smooth, - "#clipboard".equalsIgnoreCase(image) ? - session.getClipboard().getClipboard() : - null, shape); - } catch (EmptyClipboardException ignore) { + "#clipboard".equalsIgnoreCase(image) + ? session.getClipboard().getClipboard() : null, shape); + } catch (EmptyClipboardException ignored) { brush = new FlattenBrush(stream, rotation, yscale, layers, smooth, null, shape); } } else { try { brush = new HeightBrush(stream, rotation, yscale, layers, smooth, - "#clipboard".equalsIgnoreCase(image) ? - session.getClipboard().getClipboard() : - null); - } catch (EmptyClipboardException ignore) { + "#clipboard".equalsIgnoreCase(image) + ? session.getClipboard().getClipboard() : null); + } catch (EmptyClipboardException ignored) { brush = new HeightBrush(stream, rotation, yscale, layers, smooth, null); } } @@ -838,67 +944,75 @@ public class BrushCommands { } - @Command(name = "copypaste", - aliases = { - "cp", - "copypasta" - }, - desc = "Copy Paste brush", - descFooter = "Left click the base of an object to copy.\n" + "Right click to paste\n" - + "Note: Works well with the clipboard scroll action\n" - + "Video: https://www.youtube.com/watch?v=RPZIaTbqoZw") + @Command( + name = "copypaste", + aliases = { + "cp", + "copypasta" + }, + desc = "Copy Paste brush", + descFooter = "Left click the base of an object to copy.\n" + "Right click to paste\n" + + "Note: Works well with the clipboard scroll action\n" + + "Video: https://www.youtube.com/watch?v=RPZIaTbqoZw" + ) @CommandPermissions("worldedit.brush.copy") public void copy(Player player, LocalSession session, InjectedValueAccess context, - @Arg(desc = "Expression", - def = "5") Expression radius, @Switch(name = 'r', - desc = "Apply random rotation on paste") - boolean randomRotate, @Switch(name = 'a', - desc = "Apply auto view based rotation on paste") - boolean autoRotate) throws WorldEditException { + @Arg(desc = "Expression", def = "5") + Expression radius, + @Switch(name = 'r', desc = "Apply random rotation on paste") + boolean randomRotate, + @Switch(name = 'a', desc = "Apply auto view based rotation on paste") + boolean autoRotate) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); player.print(Caption.of("fawe.worldedit.brush.brush.copy", (radius))); set(context, new CopyPastaBrush(player, session, randomRotate, autoRotate)).setSize(radius); } - @Command(name = "command", - aliases = { "cmd" }, - desc = "Command brush", - descFooter = "Run the commands at the clicked position.\n" - + " - Your selection will be expanded to the specified size around each point\n" - + " - Placeholders: {x}, {y}, {z}, {world}, {size}") + @Command( + name = "command", + aliases = { "cmd" }, + desc = "Command brush", + descFooter = "Run the commands at the clicked position.\n" + + " - Your selection will be expanded to the specified size around each point\n" + + " - Placeholders: {x}, {y}, {z}, {world}, {size}" + ) @CommandPermissions("worldedit.brush.command") public void command(InjectedValueAccess context, - @Arg(desc = "Expression") Expression radius, - @Arg(desc = "Command to run") List input) throws WorldEditException { + @Arg(desc = "Expression") + Expression radius, + @Arg(desc = "Command to run") + List input) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); String cmd = StringMan.join(input, " "); set(context, new CommandBrush(cmd)).setSize(radius); } - @Command(name = "butcher", - aliases = { "kill" }, - desc = "Butcher brush, kills mobs within a radius") + @Command( + name = "butcher", + aliases = { "kill" }, + desc = "Butcher brush, kills mobs within a radius" + ) @CommandPermissions("worldedit.brush.butcher") public void butcherBrush(Player player, LocalSession session, - @Arg(desc = "Radius to kill mobs in", def = "5") - Expression radius, - @Switch(name = 'p', desc = "Also kill pets") - boolean killPets, - @Switch(name = 'n', desc = "Also kill NPCs") - boolean killNpcs, - @Switch(name = 'g', desc = "Also kill golems") - boolean killGolems, - @Switch(name = 'a', desc = "Also kill animals") - boolean killAnimals, - @Switch(name = 'b', desc = "Also kill ambient mobs") - boolean killAmbient, - @Switch(name = 't', desc = "Also kill mobs with name tags") - boolean killWithName, - @Switch(name = 'f', desc = "Also kill all friendly mobs (Applies the flags `-abgnpt`)") - boolean killFriendly, - @Switch(name = 'r', desc = "Also destroy armor stands") - boolean killArmorStands, InjectedValueAccess context) throws WorldEditException { + @Arg(desc = "Radius to kill mobs in", def = "5") + Expression radius, + @Switch(name = 'p', desc = "Also kill pets") + boolean killPets, + @Switch(name = 'n', desc = "Also kill NPCs") + boolean killNpcs, + @Switch(name = 'g', desc = "Also kill golems") + boolean killGolems, + @Switch(name = 'a', desc = "Also kill animals") + boolean killAnimals, + @Switch(name = 'b', desc = "Also kill ambient mobs") + boolean killAmbient, + @Switch(name = 't', desc = "Also kill mobs with name tags") + boolean killWithName, + @Switch(name = 'f', desc = "Also kill all friendly mobs (Applies the flags `-abgnpt`)") + boolean killFriendly, + @Switch(name = 'r', desc = "Also destroy armor stands") + boolean killArmorStands, InjectedValueAccess context) throws WorldEditException { worldEdit.checkMaxBrushRadius(radius); CreatureButcher flags = new CreatureButcher(player); @@ -909,8 +1023,7 @@ public class BrushCommands { flags.or(CreatureButcher.Flags.ANIMALS, killAnimals, "worldedit.butcher.animals"); flags.or(CreatureButcher.Flags.AMBIENT, killAmbient, "worldedit.butcher.ambient"); flags.or(CreatureButcher.Flags.TAGGED, killWithName, "worldedit.butcher.tagged"); - flags.or(CreatureButcher.Flags.ARMOR_STAND, killArmorStands, - "worldedit.butcher.armorstands"); + flags.or(CreatureButcher.Flags.ARMOR_STAND, killArmorStands, "worldedit.butcher.armorstands"); set(context, new ButcherBrush(flags)).setSize(radius); } @@ -960,14 +1073,17 @@ public class BrushCommands { return process(player, arguments, bs); } - @Command(name = "savebrush", - aliases = { "save" }, - desc = "Save your current brush") + @Command( + name = "savebrush", + aliases = { "save" }, + desc = "Save your current brush" + ) @CommandPermissions("worldedit.brush.save") public void saveBrush(Player player, LocalSession session, - @Arg(desc = "String name") String name, @Switch(name = 'g', - desc = "Save the brush globally") - boolean root) throws WorldEditException, IOException { + @Arg(desc = "String name") + String name, + @Switch(name = 'g', desc = "Save the brush globally") + boolean root) throws WorldEditException, IOException { BrushTool tool = session.getBrushTool(player); if (tool != null) { root |= name.startsWith("../"); @@ -997,48 +1113,48 @@ public class BrushCommands { } } - // TODO: Ping @MattBDev to reimplement 2020-02-04 - // @Command( - // name = "loadbrush", - // aliases = {"load"}, - // desc = "Load a brush" - // ) - // @CommandPermissions("worldedit.brush.load") - // public void loadBrush(Player player, LocalSession session, @Arg(desc = "String name") String name) - // throws WorldEditException, IOException { - // name = FileSystems.getDefault().getPath(name).getFileName().toString(); - // File folder = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes"); - // name = name.endsWith(".jsgz") ? name : name + ".jsgz"; - // File file = new File(folder, player.getUniqueId() + File.separator + name); - // if (!file.exists()) { - // file = new File(folder, name); - // } - // if (!file.exists()) { - // File[] files = folder.listFiles(pathname -> false); - // player.print(Caption.of("fawe.error.brush.not.found" , name)); - // return; - // } - // try (DataInputStream in = new DataInputStream( - // new GZIPInputStream(new FileInputStream(file)))) { - // String json = in.readUTF(); - // BrushTool tool = BrushTool.fromString(player, session, json); - // BaseItem item = player.getItemInHand(HandSide.MAIN_HAND); - // session.setTool(item, tool, player); - // player.print(Caption.of("fawe.worldedit.brush.brush.equipped" , name)); - // } catch (Throwable e) { - // e.printStackTrace(); - // player.printError(TranslatableComponent.of("fawe.error.brush.incompatible")); - // } - // } + // TODO: Write a Brush standard format. + /* @Command( + name = "loadbrush", + aliases = {"load"}, + desc = "Load a brush" + ) + @CommandPermissions("worldedit.brush.load") + public void loadBrush(Player player, LocalSession session, @Arg(desc = "String name") String name) + throws WorldEditException, IOException { + name = FileSystems.getDefault().getPath(name).getFileName().toString(); + File folder = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes"); + name = name.endsWith(".jsgz") ? name : name + ".jsgz"; + File file = new File(folder, player.getUniqueId() + File.separator + name); + if (!file.exists()) { + file = new File(folder, name); + } + if (!file.exists()) { + File[] files = folder.listFiles(pathname -> false); + player.print(Caption.of("fawe.error.brush.not.found", name)); + return; + } + try (DataInputStream in = new DataInputStream( + new GZIPInputStream(new FileInputStream(file)))) { + String json = in.readUTF(); + BrushTool tool = BrushTool.fromString(player, session, json); + BaseItem item = player.getItemInHand(HandSide.MAIN_HAND); + session.setTool(item, tool, player); + player.print(Caption.of("fawe.worldedit.brush.brush.equipped", name)); + } catch (Throwable e) { + e.printStackTrace(); + player.printError(TranslatableComponent.of("fawe.error.brush.incompatible")); + } + } */ - @Command(name = "/listbrush", - desc = "List saved brushes", - descFooter = "List all brushes in the brush directory") + @Command( + name = "/listbrush", + desc = "List saved brushes", + descFooter = "List all brushes in the brush directory") @CommandPermissions("worldedit.brush.list") - public void list(Actor actor, InjectedValueAccess args, @ArgFlag(name = 'p', - desc = "Prints the requested page", - def = "0") int page) - throws WorldEditException { + public void list(Actor actor, InjectedValueAccess args, + @ArgFlag(name = 'p', desc = "Prints the requested page", def = "0") + int page) throws WorldEditException { String baseCmd = "/brush loadbrush"; File dir = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes"); // TODO NOT IMPLEMENTED @@ -1056,19 +1172,22 @@ public class BrushCommands { player.print(TextComponent.of("Set brush to " + factory)); } - @Command(name = "deform", - desc = "Deform brush, applies an expression to an area") + @Command( + name = "deform", + desc = "Deform brush, applies an expression to an area" + ) @CommandPermissions("worldedit.brush.deform") public void deform(Player player, LocalSession localSession, - @Arg(desc = "The shape of the region") RegionFactory shape, - @Arg(desc = "The size of the brush", - def = "5") - double radius, @Arg(desc = "Expression to apply", - def = "y-=0.2") String expression, @Switch(name = 'r', - desc = "Use the game's coordinate origin") - boolean useRawCoords, - @Switch(name = 'o', desc = "Use the placement position as the origin") - boolean usePlacement) throws WorldEditException { + @Arg(desc = "The shape of the region") + RegionFactory shape, + @Arg(desc = "The size of the brush", def = "5") + double radius, + @Arg(desc = "Expression to apply", def = "y-=0.2") + String expression, + @Switch(name = 'r', desc = "Use the game's coordinate origin") + boolean useRawCoords, + @Switch(name = 'o', desc = "Use the placement position as the origin") + boolean usePlacement) throws WorldEditException { Deform deform = new Deform(expression); if (useRawCoords) { deform.setMode(Deform.Mode.RAW_COORD); @@ -1086,12 +1205,12 @@ public class BrushCommands { ) @CommandPermissions("worldedit.brush.set") public void set(Player player, LocalSession localSession, - @Arg(desc = "The shape of the region") - RegionFactory shape, - @Arg(desc = "The size of the brush", def = "5") - Expression radius, - @Arg(desc = "The pattern of blocks to set") - Pattern pattern) throws WorldEditException { + @Arg(desc = "The shape of the region") + RegionFactory shape, + @Arg(desc = "The size of the brush", def = "5") + Expression radius, + @Arg(desc = "The pattern of blocks to set") + Pattern pattern) throws WorldEditException { setOperationBasedBrush(player, localSession, radius, new Apply(new ReplaceFactory(pattern)), shape, "worldedit.brush.set"); } @@ -1102,14 +1221,14 @@ public class BrushCommands { ) @CommandPermissions("worldedit.brush.forest") public void forest(Player player, LocalSession localSession, - @Arg(desc = "The shape of the region") - RegionFactory shape, - @Arg(desc = "The size of the brush", def = "5") - Expression radius, - @Arg(desc = "The density of the brush", def = "20") - double density, - @Arg(desc = "The type of tree to use") - TreeGenerator.TreeType type) throws WorldEditException { + @Arg(desc = "The shape of the region") + RegionFactory shape, + @Arg(desc = "The size of the brush", def = "5") + Expression radius, + @Arg(desc = "The density of the brush", def = "20") + double density, + @Arg(desc = "The type of tree to use") + TreeGenerator.TreeType type) throws WorldEditException { setOperationBasedBrush(player, localSession, radius, new Paint(new TreeGeneratorFactory(type), density / 100), shape, "worldedit.brush.forest"); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ClipboardCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ClipboardCommands.java index f0a372372..1b324914d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ClipboardCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ClipboardCommands.java @@ -133,7 +133,7 @@ public class ClipboardCommands { session.setClipboard(null); Clipboard clipboard = new BlockArrayClipboard(region, actor.getUniqueId()); - + clipboard.setOrigin(centerClipboard ? region.getCenter().toBlockPoint() : session.getPlacementPosition(actor)); ForwardExtentCopy copy = new ForwardExtentCopy(editSession, region, clipboard, region.getMinimumPoint()); copy.setCopyingEntities(copyEntities); @@ -156,16 +156,15 @@ public class ClipboardCommands { } @Command( - name = "/lazycopy", - desc = "Lazily copy the selection to the clipboard" + name = "/lazycopy", + desc = "Lazily copy the selection to the clipboard" ) @CommandPermissions("worldedit.clipboard.lazycopy") - public void lazyCopy(Actor actor, LocalSession session, EditSession editSession, - @Selection Region region, + public void lazyCopy(Actor actor, LocalSession session, EditSession editSession, @Selection Region region, @Switch(name = 'e', desc = "Skip copy entities") - boolean skipEntities, + boolean skipEntities, @Switch(name = 'b', desc = "Also copy biomes") - boolean copyBiomes) throws WorldEditException { + boolean copyBiomes) throws WorldEditException { BlockVector3 min = region.getMinimumPoint(); BlockVector3 max = region.getMaximumPoint(); long volume = (((long) max.getX() - (long) min.getX() + 1) * ((long) max.getY() - (long) min.getY() + 1) * ((long) max.getZ() - (long) min.getZ() + 1)); @@ -178,39 +177,40 @@ public class ClipboardCommands { lazyClipboard.setOrigin(session.getPlacementPosition(actor)); session.setClipboard(new ClipboardHolder(lazyClipboard)); - actor.print(Caption.of("fawe.worldedit.copy.command.copy" , region.getVolume())); + actor.print(Caption.of("fawe.worldedit.copy.command.copy", region.getVolume())); } -// @Command( -// name = "/lazycut", -// desc = "Lazily cut the selection to the clipboard" -// ) -// @CommandPermissions("worldedit.clipboard.lazycut") -// public void lazyCut(Actor actor, LocalSession session, EditSession editSession, -// @Selection final Region region, -// @Switch(name = 'e', desc = "Skip copy entities") -// boolean skipEntities, -// @ArgFlag(name = 'm', desc = "Set the exclude mask, matching blocks become air", def = "") -// Mask maskOpt, -// @Switch(name = 'b', desc = "Also copy biomes") -// boolean copyBiomes) throws WorldEditException { -// BlockVector3 min = region.getMinimumPoint(); -// BlockVector3 max = region.getMaximumPoint(); -// long volume = ((long) max.getX() - (long) min.getX() + 1) * ((long) max.getY() - (long) min.getY() + 1) * ((long) max.getZ() - (long) min.getZ() + 1); -// FaweLimit limit = actor.getLimit(); -// if (volume >= limit.MAX_CHECKS) { -// throw FaweCache.MAX_CHECKS; -// } -// if (volume >= limit.MAX_CHANGES) { -// throw FaweCache.MAX_CHANGES; -// } -// session.setClipboard(null); -// -// ReadOnlyClipboard lazyClipboard = new WorldCutClipboard(editSession, region, !skipEntities, copyBiomes); -// clipboard.setOrigin(session.getPlacementPosition(actor)); -// session.setClipboard(new ClipboardHolder(lazyClipboard)); -// actor.print(TranslatableComponent.of("fawe.worldedit.cut.command.cut.lazy" , region.getArea())); -// } + /* + @Command( + name = "/lazycut", + desc = "Lazily cut the selection to the clipboard" + ) + @CommandPermissions("worldedit.clipboard.lazycut") + public void lazyCut(Actor actor, LocalSession session, EditSession editSession, + @Selection final Region region, + @Switch(name = 'e', desc = "Skip copy entities") + boolean skipEntities, + @ArgFlag(name = 'm', desc = "Set the exclude mask, matching blocks become air", def = "") + Mask maskOpt, + @Switch(name = 'b', desc = "Also copy biomes") + boolean copyBiomes) throws WorldEditException { + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); + long volume = ((long) max.getX() - (long) min.getX() + 1) * ((long) max.getY() - (long) min.getY() + 1) * ((long) max.getZ() - (long) min.getZ() + 1); + FaweLimit limit = actor.getLimit(); + if (volume >= limit.MAX_CHECKS) { + throw FaweCache.MAX_CHECKS; + } + if (volume >= limit.MAX_CHANGES) { + throw FaweCache.MAX_CHANGES; + } + session.setClipboard(null); + + ReadOnlyClipboard lazyClipboard = new WorldCutClipboard(editSession, region, !skipEntities, copyBiomes); + clipboard.setOrigin(session.getPlacementPosition(actor)); + session.setClipboard(new ClipboardHolder(lazyClipboard)); + actor.print(TranslatableComponent.of("fawe.worldedit.cut.command.cut.lazy", region.getArea())); + }*/ @Command( name = "/cut", @@ -267,24 +267,24 @@ public class ClipboardCommands { if (!actor.hasPermission("fawe.tips")) { actor.print(TranslatableComponent.of("fawe.tips.tip.lazycut")); } - copy.getStatusMessages().forEach(actor::print); + copy.getStatusMessages().forEach(actor::print); } @Command( - name = "download", - aliases = { "/download" }, - desc = "Downloads your clipboard through the configured web interface" + name = "download", + aliases = { "/download" }, + desc = "Downloads your clipboard through the configured web interface" ) @Deprecated @CommandPermissions({"worldedit.clipboard.download"}) public void download(final Player player, final LocalSession session, @Arg(name = "format", desc = "String", def = "schem") final String formatName) throws WorldEditException { final ClipboardFormat format = ClipboardFormats.findByAlias(formatName); if (format == null) { - player.print(Caption.of("fawe.worldedit.clipboard.clipboard.invalid.format" , formatName)); + player.print(Caption.of("fawe.worldedit.clipboard.clipboard.invalid.format", formatName)); return; } - player.print(Caption.of("fawe.web.generating.link" , formatName)); + player.print(Caption.of("fawe.web.generating.link", formatName)); ClipboardHolder holder = session.getClipboard(); URL url; @@ -370,7 +370,7 @@ public class ClipboardCommands { e.printStackTrace(); } } - player.print(Caption.of("fawe.web.download.link" , urlText).clickEvent(ClickEvent.openUrl(urlText))); + player.print(Caption.of("fawe.web.download.link", urlText).clickEvent(ClickEvent.openUrl(urlText))); } } @@ -412,9 +412,13 @@ public class ClipboardCommands { checkPaste(actor, editSession, to, holder, clipboard); if (!onlySelect) { - Operation operation = - holder.createPaste(editSession).to(to).ignoreAirBlocks(ignoreAirBlocks) - .copyBiomes(pasteBiomes).copyEntities(pasteEntities).maskSource(sourceMask) + Operation operation = holder + .createPaste(editSession) + .to(to) + .ignoreAirBlocks(ignoreAirBlocks) + .copyBiomes(pasteBiomes) + .copyEntities(pasteEntities) + .maskSource(sourceMask) .build(); Operations.completeLegacy(operation); messages.addAll(Lists.newArrayList(operation.getStatusMessages())); @@ -451,23 +455,22 @@ public class ClipboardCommands { } @Command( - name = "/place", - desc = "Place the clipboard's contents without applying transformations (e.g. rotate)" -) - + name = "/place", + desc = "Place the clipboard's contents without applying transformations (e.g. rotate)" + ) @CommandPermissions("worldedit.clipboard.place") @Logging(PLACEMENT) public void place(Actor actor, World world, LocalSession session, final EditSession editSession, @Switch(name = 'a', desc = "Skip air blocks") - boolean ignoreAirBlocks, + boolean ignoreAirBlocks, @Switch(name = 'o', desc = "Paste at the original position") - boolean atOrigin, + boolean atOrigin, @Switch(name = 's', desc = "Select the region after pasting") - boolean selectPasted, + boolean selectPasted, @Switch(name = 'e', desc = "Paste entities if available") - boolean pasteEntities, + boolean pasteEntities, @Switch(name = 'b', desc = "Paste biomes if available") - boolean pasteBiomes) throws WorldEditException { + boolean pasteBiomes) throws WorldEditException { ClipboardHolder holder = session.getClipboard(); final Clipboard clipboard = holder.getClipboard(); final BlockVector3 origin = clipboard.getOrigin(); @@ -486,7 +489,7 @@ public class ClipboardCommands { selector.learnChanges(); selector.explainRegionAdjust(actor, session); } - actor.print(Caption.of("fawe.worldedit.paste.command.paste" , to)); + actor.print(Caption.of("fawe.worldedit.paste.command.paste", to)); if (!actor.hasPermission("fawe.tips")) { actor.print(TranslatableComponent.of("fawe.tips.tip.copypaste")); @@ -496,23 +499,23 @@ public class ClipboardCommands { @Command( name = "/rotate", desc = "Rotate the contents of the clipboard", - descFooter = "Non-destructively rotate the contents of the clipboard.\n" + - "Angles are provided in degrees and a positive angle will result in a clockwise rotation. " + - "Multiple rotations can be stacked. Interpolation is not performed so angles should be a multiple of 90 degrees.\n" + descFooter = "Non-destructively rotate the contents of the clipboard.\n" + + "Angles are provided in degrees and a positive angle will result in a clockwise rotation. " + + "Multiple rotations can be stacked. Interpolation is not performed so angles should be a multiple of 90 degrees.\n" ) @CommandPermissions("worldedit.clipboard.rotate") public void rotate(Actor actor, LocalSession session, @Arg(desc = "Amount to rotate on the y-axis") - double yRotate, + double rotateY, @Arg(desc = "Amount to rotate on the x-axis", def = "0") - double xRotate, + double rotateX, @Arg(desc = "Amount to rotate on the z-axis", def = "0") - double zRotate) throws WorldEditException { + double rotateZ) throws WorldEditException { ClipboardHolder holder = session.getClipboard(); AffineTransform transform = new AffineTransform(); - transform = transform.rotateY(-yRotate); - transform = transform.rotateX(-xRotate); - transform = transform.rotateZ(-zRotate); + transform = transform.rotateY(-rotateY); + transform = transform.rotateX(-rotateX); + transform = transform.rotateZ(-rotateZ); holder.setTransform(holder.getTransform().combine(transform)); actor.printInfo(TranslatableComponent.of("worldedit.rotate.rotated")); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/FlattenedClipboardTransform.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/FlattenedClipboardTransform.java index bee404178..50eebbce4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/FlattenedClipboardTransform.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/FlattenedClipboardTransform.java @@ -113,7 +113,9 @@ public class FlattenedClipboardTransform { */ public Operation copyTo(Extent target) { Extent extent = original; - if (transform != null && !transform.isIdentity()) extent = new BlockTransformExtent(original, transform); + if (transform != null && !transform.isIdentity()) { + extent = new BlockTransformExtent(original, transform); + } ForwardExtentCopy copy = new ForwardExtentCopy(extent, original.getRegion(), original.getOrigin(), target, original.getOrigin()); copy.setTransform(transform); if (original.hasBiomes()) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/GeneralCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/GeneralCommands.java index 6068cf257..cbc0fcff1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/GeneralCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/GeneralCommands.java @@ -409,12 +409,18 @@ public class GeneralCommands { // complexity int min = Integer.parseInt(arguments.get(0)); int max = Integer.parseInt(arguments.get(1)); - if (min < 0 || max > 100) throw new InputParseException("Complexity must be in the range 0-100"); - if (min != 0 || max != 100) util = new CleanTextureUtil(util, min, max); + if (min < 0 || max > 100) { + throw new InputParseException("Complexity must be in the range 0-100"); + } + if (min != 0 || max != 100) { + util = new CleanTextureUtil(util, min, max); + } randomIndex = 2; } else if (arguments.size() == 1 && argLower.equals("true") || argLower.equals("false")) { - if (argLower.equals("true")) util = new RandomTextureUtil(util); + if (argLower.equals("true")) { + util = new RandomTextureUtil(util); + } checkRandomization = false; } else { if (argLower.equals("#copy") || argLower.equals("#clipboard")) { @@ -435,20 +441,24 @@ public class GeneralCommands { if (checkRandomization) { if (arguments.size() > randomIndex) { boolean random = Boolean.parseBoolean(arguments.get(randomIndex)); - if (random) util = new RandomTextureUtil(util); + if (random) { + util = new RandomTextureUtil(util); + } } } - if (!(util instanceof CachedTextureUtil)) util = new CachedTextureUtil(util); + if (!(util instanceof CachedTextureUtil)) { + util = new CachedTextureUtil(util); + } session.setTextureUtil(util); - player.print(Caption.of("fawe.worldedit.general.texture.set" , StringMan.join(arguments, " "))); + player.print(Caption.of("fawe.worldedit.general.texture.set", StringMan.join(arguments, " "))); } } @Command( - name = "/gsmask", - aliases = {"gsmask", "globalsourcemask", "/globalsourcemask"}, - desc = "Set the global source mask", - descFooter = "The global source mask applies to all edits you do and masks based on the source blocks (e.g., the blocks in your clipboard)" + name = "/gsmask", + aliases = {"gsmask", "globalsourcemask", "/globalsourcemask"}, + desc = "Set the global source mask", + descFooter = "The global source mask applies to all edits you do and masks based on the source blocks (e.g., the blocks in your clipboard)" ) @CommandPermissions({"worldedit.global-mask", "worldedit.mask.global"}) public void gsmask(Player player, LocalSession session, EditSession editSession, @Arg(desc = "The mask to set", def = "") Mask maskOpt) throws WorldEditException { @@ -462,9 +472,9 @@ public class GeneralCommands { @Command( - name = "/gtransform", - aliases = {"gtransform"}, - desc = "Set the global transform" + name = "/gtransform", + aliases = {"gtransform"}, + desc = "Set the global transform" ) @CommandPermissions({"worldedit.global-transform", "worldedit.transform.global"}) public void gtransform(Player player, EditSession editSession, LocalSession session, ResettableExtent transform) throws WorldEditException { @@ -477,9 +487,9 @@ public class GeneralCommands { } @Command( - name = "/tips", - aliases = {"tips"}, - desc = "Toggle FAWE tips" + name = "/tips", + aliases = {"tips"}, + desc = "Toggle FAWE tips" ) @CommandPermissions("fawe.tips") public void tips(Player player, LocalSession session) throws WorldEditException { 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 6ee6853fc..a7d65b216 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 @@ -108,26 +108,26 @@ public class GenerationCommands { @Arg(name = "pocketMax", desc = "TODO", def = "3") int pocketMaxOpt) throws WorldEditException { CavesGen gen = new CavesGen(sizeOpt, frequencyOpt, rarityOpt, minYOpt, maxYOpt, systemFrequencyOpt, individualRarityOpt, pocketChanceOpt, pocketMinOpt, pocketMaxOpt); editSession.generate(region, gen); - actor.print(Caption.of("fawe.worldedit.visitor.visitor.block" , editSession.getBlockChangeCount())); + actor.print(Caption.of("fawe.worldedit.visitor.visitor.block", editSession.getBlockChangeCount())); } @Command( - name = "/ores", - desc = "Generates ores" + name = "/ores", + desc = "Generates ores" ) @CommandPermissions("worldedit.generation.ore") @Logging(PLACEMENT) @Confirm(Confirm.Processor.REGION) public void ores(Actor actor, LocalSession session, EditSession editSession, @Selection Region region, @Arg(desc = "Mask") Mask mask) throws WorldEditException { editSession.addOres(region, mask); - actor.print(Caption.of("fawe.worldedit.visitor.visitor.block" , editSession.getBlockChangeCount())); + actor.print(Caption.of("fawe.worldedit.visitor.visitor.block", editSession.getBlockChangeCount())); } @Command( - name = "/img", - aliases = { "/image", "image" }, - desc = "Generate an image" + name = "/img", + aliases = { "/image", "image" }, + desc = "Generate an image" ) @CommandPermissions("worldedit.generation.image") @Logging(PLACEMENT) @@ -155,7 +155,9 @@ public class GenerationCommands { int color = finalImage.getRGB(x, z); BlockType block = tu.getNearestBlock(color); count[0]++; - if (block != null) return editSession.setBlock(pos, block.getDefaultState()); + if (block != null) { + return editSession.setBlock(pos, block.getDefaultState()); + } return false; } catch (Throwable e) { e.printStackTrace(); @@ -163,19 +165,19 @@ public class GenerationCommands { return false; }); Operations.completeBlindly(visitor); - actor.print(Caption.of("fawe.worldedit.visitor.visitor.block" , editSession.getBlockChangeCount())); + actor.print(Caption.of("fawe.worldedit.visitor.visitor.block", editSession.getBlockChangeCount())); } @Command( - name = "/ore", - desc = "Generates ores" + name = "/ore", + desc = "Generates ores" ) @CommandPermissions("worldedit.generation.ore") @Logging(PLACEMENT) @Confirm(Confirm.Processor.REGION) public void ore(Actor actor, LocalSession session, EditSession editSession, @Selection Region region, @Arg(desc = "Mask") Mask mask, @Arg(desc = "Pattern") Pattern material, @Arg(desc="Ore vein size") @Range(from = 0, to=Integer.MAX_VALUE) int size, int freq, @Range(from=0, to=100) int rarity, @Range(from=0, to=255) int minY, @Range(from=0, to=255) int maxY) throws WorldEditException { editSession.addOre(region, mask, material, size, freq, rarity, minY, maxY); - actor.print(Caption.of("fawe.worldedit.visitor.visitor.block" , editSession.getBlockChangeCount())); + actor.print(Caption.of("fawe.worldedit.visitor.visitor.block", editSession.getBlockChangeCount())); } @Command( @@ -211,7 +213,8 @@ public class GenerationCommands { int height, @Switch(name = 'h', desc = "Make a hollow cylinder") boolean hollow) throws WorldEditException { - final double radiusX, radiusZ; + final double radiusX; + final double radiusZ; switch (radii.size()) { case 1: radiusX = radiusZ = Math.max(1, radii.get(0)); @@ -270,7 +273,9 @@ public class GenerationCommands { boolean raised, @Switch(name = 'h', desc = "Make a hollow sphere") boolean hollow) throws WorldEditException { - final double radiusX, radiusY, radiusZ; + final double radiusX; + final double radiusY; + final double radiusZ; switch (radii.size()) { case 1: radiusX = radiusY = radiusZ = Math.max(0, radii.get(0)); @@ -427,9 +432,15 @@ public class GenerationCommands { zero = max.add(min).multiply(0.5); unit = max.subtract(zero); - if (unit.getX() == 0) unit = unit.withX(1.0); - if (unit.getY() == 0) unit = unit.withY(1.0); - if (unit.getZ() == 0) unit = unit.withZ(1.0); + if (unit.getX() == 0) { + unit = unit.withX(1.0); + } + if (unit.getY() == 0) { + unit = unit.withY(1.0); + } + if (unit.getZ() == 0) { + unit = unit.withZ(1.0); + } } final Vector3 unit1 = unit; @@ -451,9 +462,9 @@ public class GenerationCommands { name = "/generatebiome", aliases = { "/genbiome", "/gb" }, desc = "Sets biome according to a formula.", - descFooter = "Formula must return positive numbers (true) if the point is inside the shape\n" + - "Sets the biome of blocks in that shape.\n" - +"See also https://tinyurl.com/weexpr." + descFooter = "Formula must return positive numbers (true) if the point is inside the shape\n" + + "Sets the biome of blocks in that shape.\n" + + "See also https://tinyurl.com/weexpr." ) @CommandPermissions("worldedit.generation.shape.biome") @Logging(ALL) @@ -494,9 +505,15 @@ public class GenerationCommands { zero = max.add(min).multiply(0.5); unit = max.subtract(zero); - if (unit.getX() == 0) unit = unit.withX(1.0); - if (unit.getY() == 0) unit = unit.withY(1.0); - if (unit.getZ() == 0) unit = unit.withZ(1.0); + if (unit.getX() == 0) { + unit = unit.withX(1.0); + } + if (unit.getY() == 0) { + unit = unit.withY(1.0); + } + if (unit.getZ() == 0) { + unit = unit.withZ(1.0); + } } final Vector3 unit1 = unit; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/HistorySubCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/HistorySubCommands.java index 4428615d7..64f344400 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/HistorySubCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/HistorySubCommands.java @@ -70,50 +70,62 @@ public class HistorySubCommands { } @Command( - name = "restore", - aliases = {"rerun"}, - desc = "Rerun edits" + - " - The time uses s, m, h, d, y.\n" + - " - Import from disk: /history import" + name = "restore", + aliases = {"rerun"}, + desc = "Rerun edits" + + " - The time uses s, m, h, d, y.\n" + + " - Import from disk: /history import" ) @CommandPermissions("worldedit.history.redo") @Confirm public synchronized void rerun(Player player, World world, RollbackDatabase database, @AllowedRegion Region[] allowedRegions, - @ArgFlag(name = 'u', desc = "String user", def="me") UUID other, + @ArgFlag(name = 'u', desc = "String user", def = "me") + UUID other, @ArgFlag(name = 'r', def = "0", desc = "radius") - @Range(from = 0, to = Integer.MAX_VALUE) int radius, + @Range(from = 0, to = Integer.MAX_VALUE) + int radius, @ArgFlag(name = 't', desc = "Time e.g. 20s", def = "0") - @Time long timeDiff) throws WorldEditException { + @Time + long timeDiff) throws WorldEditException { rollback(player, world, database, allowedRegions, other, radius, timeDiff, true); } @Command( - name = "rollback", - desc = "Undo a specific edit. " + - " - The time uses s, m, h, d, y." + name = "rollback", + desc = "Undo a specific edit. " + + " - The time uses s, m, h, d, y." ) @CommandPermissions("worldedit.history.undo") @Confirm public synchronized void rollback(Player player, World world, RollbackDatabase database, @AllowedRegion Region[] allowedRegions, - @ArgFlag(name = 'u', desc = "String user", def = "") UUID other, + @ArgFlag(name = 'u', desc = "String user", def = "") + UUID other, @ArgFlag(name = 'r', def = "0", desc = "radius") - @Range(from = 0, to = Integer.MAX_VALUE) int radius, - @ArgFlag(name = 't', desc = "Time e.g. 20s", def = "0") @Time long timeDiff, - @Switch(name = 'f', desc = "Restore instead of rollback") boolean restore) throws WorldEditException { + @Range(from = 0, to = Integer.MAX_VALUE) + int radius, + @ArgFlag(name = 't', desc = "Time e.g. 20s", def = "0") + @Time + long timeDiff, + @Switch(name = 'f', desc = "Restore instead of rollback") + boolean restore) throws WorldEditException { if (!Settings.IMP.HISTORY.USE_DATABASE) { - player.print(Caption.of("fawe.error.setting.disable" , "history.use-database (Import with /history import )")); + player.print(Caption.of("fawe.error.setting.disable", "history.use-database (Import with /history import )")); return; } checkCommandArgument(radius > 0, "Radius must be >= 0"); checkCommandArgument(timeDiff > 0, "Time must be >= 0"); - if (other == null) other = player.getUniqueId(); + if (other == null) { + other = player.getUniqueId(); + } if (!other.equals(player.getUniqueId())) { player.checkPermission("worldedit.history.undo.other"); } - if (other == Identifiable.EVERYONE) other = null; + if (other == Identifiable.EVERYONE) { + other = null; + } Location origin = player.getLocation(); BlockVector3 bot = origin.toBlockPoint().subtract(radius, radius, radius); BlockVector3 top = origin.toBlockPoint().add(radius, radius, radius); @@ -121,11 +133,11 @@ public class HistorySubCommands { top = top.clampY(0, world.getMaxY()); // TODO mask the regions bot / top to the bottom and top coord in the allowedRegions // TODO: then mask the edit to the bot / top -// if (allowedRegions.length != 1 || !allowedRegions[0].isGlobal()) { -// finalQueue = new MaskedIQueueExtent(SetQueue.IMP.getNewQueue(fp.getWorld(), true, false), allowedRegions); -// } else { -// finalQueue = SetQueue.IMP.getNewQueue(fp.getWorld(), true, false); -// } + // if (allowedRegions.length != 1 || !allowedRegions[0].isGlobal()) { + // finalQueue = new MaskedIQueueExtent(SetQueue.IMP.getNewQueue(fp.getWorld(), true, false), allowedRegions); + // } else { + // finalQueue = SetQueue.IMP.getNewQueue(fp.getWorld(), true, false); + // } int count = 0; UUID finalOther = other; long minTime = System.currentTimeMillis() - timeDiff; @@ -136,14 +148,14 @@ public class HistorySubCommands { String path = edit.getWorld().getName() + "/" + finalOther + "-" + edit.getIndex(); player.print(Caption.of("fawe.worldedit.rollback.rollback.element", path)); } - player.print(Caption.of("fawe.worldedit.tool.tool.inspect.info.footer" , count)); + player.print(Caption.of("fawe.worldedit.tool.tool.inspect.info.footer", count)); } @Command( - name = "import", - desc = "Import history into the database" + - " - The time uses s, m, h, d, y.\n" + - " - Import from disk: /history import" + name = "import", + desc = "Import history into the database" + + " - The time uses s, m, h, d, y.\n" + + " - Import from disk: /history import" ) @CommandPermissions("fawe.rollback.import") @Confirm @@ -197,14 +209,16 @@ public class HistorySubCommands { } @Command( - name = "info", - aliases = {"summary", "summarize"}, - desc = "Summarize an edit" + name = "info", + aliases = {"summary", "summarize"}, + desc = "Summarize an edit" ) @CommandPermissions("worldedit.history.info") public synchronized void summary(Player player, RollbackDatabase database, Arguments arguments, - @Arg(desc = "Player uuid/name") UUID other, - @Arg(desc = "edit index") Integer index) throws WorldEditException, ExecutionException, InterruptedException { + @Arg(desc = "Player uuid/name") + UUID other, + @Arg(desc = "edit index") + Integer index) throws WorldEditException, ExecutionException, InterruptedException { RollbackOptimizedHistory edit = database.getEdit(other, index).get(); if (edit == null) { player.print(TranslatableComponent.of("fawe.worldedit.schematic.schematic.none")); @@ -238,11 +252,21 @@ public class HistorySubCommands { String sizeStr = StringMan.humanReadableByteCountBin(edit.getSizeOnDisk()); String extra = ""; - if (biomes) extra += "biomes, "; - if (createdEnts) extra += "+entity, "; - if (removedEnts) extra += "-entity, "; - if (createdTiles) extra += "+tile, "; - if (removedTiles) extra += "-tile, "; + if (biomes) { + extra += "biomes, "; + } + if (createdEnts) { + extra += "+entity, "; + } + if (removedEnts) { + extra += "-entity, "; + } + if (createdTiles) { + extra += "+tile, "; + } + if (removedTiles) { + extra += "-tile, "; + } TranslatableComponent body = Caption.of("fawe.worldedit.history.find.element.more", size, edit.getMinimumPoint(), edit.getMaximumPoint(), extra.trim(), sizeStr); Component distr = TextComponent.of("/history distr").clickEvent(ClickEvent.suggestCommand("//history distr " + other + " " + index)); @@ -296,23 +320,29 @@ public class HistorySubCommands { } @Command( - name = "find", - aliases = {"inspect", "search", "near"}, - desc = "Find nearby edits" + name = "find", + aliases = {"inspect", "search", "near"}, + desc = "Find nearby edits" ) @CommandPermissions("worldedit.history.find") public synchronized void find(Player player, World world, RollbackDatabase database, Arguments arguments, - @ArgFlag(name = 'u', def="", desc = "String user") UUID other, + @ArgFlag(name = 'u', def = "", desc = "String user") + UUID other, @ArgFlag(name = 'r', def = "0", desc = "radius") - @Range(from = 0, to = Integer.MAX_VALUE) Integer radius, + @Range(from = 0, to = Integer.MAX_VALUE) + Integer radius, @ArgFlag(name = 't', desc = "Time e.g. 20s", def = "0") - @Time Long timeDiff, - @ArgFlag(name = 'p', desc = "Page to view.", def = "") Integer page) throws WorldEditException { + @Time + Long timeDiff, + @ArgFlag(name = 'p', desc = "Page to view.", def = "") + Integer page) throws WorldEditException { if (!Settings.IMP.HISTORY.USE_DATABASE) { - player.print(Caption.of("fawe.error.setting.disable" , "history.use-database (Import with //history import )")); + player.print(Caption.of("fawe.error.setting.disable", "history.use-database (Import with //history import )")); return; } - if (other == null && radius == 0 && timeDiff == 0) throw new InsufficientArgumentsException("User must be provided"); + if (other == null && radius == 0 && timeDiff == 0) { + throw new InsufficientArgumentsException("User must be provided"); + } checkCommandArgument(radius > 0, "Radius must be >= 0"); checkCommandArgument(timeDiff > 0, "Time must be >= 0"); @@ -322,11 +352,15 @@ public class HistorySubCommands { List> history = cached == null ? null : cached.get(); if (page == null || history == null) { - if (other == null) other = player.getUniqueId(); + if (other == null) { + other = player.getUniqueId(); + } if (!other.equals(player.getUniqueId())) { player.checkPermission("worldedit.history.undo.other"); } - if (other == Identifiable.EVERYONE) other = null; + if (other == Identifiable.EVERYONE) { + other = null; + } BlockVector3 bot = origin.toBlockPoint().subtract(radius, radius, radius); BlockVector3 top = origin.toBlockPoint().add(radius, radius, radius); @@ -345,15 +379,18 @@ public class HistorySubCommands { } @Command( - name = "distr", - aliases = {"distribution"}, - desc = "View block distribution for an edit" + name = "distr", + aliases = {"distribution"}, + desc = "View block distribution for an edit" ) @CommandPermissions("worldedit.history.distr") public void distr(Player player, LocalSession session, RollbackDatabase database, Arguments arguments, - @Arg(desc = "Player uuid/name") UUID other, - @Arg(desc = "edit index") Integer index, - @ArgFlag(name = 'p', desc = "Page to view.", def = "") Integer page) throws ExecutionException, InterruptedException { + @Arg(desc = "Player uuid/name") + UUID other, + @Arg(desc = "edit index") + Integer index, + @ArgFlag(name = 'p', desc = "Page to view.", def = "") + Integer page) throws ExecutionException, InterruptedException { String pageCommand = "/" + arguments.get().replaceAll("-p [0-9]+", "").trim(); Reference cached = player.getMeta(pageCommand); PaginationBox pages = cached == null ? null : cached.get(); @@ -372,13 +409,15 @@ public class HistorySubCommands { } @Command( - name = "list", - desc = "List your history" + name = "list", + desc = "List your history" ) @CommandPermissions("worldedit.history.list") public void list(Player player, LocalSession session, RollbackDatabase database, Arguments arguments, - @Arg(desc = "Player uuid/name") UUID other, - @ArgFlag(name = 'p', desc = "Page to view.", def = "") Integer page) { + @Arg(desc = "Player uuid/name") + UUID other, + @ArgFlag(name = 'p', desc = "Page to view.", def = "") + Integer page) { int index = session.getHistoryIndex(); List> history = Lists.transform(session.getHistory(), (Function>) input -> () -> input); Location origin = player.getLocation(); @@ -393,8 +432,8 @@ public class HistorySubCommands { } @Command( - name = "clear", - desc = "Clear your history" + name = "clear", + desc = "Clear your history" ) @CommandPermissions("worldedit.history.clear") public void clearHistory(Actor actor, LocalSession session) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ListFilters.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ListFilters.java index 6d26d5446..f922cf131 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ListFilters.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ListFilters.java @@ -88,13 +88,17 @@ public class ListFilters { @Override public File getPath(File root) { File newRoot = new File(root, finalArg); - if (newRoot.exists()) return newRoot; + if (newRoot.exists()) { + return newRoot; + } String firstArg = finalArg.substring(0, finalArg.length() - File.separator.length()); if (firstArg.length() > 3 && firstArg.length() <= 16) { UUID fromName = Fawe.imp().getUUID(finalArg); if (fromName != null) { newRoot = new File(root, finalArg); - if (newRoot.exists()) return newRoot; + if (newRoot.exists()) { + return newRoot; + } } } throw new StopExecutionException(TextComponent.of("Cannot find path: " + finalArg)); @@ -105,7 +109,7 @@ public class ListFilters { Pattern pattern; try { pattern = Pattern.compile(argLower); - } catch (PatternSyntaxException ignore) { + } catch (PatternSyntaxException ignored) { pattern = Pattern.compile(Pattern.quote(argLower)); } Pattern finalPattern = pattern; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/MethodCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/MethodCommands.java index e86f42ea8..8e781b075 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/MethodCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/MethodCommands.java @@ -9,7 +9,9 @@ import java.util.Optional; public class MethodCommands { public static String getArguments(InjectedValueAccess context) { - if (context == null) return null; + if (context == null) { + return null; + } Optional arguments = context.injectedValue(Key.of(Arguments.class)); return arguments.map(Arguments::get).orElse(null); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/RegionCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/RegionCommands.java index dd608fd88..c8f5005a9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/RegionCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/RegionCommands.java @@ -115,9 +115,9 @@ public class RegionCommands { } @Command( - name = "/air", - aliases = {"/0"}, - desc = "Sets all the blocks in the region to air" + name = "/air", + aliases = {"/0"}, + desc = "Sets all the blocks in the region to air" ) @CommandPermissions("worldedit.region.set") @Logging(REGION) @@ -126,18 +126,19 @@ public class RegionCommands { } @Command( - name = "/test", - desc = "test region" + name = "/test", + desc = "test region" ) @CommandPermissions("worldedit.region.test") @Logging(REGION) - public void test(Player player, EditSession editSession, @Arg(desc = "test") double testValue) throws WorldEditException { + public void test(Player player, EditSession editSession, + @Arg(desc = "test") double testValue) throws WorldEditException { player.print(TextComponent.of(testValue)); } @Command( - name = "/fixlighting", - desc = "Get the light at a position" + name = "/fixlighting", + desc = "Get the light at a position" ) @CommandPermissions("worldedit.light.fix") public void fixLighting(Player player) throws WorldEditException { @@ -148,25 +149,25 @@ public class RegionCommands { final int cz = loc.getBlockZ() >> 4; selection = new CuboidRegion(BlockVector3.at(cx - 8, 0, cz - 8).multiply(16), BlockVector3.at(cx + 8, 0, cz + 8).multiply(16)); } - int count = FaweAPI.fixLighting(player.getWorld(), selection,null, RelightMode.ALL); - player.print(Caption.of("fawe.info.lighting.propagate.selection" , count)); + int count = FaweAPI.fixLighting(player.getWorld(), selection, null, RelightMode.ALL); + player.print(Caption.of("fawe.info.lighting.propagate.selection", count)); } -// @Command( -// name = "/getlighting", -// desc = "Get the light at a position" -// ) -// @CommandPermissions("worldedit.light.fix") -// public void getLighting(Player player, EditSession editSession) throws WorldEditException { -// final Location loc = player.getLocation(); -// int block = editSession.getBlockLight(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); -// int sky = editSession.getSkyLight(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); -// player.print(TextComponent.of("Light: " + block + " | " + sky)); -// } + // @Command( + // name = "/getlighting", + // desc = "Get the light at a position" + // ) + // @CommandPermissions("worldedit.light.fix") + // public void getLighting(Player player, EditSession editSession) throws WorldEditException { + // final Location loc = player.getLocation(); + // int block = editSession.getBlockLight(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + // int sky = editSession.getSkyLight(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + // player.print(TextComponent.of("Light: " + block + " | " + sky)); + // } @Command( - name = "/removelighting", - desc = "Removing lighting in a selection" + name = "/removelighting", + desc = "Removing lighting in a selection" ) @CommandPermissions("worldedit.light.remove") public void removeLighting(Player player) { @@ -177,13 +178,13 @@ public class RegionCommands { selection = new CuboidRegion(BlockVector3.at(cx - 8, 0, cz - 8).multiply(16), BlockVector3.at(cx + 8, 0, cz + 8).multiply(16)); } int count = FaweAPI.fixLighting(player.getWorld(), selection, null, RelightMode.NONE); - player.print(Caption.of("fawe.info.updated.lighting.selection" , count)); + player.print(Caption.of("fawe.info.updated.lighting.selection", count)); } @Command( - name = "/nbtinfo", - aliases = "/nbt", - desc = "View nbt info for a block" + name = "/nbtinfo", + aliases = "/nbt", + desc = "View nbt info for a block" ) @CommandPermissions("worldedit.nbtinfo") public void nbtinfo(Player player, EditSession editSession) { @@ -201,8 +202,8 @@ public class RegionCommands { } @Command( - name = "/setblocklight", - desc = "Set block lighting in a selection" + name = "/setblocklight", + desc = "Set block lighting in a selection" ) @CommandPermissions("worldedit.light.set") public void setlighting(Player player, EditSession editSession, @Selection Region region) { @@ -210,8 +211,8 @@ public class RegionCommands { } @Command( - name = "/setskylight", - desc = "Set sky lighting in a selection" + name = "/setskylight", + desc = "Set sky lighting in a selection" ) @CommandPermissions("worldedit.light.set") public void setskylighting(Player player, @Selection Region region) { @@ -316,9 +317,9 @@ public class RegionCommands { } @Command( - name = "/lay", - desc = "Set the top block in the region" -) + name = "/lay", + desc = "Set the top block in the region" + ) @CommandPermissions("worldedit.region.overlay") @Logging(REGION) @Confirm(Confirm.Processor.REGION) @@ -337,7 +338,7 @@ public class RegionCommands { editSession.setBlock(x, y, z, patternArg); affected++; } - player.print(Caption.of("fawe.worldedit.visitor.visitor.block" , affected)); + player.print(Caption.of("fawe.worldedit.visitor.visitor.block", affected)); } @Command( @@ -412,7 +413,8 @@ public class RegionCommands { int iterations, @Arg(desc = "The mask of blocks to use as the height map", def = "") Mask mask, - @Switch(name = 's', desc = "TODO") boolean snow) throws WorldEditException { + @Switch(name = 's', desc = "The flag makes it only consider snow") + boolean snow) throws WorldEditException { BlockVector3 min = region.getMinimumPoint(); BlockVector3 max = region.getMaximumPoint(); long volume = (((long) max.getX() - (long) min.getX() + 1) * ((long) max.getY() - (long) min.getY() + 1) * ((long) max.getZ() - (long) min.getZ() + 1)); @@ -433,10 +435,10 @@ public class RegionCommands { } @Command( - name = "/wea", - aliases = {"wea", "worldeditanywhere", "/worldeditanywhere", "/weanywhere"}, - desc = "Bypass region restrictions", - descFooter = "Bypass region restrictions" + name = "/wea", + aliases = {"wea", "worldeditanywhere", "/worldeditanywhere", "/weanywhere"}, + desc = "Bypass region restrictions", + descFooter = "Bypass region restrictions" ) @CommandPermissions("fawe.admin") public void wea(Actor actor) throws WorldEditException { @@ -448,10 +450,10 @@ public class RegionCommands { } @Command( - name = "/wer", - aliases = {"wer", "worldeditregion", "/worldeditregion", "select", "/select"}, - desc = "Select your current allowed region", - descFooter = "Select your current allowed region" + name = "/wer", + aliases = {"wer", "worldeditregion", "/worldeditregion", "select", "/select"}, + desc = "Select your current allowed region", + descFooter = "Select your current allowed region" ) @CommandPermissions("fawe.worldeditregion") public void wer(Player player) throws WorldEditException { @@ -523,20 +525,21 @@ public class RegionCommands { } @Command( - name = "/fall", - desc = "Have the blocks in the selection fall", - descFooter = "Make the blocks in the selection fall\n" + - "The -m flag will only fall within the vertical selection." -) + name = "/fall", + desc = "Have the blocks in the selection fall", + descFooter = "Make the blocks in the selection fall\n" + ) @CommandPermissions("worldedit.region.fall") @Logging(ORIENTATION_REGION) @Confirm(Confirm.Processor.REGION) public void fall(Player player, EditSession editSession, LocalSession session, @Selection Region region, - @Arg(desc = "BlockStateHolder", def = "air") BlockStateHolder replace, - @Switch(name = 'm', desc = "TODO") boolean notFullHeight) throws WorldEditException { + @Arg(desc = "BlockStateHolder", def = "air") + BlockStateHolder replace, + @Switch(name = 'm', desc = "Only fall within the vertical selection") + boolean notFullHeight) throws WorldEditException { int affected = editSession.fall(region, !notFullHeight, replace); - player.print(Caption.of("fawe.worldedit.visitor.visitor.block" , affected)); + player.print(Caption.of("fawe.worldedit.visitor.visitor.block", affected)); } @Command( @@ -598,14 +601,14 @@ public class RegionCommands { @Command( name = "/regen", desc = "Regenerates the contents of the selection", - descFooter = "This command might affect things outside the selection,\n" + - "if they are within the same chunk." + descFooter = "This command might affect things outside the selection,\n" + + "if they are within the same chunk." ) @CommandPermissions("worldedit.regen") @Logging(REGION) @Confirm(Confirm.Processor.REGION) - public void regenerateChunk(Actor actor, World world, LocalSession session, - EditSession editSession, @Selection Region region) throws WorldEditException { + public void regenerateChunk(Actor actor, World world, LocalSession session, EditSession editSession, + @Selection Region region) throws WorldEditException { Mask mask = session.getMask(); boolean success; try { @@ -626,9 +629,9 @@ public class RegionCommands { @Command( name = "/deform", desc = "Deforms a selected region with an expression", - descFooter = "The expression is executed for each block and is expected\n" + - "to modify the variables x, y and z to point to a new block\n" + - "to fetch. See also https://tinyurl.com/weexpr" + descFooter = "The expression is executed for each block and is expected\n" + + "to modify the variables x, y and z to point to a new block\n" + + "to fetch. See also https://tinyurl.com/weexpr" ) @CommandPermissions("worldedit.region.deform") @Logging(ALL) @@ -665,9 +668,15 @@ public class RegionCommands { zero = max.add(min).divide(2); unit = max.subtract(zero); - if (unit.getX() == 0) unit = unit.withX(1.0); - if (unit.getY() == 0) unit = unit.withY(1.0); - if (unit.getZ() == 0) unit = unit.withZ(1.0); + if (unit.getX() == 0) { + unit = unit.withX(1.0); + } + if (unit.getY() == 0) { + unit = unit.withY(1.0); + } + if (unit.getZ() == 0) { + unit = unit.withZ(1.0); + } } final Vector3 unit1 = unit; @@ -687,10 +696,9 @@ public class RegionCommands { @Command( name = "/hollow", desc = "Hollows out the object contained in this selection", - descFooter = "Hollows out the object contained in this selection.\n" + - "Optionally fills the hollowed out part with the given block.\n" + - "Thickness is measured in manhattan distance." - + descFooter = "Hollows out the object contained in this selection.\n" + + "Optionally fills the hollowed out part with the given block.\n" + + "Thickness is measured in manhattan distance." ) @CommandPermissions("worldedit.region.hollow") @Logging(REGION) @@ -701,7 +709,8 @@ public class RegionCommands { int thickness, @Arg(desc = "The pattern of blocks to replace the hollowed area with", def = "air") Pattern pattern, - @ArgFlag(name = 'm', desc = "Mask to hollow with") Mask mask) throws WorldEditException { + @ArgFlag(name = 'm', desc = "Mask to hollow with") + Mask mask) throws WorldEditException { checkCommandArgument(thickness >= 0, "Thickness must be >= 0"); Mask finalMask = mask == null ? new SolidBlockMask(editSession) : mask; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java index 5ffe56406..a77369af1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SchematicCommands.java @@ -116,8 +116,8 @@ public class SchematicCommands { } @Command( - name = "loadall", - desc = "Load multiple clipboards (paste will randomly choose one)" + name = "loadall", + desc = "Load multiple clipboards (paste will randomly choose one)" ) @Deprecated @CommandPermissions({"worldedit.clipboard.load", "worldedit.schematic.load", "worldedit.schematic.load.web", "worldedit.schematic.load.asset"}) @@ -130,14 +130,14 @@ public class SchematicCommands { boolean randomRotate) throws FilenameException { final ClipboardFormat format = ClipboardFormats.findByAlias(formatName); if (format == null) { - player.print(Caption.of("fawe.worldedit.clipboard.clipboard.invalid.format" , formatName)); + player.print(Caption.of("fawe.worldedit.clipboard.clipboard.invalid.format", formatName)); return; } try { MultiClipboardHolder all = ClipboardFormats.loadAllFromInput(player, filename, null, true); if (all != null) { session.addClipboard(all); - player.print(Caption.of("fawe.worldedit.schematic.schematic.loaded" , filename)); + player.print(Caption.of("fawe.worldedit.schematic.schematic.loaded", filename)); } } catch (IOException e) { throw new RuntimeException(e); @@ -145,8 +145,8 @@ public class SchematicCommands { } @Command( - name = "clear", - desc = "Clear your clipboard" + name = "clear", + desc = "Clear your clipboard" ) @CommandPermissions({"worldedit.clipboard.clear", "worldedit.schematic.clear"}) public void clear(Player player, LocalSession session) throws WorldEditException { @@ -155,8 +155,8 @@ public class SchematicCommands { } @Command( - name = "unload", - desc = "Remove a clipboard from your multi-clipboard" + name = "unload", + desc = "Remove a clipboard from your multi-clipboard" ) @CommandPermissions({"worldedit.clipboard.clear", "worldedit.schematic.clear"}) public void unload(Player player, LocalSession session, String fileName) throws WorldEditException { @@ -177,7 +177,9 @@ public class SchematicCommands { if (identifiable instanceof MultiClipboardHolder) { MultiClipboardHolder multi = (MultiClipboardHolder) identifiable; multi.remove(uri); - if (multi.getHolders().isEmpty()) session.setClipboard(null); + if (multi.getHolders().isEmpty()) { + session.setClipboard(null); + } } else { session.setClipboard(null); } @@ -185,7 +187,7 @@ public class SchematicCommands { return; } } - player.print(Caption.of("fawe.worldedit.clipboard.clipboard.uri.not.found" , fileName)); + player.print(Caption.of("fawe.worldedit.clipboard.clipboard.uri.not.found", fileName)); } @Command( @@ -272,7 +274,7 @@ public class SchematicCommands { uri = file.toURI(); } format.hold(actor, uri, in); - actor.print(Caption.of("fawe.worldedit.schematic.schematic.loaded" , filename)); + actor.print(Caption.of("fawe.worldedit.schematic.schematic.loaded", filename)); } catch (IllegalArgumentException e) { actor.printError("Unknown filename: " + filename); } catch (URISyntaxException | IOException e) { @@ -301,8 +303,7 @@ public class SchematicCommands { @Switch(name = 'f', desc = "Overwrite an existing file.") boolean allowOverwrite, @Switch(name = 'g', desc = "//TODO") - boolean global - ) throws WorldEditException { + boolean global) throws WorldEditException { LocalConfiguration config = worldEdit.getConfiguration(); File dir = worldEdit.getWorkingDirectoryFile(config.saveDir); @@ -401,7 +402,7 @@ public class SchematicCommands { for (File source : sources) { File destFile = new File(destDir, source.getName()); if (destFile.exists()) { - player.print(Caption.of("fawe.worldedit.schematic.schematic.move.exists" , destFile)); + player.print(Caption.of("fawe.worldedit.schematic.schematic.move.exists", destFile)); continue; } if (Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS && (!MainUtil.isInSubDirectory(dir, destFile) || !MainUtil.isInSubDirectory(dir, source)) && !player.hasPermission("worldedit.schematic.delete.other")) { @@ -412,8 +413,10 @@ public class SchematicCommands { try { File cached = new File(source.getParentFile(), "." + source.getName() + ".cached"); Files.move(source.toPath(), destFile.toPath()); - if (cached.exists()) Files.move(cached.toPath(), destFile.toPath()); - player.print(Caption.of("fawe.worldedit.schematic.schematic.move.success" , source, destFile)); + if (cached.exists()) { + Files.move(cached.toPath(), destFile.toPath()); + } + player.print(Caption.of("fawe.worldedit.schematic.schematic.move.success", source, destFile)); } catch (IOException e) { throw new RuntimeException(e); } @@ -428,7 +431,9 @@ public class SchematicCommands { List files = new ArrayList<>(); for (URI uri : uris) { File file = new File(uri); - if (file.exists()) files.add(file); + if (file.exists()) { + files.add(file); + } } return files; } @@ -475,9 +480,7 @@ public class SchematicCommands { @ArgFlag(name = 'f', desc = "Restricts by format.", def = "") String formatName, @Arg(name = "filter", desc = "Filter for schematics", def = "all") - String filter, - Arguments arguments - ) throws WorldEditException { + String filter, Arguments arguments) throws WorldEditException { if (oldFirst && newFirst) { throw new StopExecutionException(TextComponent.of("Cannot sort by oldest and newest.")); } @@ -633,7 +636,7 @@ public class SchematicCommands { writer.write(target); } log.info(actor.getName() + " saved " + file.getCanonicalPath()); - actor.print(Caption.of("fawe.worldedit.schematic.schematic.saved" , file.getName())); + actor.print(Caption.of("fawe.worldedit.schematic.schematic.saved", file.getName())); } else { actor.printError(TranslatableComponent.of("fawe.cancel.worldedit.cancel.reason.manual")); } @@ -686,7 +689,9 @@ public class SchematicCommands { } } else { res = Long.compare(f1.lastModified(), f2.lastModified()); // use date if there is a flag - if (sortType == 1) res = -res; // flip date for newest first instead of oldest first + if (sortType == 1) { + res = -res; // flip date for newest first instead of oldest first + } } return res; }); @@ -699,7 +704,9 @@ public class SchematicCommands { //TODO filtering for directories, global, and private scheamtics needs to be reimplemented here private static List getFiles(File root, String filter, ClipboardFormat format) { File[] files = root.listFiles(); - if (files == null) return null; + if (files == null) { + return null; + } //Only get the files that match the format parameter if (format != null) { files = Arrays.stream(files).filter(format::isFormat).toArray(File[]::new); @@ -708,7 +715,9 @@ public class SchematicCommands { for (File f : files) { if (f.isDirectory()) { List subFiles = getFiles(f, filter, format); - if (subFiles == null) continue; // empty subdir + if (subFiles == null) { + continue; // empty subdir + } fileList.addAll(subFiles); } else { fileList.add(f); @@ -723,8 +732,7 @@ public class SchematicCommands { desc = "Delete a saved schematic" ) @CommandPermissions("worldedit.schematic.delete") - public void delete(Actor actor, - LocalSession session, + public void delete(Actor actor, LocalSession session, @Arg(desc = "File name.") String filename) throws WorldEditException, IOException { LocalConfiguration config = worldEdit.getConfiguration(); @@ -756,7 +764,7 @@ public class SchematicCommands { actor.printError(TranslatableComponent.of("worldedit.schematic.delete.failed", TextComponent.of(filename))); continue; } - actor.print(Caption.of("worldedit.schematic.delete.deleted" , filename)); + actor.print(Caption.of("worldedit.schematic.delete.deleted", filename)); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SelectionCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SelectionCommands.java index 201176fea..47ce2b41b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/SelectionCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/SelectionCommands.java @@ -559,7 +559,9 @@ public class SelectionCommands { } BlockDistributionResult res = new BlockDistributionResult(distribution, separateStates); - if (!actor.isPlayer()) res.formatForConsole(); + if (!actor.isPlayer()) { + res.formatForConsole(); + } actor.print(res.create(page)); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ToolCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ToolCommands.java index f408e661e..b2f2872a0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ToolCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ToolCommands.java @@ -88,8 +88,8 @@ public class ToolCommands { ).build(); } commandManager.register(CommandUtil.deprecate( - command, "Global tool names cause conflicts " + - "and will be removed in WorldEdit 8", ToolCommands::asNonGlobal + command, "Global tool names cause conflicts " + + "and will be removed in WorldEdit 8", ToolCommands::asNonGlobal )); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ToolUtilCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ToolUtilCommands.java index 7ce716f3b..0eff1b524 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ToolUtilCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ToolUtilCommands.java @@ -51,6 +51,7 @@ import org.enginehub.piston.annotation.param.Switch; import org.jetbrains.annotations.Range; import java.util.List; +import java.util.Locale; /** * Tool commands. @@ -64,18 +65,16 @@ public class ToolUtilCommands { } @Command( - name = "mask", - aliases = "/mask", - desc = "Set the brush destination mask" + name = "mask", + aliases = "/mask", + desc = "Set the brush destination mask" ) @CommandPermissions({"worldedit.brush.options.mask", "worldedit.mask.brush"}) public void mask(Player player, LocalSession session, - @Switch(name = 'h', desc = "TODO") - boolean offHand, + @Switch(name = 'h', desc = "Whether the offhand should be considered or not") + boolean offHand, @Arg(desc = "The destination mask", def = "") - Mask maskOpt, - Arguments arguments) - throws WorldEditException { + Mask maskOpt, Arguments arguments) throws WorldEditException { BrushTool tool = session.getBrushTool(player, false); if (tool == null) { player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.none")); @@ -96,32 +95,31 @@ public class ToolUtilCommands { } @Command( - name = "material", - aliases = {"mat", "/material", "pattern"}, - desc = "Set the brush material" + name = "material", + aliases = {"mat", "/material", "pattern"}, + desc = "Set the brush material" ) @CommandPermissions("worldedit.brush.options.material") public void material(Player player, LocalSession session, @Arg(desc = "The pattern of blocks to use") Pattern pattern, - @Switch(name = 'h', desc = "TODO") - boolean offHand, - Arguments arguments) throws WorldEditException { + @Switch(name = 'h', desc = "Whether the offhand should be considered or not") + boolean offHand, Arguments arguments) throws WorldEditException { BrushTool tool = session.getBrushTool(player, false); if (tool == null) { player.printInfo(TranslatableComponent.of("fawe.worldedit.brush.brush.none")); return; - } + } if (pattern == null) { tool.setFill(null); } else { - BrushSettings settings = offHand ? tool.getOffHand() : tool.getContext(); - settings.setFill(pattern); - String lastArg = Iterables.getLast(CommandArgParser.spaceSplit(arguments.get())).getSubstring(); - settings.addSetting(BrushSettings.SettingType.FILL, lastArg); - tool.update(); - } - player.printInfo(TranslatableComponent.of("worldedit.tool.material.set")); + BrushSettings settings = offHand ? tool.getOffHand() : tool.getContext(); + settings.setFill(pattern); + String lastArg = Iterables.getLast(CommandArgParser.spaceSplit(arguments.get())).getSubstring(); + settings.addSetting(BrushSettings.SettingType.FILL, lastArg); + tool.update(); + } + player.printInfo(TranslatableComponent.of("worldedit.tool.material.set")); } @Command( @@ -169,9 +167,9 @@ public class ToolUtilCommands { } @Command( - name = "/superpickaxe", - aliases = {",", "/sp", "/pickaxe", "/"}, - desc = "Toggle the super pickaxe function" + name = "/superpickaxe", + aliases = {",", "/sp", "/pickaxe", "/"}, + desc = "Toggle the super pickaxe function" ) @CommandPermissions("worldedit.superpickaxe") public void togglePickaxe(Player player, LocalSession session, @@ -180,8 +178,8 @@ public class ToolUtilCommands { boolean hasSuperPickAxe = session.hasSuperPickAxe(); if (superPickaxe != null && superPickaxe == hasSuperPickAxe) { player.printError(TranslatableComponent.of(superPickaxe ? "worldedit.tool.superpickaxe.enabled.already" : "worldedit.tool.superpickaxe.disabled.already")); - return; - } + return; + } if (hasSuperPickAxe) { session.disableSuperPickAxe(); player.printInfo(TranslatableComponent.of("worldedit.tool.superpickaxe.disabled")); @@ -192,10 +190,10 @@ public class ToolUtilCommands { } @Command( - name = "primary", - aliases = { "/primary" }, - desc = "Set the right click brush", - descFooter = "Set the right click brush" + name = "primary", + aliases = { "/primary" }, + desc = "Set the right click brush", + descFooter = "Set the right click brush" ) @CommandPermissions("worldedit.brush.primary") public void primary(Player player, LocalSession session, @@ -213,15 +211,15 @@ public class ToolUtilCommands { } @Command( - name = "secondary", - aliases = { "/secondary" }, - desc = "Set the left click brush", - descFooter = "Set the left click brush" + name = "secondary", + aliases = { "/secondary" }, + desc = "Set the left click brush", + descFooter = "Set the left click brush" ) @CommandPermissions("worldedit.brush.secondary") public void secondary(Player player, LocalSession session, - @Arg(desc = "The brush command", variable = true) List commandStr) - throws WorldEditException { + @Arg(desc = "The brush command", variable = true) + List commandStr) throws WorldEditException { BaseItem item = player.getItemInHand(HandSide.MAIN_HAND); BrushTool tool = session.getBrushTool(player, false); session.setTool(item, null, player); @@ -235,19 +233,19 @@ public class ToolUtilCommands { } @Command( - name = "visualize", - aliases = {"visual", "vis", "/visualize", "/visual", "/vis"}, - desc = "Toggle between different visualization modes", - descFooter = "Toggle between different visualization modes\n" + - "0 = No visualization\n" + - "1 = Single block at target position\n" + - "2 = Glass showing what blocks will be changed" + name = "visualize", + aliases = {"visual", "vis", "/visualize", "/visual", "/vis"}, + desc = "Toggle between different visualization modes", + descFooter = "Toggle between different visualization modes\n" + + "0 = No visualization\n" + + "1 = Single block at target position\n" + + "2 = Glass showing what blocks will be changed" ) @CommandPermissions("worldedit.brush.visualize") public void visual(Player player, LocalSession session, - @Arg(name = "mode", desc = "int", def = "0") @Range(from = 0, to = 2) - int mode) - throws WorldEditException { + @Arg(name = "mode", desc = "int", def = "0") + @Range(from = 0, to = 2) + int mode) throws WorldEditException { BrushTool tool = session.getBrushTool(player, false); if (tool == null) { player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.none")); @@ -256,17 +254,18 @@ public class ToolUtilCommands { VisualMode[] modes = VisualMode.values(); VisualMode newMode = modes[MathMan.wrap(mode, 0, modes.length - 1)]; tool.setVisualMode(player, newMode); - player.print(Caption.of("fawe.worldedit.brush.brush.visual.mode.set" , newMode)); + player.print(Caption.of("fawe.worldedit.brush.brush.visual.mode.set", newMode)); } @Command( - name = "target", - aliases = {"tar", "/target", "/tar"}, - desc = "Toggle between different target modes" + name = "target", + aliases = {"tar", "/target", "/tar"}, + desc = "Toggle between different target modes" ) @CommandPermissions("worldedit.brush.target") public void target(Player player, LocalSession session, - @Arg(name = "mode", desc = "int", def = "0") int mode) throws WorldEditException { + @Arg(name = "mode", desc = "int", def = "0") + int mode) throws WorldEditException { BrushTool tool = session.getBrushTool(player, false); if (tool == null) { player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.none")); @@ -275,13 +274,13 @@ public class ToolUtilCommands { TargetMode[] modes = TargetMode.values(); TargetMode newMode = modes[MathMan.wrap(mode, 0, modes.length - 1)]; tool.setTargetMode(newMode); - player.print(Caption.of("fawe.worldedit.brush.brush.target.mode.set" , newMode)); + player.print(Caption.of("fawe.worldedit.brush.brush.target.mode.set", newMode)); } @Command( - name = "targetoffset", - aliases = {"to"}, - desc = "Set the targeting mask" + name = "targetoffset", + aliases = {"to"}, + desc = "Set the targeting mask" ) @CommandPermissions("worldedit.brush.targetoffset") public void targetOffset(Player player, EditSession editSession, LocalSession session, @@ -292,21 +291,21 @@ public class ToolUtilCommands { return; } tool.setTargetOffset(offset); - player.print(Caption.of("fawe.worldedit.brush.brush.target.offset.set" , offset)); + player.print(Caption.of("fawe.worldedit.brush.brush.target.offset.set", offset)); } @Command( - name = "scroll", - desc = "Toggle between different target modes" + name = "scroll", + desc = "Toggle between different target modes" ) @CommandPermissions("worldedit.brush.scroll") public void scroll(Player player, EditSession editSession, LocalSession session, - @Switch(name = 'h', desc = "TODO") - boolean offHand, + @Switch(name = 'h', desc = "Whether the offhand should be considered or not") + boolean offHand, @Arg(desc = "Target Modes", def = "none") - Scroll.Action mode, + Scroll.Action mode, @Arg(desc = "The scroll action", variable = true) - List commandStr) throws WorldEditException { + List commandStr) throws WorldEditException { BrushTool bt = session.getBrushTool(player, false); if (bt == null) { player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.none")); @@ -319,9 +318,9 @@ public class ToolUtilCommands { if (mode == Scroll.Action.NONE) { player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.scroll.action.unset")); } else if (action != null) { - String full = (mode.name().toLowerCase() + " " + StringMan.join(commandStr, " ")).trim(); + String full = (mode.name().toLowerCase(Locale.ROOT) + " " + StringMan.join(commandStr, " ")).trim(); settings.addSetting(BrushSettings.SettingType.SCROLL_ACTION, full); - player.print(Caption.of("fawe.worldedit.brush.brush.scroll.action.set" , mode)); + player.print(Caption.of("fawe.worldedit.brush.brush.scroll.action.set", mode)); } bt.update(); } @@ -329,17 +328,17 @@ public class ToolUtilCommands { @Command( - name = "smask", - aliases = {"/smask", "/sourcemask", "sourcemask"}, - desc = "Set the brush source mask", - descFooter = "Set the brush source mask" + name = "smask", + aliases = {"/smask", "/sourcemask", "sourcemask"}, + desc = "Set the brush source mask", + descFooter = "Set the brush source mask" ) @CommandPermissions({"worldedit.brush.options.mask", "worldedit.mask.brush"}) public void smask(Player player, LocalSession session, EditSession editSession, @Arg(desc = "The destination mask", def = "") - Mask maskArg, - @Switch(name = 'h', desc = "TODO") - boolean offHand, + Mask maskArg, + @Switch(name = 'h', desc = "Whether the offhand should be considered or not") + boolean offHand, Arguments arguments) throws WorldEditException { BrushTool tool = session.getBrushTool(player, false); if (tool == null) { @@ -367,7 +366,7 @@ public class ToolUtilCommands { // @CommandPermissions({"worldedit.brush.options.transform", "worldedit.transform.brush"}) // public void transform(Player player, LocalSession session, EditSession editSession, // @Arg(desc = "The transform", def = "") ResettableExtent transform, -// @Switch(name = 'h', desc = "TODO") +// @Switch(name = 'h', desc = "Whether the offhand should be considered or not") // boolean offHand, // Arguments arguments) throws WorldEditException { // BrushTool tool = session.getBrushTool(player, false); 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 d728f8bbe..17daf0287 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 @@ -101,7 +101,7 @@ import static com.sk89q.worldedit.command.util.Logging.LogMode.PLACEMENT; /** * Utility commands. */ -@CommandContainer(superTypes = {CommandPermissionsConditionGenerator.Registration.class}) +@CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class) public class UtilityCommands { private final WorldEdit we; @@ -111,8 +111,8 @@ public class UtilityCommands { } @Command( - name = "/macro", - desc = "Generate or run a macro" + name = "/macro", + desc = "Generate or run a macro" ) @CommandPermissions("worldedit.macro") public void macro(Player player, LocalSession session, String name, String argument) throws IOException { @@ -120,9 +120,9 @@ public class UtilityCommands { } @Command( - name = "/heightmapinterface", + name = "/heightmapinterface", aliases = { "/hmi", "hmi" }, - desc = "Generate the heightmap interface: https://github.com/boy0001/HeightMap" + desc = "Generate the heightmap interface: https://github.com/boy0001/HeightMap" ) @CommandPermissions("fawe.admin") public void heightmapInterface(Player player, @Arg(name = "min", desc = "int", def = "100") int min, @Arg(name = "max", desc = "int", def = "200") int max) throws IOException { @@ -135,7 +135,7 @@ public class UtilityCommands { final int sub = srcFolder.getAbsolutePath().length(); List images = new ArrayList<>(); MainUtil.iterateFiles(srcFolder, file -> { - switch (file.getName().substring(file.getName().lastIndexOf('.')).toLowerCase()) { + switch (file.getName().substring(file.getName().lastIndexOf('.')).toLowerCase(Locale.ROOT)) { case ".png": case ".jpeg": break; @@ -144,7 +144,9 @@ public class UtilityCommands { } try { String name = file.getAbsolutePath().substring(sub); - if (name.startsWith(File.separator)) name = name.replaceFirst(java.util.regex.Pattern.quote(File.separator), ""); + if (name.startsWith(File.separator)) { + name = name.replaceFirst(java.util.regex.Pattern.quote(File.separator), ""); + } BufferedImage img = MainUtil.readImage(file); BufferedImage minImg = ImageUtil.getScaledInstance(img, min, min, RenderingHints.VALUE_INTERPOLATION_BILINEAR, true); BufferedImage maxImg = max == -1 ? img : ImageUtil.getScaledInstance(img, max, max, RenderingHints.VALUE_INTERPOLATION_BILINEAR, true); @@ -173,20 +175,20 @@ public class UtilityCommands { config.append("// The local source for the image (used in commands)\n"); config.append("var src_local = \"file://\";\n"); File configFile = new File(webSrc, "config.js"); - player.print(TextComponent.of(String.format("Writing %s",configFile))); + player.print(TextComponent.of(String.format("Writing %s", configFile))); Files.write(configFile.toPath(), config.toString().getBytes()); player.print(TextComponent.of("Done! See: `FastAsyncWorldEdit/web/heightmap`")); } @Command( - name = "/cancel", - aliases= {"fcancel"}, - desc = "Cancel your current command" + name = "/cancel", + aliases = {"fcancel"}, + desc = "Cancel your current command" ) @CommandPermissions(value = "fawe.cancel", queued = false) public void cancel(Player player) { int cancelled = player.cancel(false); - player.print(Caption.of("fawe.cancel.worldedit.cancel.count" , cancelled)); + player.print(Caption.of("fawe.cancel.worldedit.cancel.count", cancelled)); } @Command( @@ -702,8 +704,8 @@ public class UtilityCommands { @Command( - name = "/confirm", - desc = "Confirm a command" + name = "/confirm", + desc = "Confirm a command" ) @CommandPermissions(value = "fawe.confirm", queued = false) public void confirm(Player player) throws WorldEditException { @@ -746,15 +748,16 @@ public class UtilityCommands { if (file.isDirectory()) { type = URIType.DIRECTORY; } else { - if (name.indexOf('.') != -1) + if (name.indexOf('.') != -1) { name = name.substring(0, name.lastIndexOf('.')); + } } try { if (!MainUtil.isInSubDirectory(root, file)) { throw new RuntimeException( new StopExecutionException(TextComponent.of("Invalid path"))); } - } catch (IOException ignore) { + } catch (IOException ignored) { } } else if (uriStr.startsWith("http://") || uriStr.startsWith("https://")) { type = URIType.URL; @@ -780,8 +783,9 @@ public class UtilityCommands { fileList.sort((f1, f2) -> { boolean dir1 = f1.isDirectory(); boolean dir2 = f2.isDirectory(); - if (dir1 != dir2) + if (dir1 != dir2) { return dir1 ? -1 : 1; + } int res; if (sortType == 0) { // use name by default int p = f1.getParent().compareTo(f2.getParent()); @@ -792,8 +796,9 @@ public class UtilityCommands { } } else { res = Long.compare(f1.lastModified(), f2.lastModified()); // use date if there is a flag - if (sortType == 1) + if (sortType == 1) { res = -res; // flip date for newest first instead of oldest first + } } return res; }); @@ -814,7 +819,7 @@ public class UtilityCommands { boolean listGlobal = !Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS; if (len > 0) { for (String arg : args) { - switch (arg.toLowerCase()) { + switch (arg.toLowerCase(Locale.ROOT)) { case "me": case "mine": case "local": @@ -874,21 +879,27 @@ public class UtilityCommands { forEachFile = new DelegateConsumer(forEachFile) { @Override public void accept(File file) { - if (cf.isFormat(file)) super.accept(file); + if (cf.isFormat(file)) { + super.accept(file); + } } }; } else { forEachFile = new DelegateConsumer(forEachFile) { @Override public void accept(File file) { - if (!file.toString().endsWith(".cached")) super.accept(file); + if (!file.toString().endsWith(".cached")) { + super.accept(file); + } } }; } if (playerFolder) { if (listMine) { File playerDir = MainUtil.resolveRelative(new File(dir, actor.getUniqueId() + dirFilter)); - if (playerDir.exists()) allFiles(playerDir.listFiles(), false, forEachFile); + if (playerDir.exists()) { + allFiles(playerDir.listFiles(), false, forEachFile); + } } if (listGlobal) { File rel = MainUtil.resolveRelative(new File(dir, dirFilter)); @@ -905,37 +916,51 @@ public class UtilityCommands { super.accept(f); } }; - if (rel.exists()) allFiles(rel.listFiles(), false, forEachFile); + if (rel.exists()) { + allFiles(rel.listFiles(), false, forEachFile); + } } } else { File rel = MainUtil.resolveRelative(new File(dir, dirFilter)); - if (rel.exists()) allFiles(rel.listFiles(), false, forEachFile); + if (rel.exists()) { + allFiles(rel.listFiles(), false, forEachFile); + } } if (!filters.isEmpty() && !toFilter.isEmpty()) { List result = filter(toFilter, filters); - for (File file : result) rootFunction.accept(file); + for (File file : result) { + rootFunction.accept(file); + } } } private static List filter(List fileList, List filters) { String[] normalizedNames = new String[fileList.size()]; for (int i = 0; i < fileList.size(); i++) { - String normalized = fileList.get(i).getName().toLowerCase(); - if (normalized.startsWith("../")) normalized = normalized.substring(3); + String normalized = fileList.get(i).getName().toLowerCase(Locale.ROOT); + if (normalized.startsWith("../")) { + normalized = normalized.substring(3); + } normalizedNames[i] = normalized.replace("/", File.separator); } for (String filter : filters) { - if (fileList.isEmpty()) return fileList; - String lowerFilter = filter.toLowerCase().replace("/", File.separator); + if (fileList.isEmpty()) { + return fileList; + } + String lowerFilter = filter.toLowerCase(Locale.ROOT).replace("/", File.separator); List newList = new ArrayList<>(); for (int i = 0; i < normalizedNames.length; i++) { - if (normalizedNames[i].startsWith(lowerFilter)) newList.add(fileList.get(i)); + if (normalizedNames[i].startsWith(lowerFilter)) { + newList.add(fileList.get(i)); + } } if (newList.isEmpty()) { for (int i = 0; i < normalizedNames.length; i++) { - if (normalizedNames[i].contains(lowerFilter)) newList.add(fileList.get(i)); + if (normalizedNames[i].contains(lowerFilter)) { + newList.add(fileList.get(i)); + } } if (newList.isEmpty()) { @@ -943,9 +968,11 @@ public class UtilityCommands { if (checkName.length() > 3 && checkName.length() <= 16) { UUID fromName = Fawe.imp().getUUID(checkName); if (fromName != null) { - lowerFilter = filter.replaceFirst(checkName, fromName.toString()).toLowerCase(); + lowerFilter = filter.replaceFirst(checkName, fromName.toString()).toLowerCase(Locale.ROOT); for (int i = 0; i < normalizedNames.length; i++) { - if (normalizedNames[i].startsWith(lowerFilter)) newList.add(fileList.get(i)); + if (normalizedNames[i].startsWith(lowerFilter)) { + newList.add(fileList.get(i)); + } } } } @@ -957,7 +984,9 @@ public class UtilityCommands { } public static void allFiles(File[] files, boolean recursive, Consumer task) { - if (files == null || files.length == 0) return; + if (files == null || files.length == 0) { + return; + } for (File f : files) { if (f.isDirectory()) { if (recursive) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/WorldEditCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/WorldEditCommands.java index b99c7e9cd..76afac4b8 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/WorldEditCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/WorldEditCommands.java @@ -78,22 +78,22 @@ public class WorldEditCommands { FaweVersion fVer = Fawe.get().getVersion(); String fVerStr = fVer == null ? "unknown" : "-" + fVer.build; actor.print(TextComponent.of("FastAsyncWorldEdit" + fVerStr + " created by Empire92, MattBDev, IronApollo, dordsor21 and NotMyFault")); - + if (fVer != null) { FaweVersion version = Fawe.get().getVersion(); Date date = new GregorianCalendar(2000 + version.year, version.month - 1, version.day) .getTime(); - - TextComponent dateArg = TextComponent.of(date.toLocaleString()); - TextComponent commitArg = TextComponent.of(Integer.toHexString(version.hash)); - TextComponent buildArg = TextComponent.of(version.build); - TextComponent platformArg = TextComponent.of(Settings.IMP.PLATFORM); - - actor.printInfo(TranslatableComponent.of("worldedit.version.version", dateArg, commitArg, buildArg, platformArg)); + + TextComponent dateArg = TextComponent.of(date.toLocaleString()); + TextComponent commitArg = TextComponent.of(Integer.toHexString(version.hash)); + TextComponent buildArg = TextComponent.of(version.build); + TextComponent platformArg = TextComponent.of(Settings.IMP.PLATFORM); + + actor.printInfo(TranslatableComponent.of("worldedit.version.version", dateArg, commitArg, buildArg, platformArg)); } - - actor.printInfo(TextComponent.of("Wiki: https://wiki.intellectualsites.com/FastAsyncWorldEdit/index")); - + + actor.printInfo(TextComponent.of("Wiki: https://wiki.intellectualsites.com/FastAsyncWorldEdit/index")); + PlatformManager pm = we.getPlatformManager(); TextComponentProducer producer = new TextComponentProducer(); @@ -104,19 +104,19 @@ public class WorldEditCommands { .append(TextComponent.of("(" + platform.getPlatformVersion() + ")")) ).newline(); } - actor.print(new MessageBox("Platforms", producer, TextColor.GRAY).create()); - - producer.reset(); - for (Capability capability : Capability.values()) { + actor.print(new MessageBox("Platforms", producer, TextColor.GRAY).create()); + + producer.reset(); + for (Capability capability : Capability.values()) { Platform platform = pm.queryCapability(capability); producer.append( - TextComponent.of(capability.name(), TextColor.GRAY) + TextComponent.of(capability.name(), TextColor.GRAY) .append(TextComponent.of(": ") .append(TextComponent.of(platform != null ? platform.getPlatformName() : "NONE"))) ).newline(); } actor.print(new MessageBox("Capabilities", producer, TextColor.GRAY).create()); - + } @Command( diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/AreaPickaxe.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/AreaPickaxe.java index 720b17ca0..465957dee 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/AreaPickaxe.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/AreaPickaxe.java @@ -67,7 +67,7 @@ public class AreaPickaxe implements BlockTool { try { for (int x = ox - range; x <= ox + range; ++x) { - for (int y = oy - range; y <= oy + range; ++y) { + for (int y = oy - range; y <= oy + range; ++y) { for (int z = oz - range; z <= oz + range; ++z) { if (!initialType.equals(editSession.getBlock(x, y, z).getBlockType())) { continue; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BrushTool.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BrushTool.java index c9f52a524..91d1079c9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BrushTool.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BrushTool.java @@ -280,7 +280,7 @@ public class BrushTool /** * Set the brush. * - * @param brush tbe brush + * @param brush the brush * @param permission the permission */ public void setBrush(Brush brush, String permission) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/NavigationWand.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/NavigationWand.java index 1842cd0b6..9a3ab6d8a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/NavigationWand.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/NavigationWand.java @@ -33,7 +33,7 @@ public enum NavigationWand implements DoubleActionTraceTool { @Override public boolean actSecondary(Platform server, LocalConfiguration config, Player player, LocalSession session) { if (!player.hasPermission("worldedit.navigation.jumpto.tool")) { - return false; + return false; } final int maxDist = config.navigationWandMaxDistance; if (maxDist <= 0) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/entity/Player.java b/worldedit-core/src/main/java/com/sk89q/worldedit/entity/Player.java index c7eee03d9..52527a05f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/entity/Player.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/entity/Player.java @@ -55,7 +55,7 @@ import java.io.File; import javax.annotation.Nullable; /** - * Represents a player + * Represents a player. */ public interface Player extends Entity, Actor { @@ -356,30 +356,29 @@ public interface Player extends Entity, Actor { void setSelection(Region region); /** - * Get the player's current selection (or null) + * Get the player's selection region. If the selection is defined in + * a different world, the {@code IncompleteRegionException} + * exception will be thrown. * - * @return + * @return a region + * @throws IncompleteRegionException if no region is selected */ - default Region getSelection() { - try { - return getSession().getSelection(getWorld()); - } catch (IncompleteRegionException e) { - return null; - } + default Region getSelection() throws IncompleteRegionException { + return getSession().getSelection(getWorld()); } /** - * Set the player's WorldEdit selection + * Set the player's WorldEdit selection. * - * @param selector + * @param selector the selector */ default void setSelection(RegionSelector selector) { getSession().setRegionSelector(getWorld(), selector); } /** - * Get the World the player is editing in (may not match the world they are in)
- e.g., If - * they are editing a CFI world.
+ * Get the world the player is editing in. The world may or may not match the world they are in. + * For example, if they are editing a CFI world. * * @return Editing world */ @@ -396,7 +395,7 @@ public interface Player extends Entity, Actor { } /** - * Unregister this player (deletes all metadata etc) - Usually called on logout + * Unregister this player, deleting all data stored during the logon session. */ default void unregister() { cancel(true); @@ -410,7 +409,7 @@ public interface Player extends Entity, Actor { void sendTitle(Component title, Component sub); /** - * Loads any history items from disk: - Should already be called if history on disk is enabled + * Loads any history items from disk: - Should already be called if history on disk is enabled. */ default void loadClipboardFromDisk() { File file = MainUtil.getFile(Fawe.imp().getDirectory(), diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/event/extent/EditSessionEvent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/event/extent/EditSessionEvent.java index 9288cc79a..de0db9c29 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/event/extent/EditSessionEvent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/event/extent/EditSessionEvent.java @@ -89,7 +89,8 @@ public class EditSessionEvent extends Event implements Cancellable { * * @return the actor, which may be null if unavailable */ - public @Nullable Actor getActor() { + @Nullable + public Actor getActor() { return actor; } @@ -98,7 +99,8 @@ public class EditSessionEvent extends Event implements Cancellable { * * @return the world */ - public @Nullable World getWorld() { + @Nullable + public World getWorld() { return world; } 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 cfdbc90c6..2365cac96 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 @@ -286,7 +286,7 @@ public class DefaultBlockParser extends InputParser { stateString = blockAndExtraData[0].substring(stateStart + 1, blockAndExtraData[0].length() - 1); } String[] stateProperties = EMPTY_STRING_ARRAY; - if(stateString != null) { + if (stateString != null) { stateProperties = stateString.split(","); } if (typeString.isEmpty()) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/RichParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/RichParser.java index 5d625826d..66fe34d98 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/RichParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/RichParser.java @@ -55,8 +55,12 @@ public abstract class RichParser extends InputParser { @Override public E parseFromInput(String input, ParserContext context) throws InputParseException { - if (!input.startsWith(this.prefix)) return null; - if (input.length() < this.prefix.length()) return null; + if (!input.startsWith(this.prefix)) { + return null; + } + if (input.length() < this.prefix.length()) { + return null; + } String[] arguments = extractArguments(input.substring(prefix.length()), true); return parseFromInput(arguments, context); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/AdjacentMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/AdjacentMaskParser.java index 128c51d9a..c9d24e1a8 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/AdjacentMaskParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/AdjacentMaskParser.java @@ -29,14 +29,18 @@ public class AdjacentMaskParser extends RichParser { @Override protected Mask parseFromInput(@NotNull String[] arguments, ParserContext context) throws InputParseException { - if (arguments.length == 0) return null; + if (arguments.length == 0) { + return null; + } Mask subMask = worldEdit.getMaskFactory().parseFromInput(arguments[0], context); int min = arguments.length > 1 ? Integer.parseInt(arguments[1]) : -1; int max = arguments.length > 2 ? Integer.parseInt(arguments[2]) : -1; if (min == -1 && max == -1) { min = 1; max = 8; - } else if (max == -1) max = min; + } else if (max == -1) { + max = min; + } if (max >= 8 && min == 1) { return new AdjacentAnyMask(subMask); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/AngleMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/AngleMaskParser.java index a3b3982ea..0c7acf214 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/AngleMaskParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/AngleMaskParser.java @@ -30,14 +30,15 @@ public class AngleMaskParser extends RichParser { @Override protected Mask parseFromInput(@NotNull String[] arguments, ParserContext context) throws InputParseException { - if (arguments.length < 2 || arguments.length > 2 + flags.length) return null; + if (arguments.length < 2 || arguments.length > 2 + flags.length) { + return null; + } String minArg = arguments[0]; String maxArg = arguments[1]; boolean degree = minArg.endsWith("d"); if (degree ^ maxArg.endsWith("d")) { throw new InputParseException("Cannot combine degree with block-step"); } - double min, max; boolean overlay = false; if (arguments.length > 2) { for (int index = 2; index < 2 + flags.length; index++) { @@ -49,6 +50,8 @@ public class AngleMaskParser extends RichParser { } } } + double min; + double max; if (degree) { double minDeg = Double.parseDouble(minArg.substring(0, minArg.length() - 1)); double maxDeg = Double.parseDouble(maxArg.substring(0, maxArg.length() - 1)); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/DefaultMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/DefaultMaskParser.java index 8d467a46e..82685458f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/DefaultMaskParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/DefaultMaskParser.java @@ -118,7 +118,7 @@ //// () -> { //// if (full.length() == 1) return new ArrayList<>(dispatcher.getPrimaryAliases()); //// return dispatcher.getAliases().stream().filter( -//// s -> s.startsWith(command.toLowerCase()) +//// s -> s.startsWith(command.toLowerCase(Locale.ROOT)) //// ).collect(Collectors.toList()); //// } //// ); @@ -147,7 +147,7 @@ // input = input.substring(input.indexOf(char0) + 1); // mask = parseFromInput(char0 + "[" + input + "]", context); // if (actor != null) { -// actor.print(Caption.of("fawe.worldedit.help.command.clarifying.bracket" , char0 + "[" + input + "]")); +// actor.print(Caption.of("fawe.worldedit.help.command.clarifying.bracket", char0 + "[" + input + "]")); // } // return mask; // } @@ -164,7 +164,7 @@ // { // try { // builder.addRegex(full); -// } catch (InputParseException ignore) {} +// } catch (InputParseException ignored) {} // } // if (mask == null) { // context.setPreferringWildcard(false); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/ExtremaMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/ExtremaMaskParser.java index c6227a9c1..50fa9b849 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/ExtremaMaskParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/ExtremaMaskParser.java @@ -30,14 +30,17 @@ public class ExtremaMaskParser extends RichParser { @Override protected Mask parseFromInput(@NotNull String[] arguments, ParserContext context) throws InputParseException { - if (arguments.length < 2 || arguments.length > 2 + flags.length) return null; + if (arguments.length < 2 || arguments.length > 2 + flags.length) { + return null; + } String minArg = arguments[0]; String maxArg = arguments[1]; boolean degree = minArg.endsWith("d"); if (degree ^ maxArg.endsWith("d")) { throw new InputParseException("Cannot combine degree with block-step"); } - double min, max; + double min; + double max; boolean overlay = false; if (arguments.length > 2) { for (int index = 2; index < 2 + flags.length; index++) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/ROCAngleMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/ROCAngleMaskParser.java index 4dee4289e..fd4672ae7 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/ROCAngleMaskParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/ROCAngleMaskParser.java @@ -30,14 +30,17 @@ public class ROCAngleMaskParser extends RichParser { @Override protected Mask parseFromInput(@NotNull String[] arguments, ParserContext context) throws InputParseException { - if (arguments.length < 2 || arguments.length > 2 + flags.length) return null; + if (arguments.length < 2 || arguments.length > 2 + flags.length) { + return null; + } String minArg = arguments[0]; String maxArg = arguments[1]; boolean degree = minArg.endsWith("d"); if (degree ^ maxArg.endsWith("d")) { throw new InputParseException("Cannot combine degree with block-step"); } - double min, max; + double min; + double max; boolean overlay = false; if (arguments.length > 2) { for (int index = 2; index < 2 + flags.length; index++) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/RadiusMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/RadiusMaskParser.java index bfc78863a..914159218 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/RadiusMaskParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/RadiusMaskParser.java @@ -26,7 +26,9 @@ public class RadiusMaskParser extends RichParser { @Override protected Mask parseFromInput(@NotNull String[] arguments, ParserContext context) throws InputParseException { - if (arguments.length < 2) return null; + if (arguments.length < 2) { + return null; + } int min = Integer.parseInt(arguments[0]); int max = Integer.parseInt(arguments[1]); return new RadiusMask(min, max); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/SimplexMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/SimplexMaskParser.java index 450416839..09424b6c8 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/SimplexMaskParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/SimplexMaskParser.java @@ -27,7 +27,9 @@ public class SimplexMaskParser extends RichParser { @Override protected Mask parseFromInput(@NotNull String[] arguments, ParserContext context) throws InputParseException { - if (arguments.length != 3) return null; + if (arguments.length != 3) { + return null; + } double scale = Double.parseDouble(arguments[0]); double min = Double.parseDouble(arguments[1]); double max = Double.parseDouble(arguments[2]); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/WallMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/WallMaskParser.java index d1b7c0f7b..7b4236315 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/WallMaskParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/WallMaskParser.java @@ -5,7 +5,10 @@ import com.google.common.collect.ImmutableList; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.ParserContext; -import com.sk89q.worldedit.function.mask.*; +import com.sk89q.worldedit.function.mask.BlockMask; +import com.sk89q.worldedit.function.mask.ExistingBlockMask; +import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.function.mask.MaskIntersection; import com.sk89q.worldedit.internal.registry.SimpleInputParser; import com.sk89q.worldedit.world.block.BlockTypes; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/RandomPatternParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/RandomPatternParser.java index 1cb8729db..bc640d707 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/RandomPatternParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/RandomPatternParser.java @@ -26,6 +26,8 @@ import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.RandomPattern; import com.sk89q.worldedit.internal.registry.InputParser; +import com.sk89q.worldedit.util.formatting.text.TextComponent; +import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; import java.util.List; import java.util.stream.Stream; @@ -79,7 +81,7 @@ public class RandomPatternParser extends InputParser { String[] p = token.split("%", 2); if (p.length < 2) { - throw new InputParseException("Missing the type after the % symbol for '" + input + "'"); + throw new InputParseException(TranslatableComponent.of("worldedit.error.parser.missing-random-type", TextComponent.of(input))); } else { chance = Double.parseDouble(p[0]); innerPattern = worldEdit.getPatternFactory().parseFromInput(p[1], context); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/TypeOrStateApplyingPatternParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/TypeOrStateApplyingPatternParser.java index 25e4741ab..d2c9a85ec 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/TypeOrStateApplyingPatternParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/TypeOrStateApplyingPatternParser.java @@ -30,6 +30,8 @@ import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.StateApplyingPattern; import com.sk89q.worldedit.function.pattern.TypeApplyingPattern; import com.sk89q.worldedit.internal.registry.InputParser; +import com.sk89q.worldedit.util.formatting.text.TextComponent; +import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; import java.util.HashMap; import java.util.Map; @@ -82,19 +84,29 @@ public class TypeOrStateApplyingPatternParser extends InputParser { worldEdit.getBlockFactory().parseFromInput(type, context).getBlockType().getDefaultState()); } else { // states given - if (!parts[1].endsWith("]")) throw new InputParseException("State is missing trailing ']'"); + if (!parts[1].endsWith("]")) { + throw new InputParseException(TranslatableComponent.of("worldedit.error.parser.missing-rbracket")); + } final String[] states = parts[1].substring(0, parts[1].length() - 1).split(","); Map statesToSet = new HashMap<>(); for (String state : states) { - if (state.isEmpty()) throw new InputParseException("Empty part in state"); + if (state.isEmpty()) { + throw new InputParseException(TranslatableComponent.of("worldedit.error.parser.empty-state")); + } String[] propVal = state.split("=", 2); - if (propVal.length != 2) throw new InputParseException("Missing '=' separator"); + if (propVal.length != 2) { + throw new InputParseException(TranslatableComponent.of("worldedit.error.parser.missing-equals-separator")); + } final String prop = propVal[0]; - if (prop.isEmpty()) throw new InputParseException("Empty property in state"); + if (prop.isEmpty()) { + throw new InputParseException(TranslatableComponent.of("worldedit.error.parser.empty-property")); + } final String value = propVal[1]; - if (value.isEmpty()) throw new InputParseException("Empty value in state"); + if (value.isEmpty()) { + throw new InputParseException(TranslatableComponent.of("worldedit.error.parser.empty-value")); + } if (statesToSet.put(prop, value) != null) { - throw new InputParseException("Duplicate properties in state"); + throw new InputParseException(TranslatableComponent.of("worldedit.error.parser.duplicate-property", TextComponent.of(prop))); } } if (type.isEmpty()) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/input/ParserContext.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/input/ParserContext.java index c37d66368..ce447801d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/input/ParserContext.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/input/ParserContext.java @@ -36,10 +36,14 @@ import javax.annotation.Nullable; */ public class ParserContext { - private @Nullable Extent extent; - private @Nullable LocalSession session; - private @Nullable World world; - private @Nullable Actor actor; + @Nullable + private Extent extent; + @Nullable + private LocalSession session; + @Nullable + private World world; + @Nullable + private Actor actor; private boolean restricted = true; private boolean tryLegacy = true; private boolean preferringWildcard; @@ -71,7 +75,8 @@ public class ParserContext { * * @return an extent */ - public @Nullable Extent getExtent() { + @Nullable + public Extent getExtent() { return extent; } @@ -89,7 +94,8 @@ public class ParserContext { * * @return a session */ - public @Nullable LocalSession getSession() { + @Nullable + public LocalSession getSession() { return session; } @@ -107,7 +113,8 @@ public class ParserContext { * * @return a world */ - public @Nullable World getWorld() { + @Nullable + public World getWorld() { return world; } @@ -126,7 +133,8 @@ public class ParserContext { * * @return an actor, or null */ - public @Nullable Actor getActor() { + @Nullable + public Actor getActor() { return actor; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/AbstractPlayerActor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/AbstractPlayerActor.java index a594960c2..d180ef31a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/AbstractPlayerActor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/AbstractPlayerActor.java @@ -76,22 +76,8 @@ import javax.annotation.Nullable; * players that make use of WorldEdit. */ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { - private final Map meta; - public AbstractPlayerActor(Map meta) { - this.meta = meta; - } - - public AbstractPlayerActor() { - this(new ConcurrentHashMap<>()); - } - - @Override - public Map getRawMeta() { - return meta; - } - // Queue for async tasks private AtomicInteger runningCount = new AtomicInteger(); private AsyncNotifyQueue asyncNotifyQueue = new AsyncNotifyQueue( @@ -111,6 +97,14 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { } }); + public AbstractPlayerActor(Map meta) { + this.meta = meta; + } + + public AbstractPlayerActor() { + this(new ConcurrentHashMap<>()); + } + @Override public final Extent getExtent() { return getWorld(); @@ -146,6 +140,11 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { } } + @Override + public Map getRawMeta() { + return meta; + } + @Override public boolean isHoldingPickAxe() { ItemType item = getItemInHand(HandSide.MAIN_HAND).getType(); @@ -250,7 +249,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { return false; } return getWorld().getBlock(location.add(0, -1, 0)).getBlockType().getMaterial() - .isMovementBlocker(); + .isMovementBlocker(); } @Override @@ -522,6 +521,52 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { return getCardinalDirection(0); } + /** + * Get the player's current allowed WorldEdit regions. + * + * @return an array of allowed regions + */ + public Region[] getCurrentRegions() { + return getCurrentRegions(FaweMaskManager.MaskType.MEMBER); + } + + public Region[] getCurrentRegions(FaweMaskManager.MaskType type) { + return WEManager.IMP.getMask(this, type); + } + + /** + * Get the largest region in the player's allowed WorldEdit region. + */ + public Region getLargestRegion() { + long area = 0; + Region max = null; + for (Region region : this.getCurrentRegions()) { + final long tmp = region.getVolume(); + if (tmp > area) { + area = tmp; + max = region; + } + } + return max; + } + + public void setSelection(Region region) { + RegionSelector selector; + if (region instanceof ConvexPolyhedralRegion) { + selector = new ConvexPolyhedralRegionSelector((ConvexPolyhedralRegion) region); + } else if (region instanceof CylinderRegion) { + selector = new CylinderRegionSelector((CylinderRegion) region); + } else if (region instanceof Polygonal2DRegion) { + selector = new Polygonal2DRegionSelector((Polygonal2DRegion) region); + } else { + selector = new CuboidRegionSelector(null, region.getMinimumPoint(), + region.getMaximumPoint()); + } + selector.setWorld(region.getWorld()); + + getSession().setRegionSelector(getWorld(), selector); + } + @Override public Direction getCardinalDirection(int yawOffset) { final Location location = getLocation(); @@ -631,6 +676,36 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { return null; } + /** + * Run a task either async, or on the current thread. + * + * @param ifFree the task to run if free + * @param checkFree Whether to first check if a task is running + * @param async TODO description + * @return false if the task was ran or queued + */ + public boolean runAction(Runnable ifFree, boolean checkFree, boolean async) { + if (checkFree) { + if (runningCount.get() != 0) { + return false; + } + } + Runnable wrapped = () -> { + try { + runningCount.addAndGet(1); + ifFree.run(); + } finally { + runningCount.decrementAndGet(); + } + }; + if (async) { + asyncNotifyQueue.run(wrapped); + } else { + TaskManager.IMP.taskNow(wrapped, false); + } + return true; + } + @Override public boolean canDestroyBedrock() { return hasPermission("worldedit.override.bedrock"); @@ -690,84 +765,4 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { public > void sendFakeBlock(BlockVector3 pos, B block) { } - - /** - * Run a task either async, or on the current thread. - * - * @param ifFree the task to run if free - * @param checkFree Whether to first check if a task is running - * @param async TODO description - * @return false if the task was ran or queued - */ - public boolean runAction(Runnable ifFree, boolean checkFree, boolean async) { - if (checkFree) { - if (runningCount.get() != 0) { - return false; - } - } - Runnable wrapped = () -> { - try { - runningCount.addAndGet(1); - ifFree.run(); - } finally { - runningCount.decrementAndGet(); - } - }; - if (async) { - asyncNotifyQueue.run(wrapped); - } else { - TaskManager.IMP.taskNow(wrapped, false); - } - return true; - } - - - /** - * Get the player's current allowed WorldEdit regions. - * - * @return an array of allowed regions - */ - public Region[] getCurrentRegions() { - return getCurrentRegions(FaweMaskManager.MaskType.MEMBER); - } - - public Region[] getCurrentRegions(FaweMaskManager.MaskType type) { - return WEManager.IMP.getMask(this, type); - } - - /** - * Get the largest region in the player's allowed WorldEdit region. - * - * @return - */ - public Region getLargestRegion() { - long area = 0; - Region max = null; - for (Region region : this.getCurrentRegions()) { - final long tmp = region.getVolume(); - if (tmp > area) { - area = tmp; - max = region; - } - } - return max; - } - - public void setSelection(Region region) { - RegionSelector selector; - if (region instanceof ConvexPolyhedralRegion) { - selector = new ConvexPolyhedralRegionSelector((ConvexPolyhedralRegion) region); - } else if (region instanceof CylinderRegion) { - selector = new CylinderRegionSelector((CylinderRegion) region); - } else if (region instanceof Polygonal2DRegion) { - selector = new Polygonal2DRegionSelector((Polygonal2DRegion) region); - } else { - selector = new CuboidRegionSelector(null, region.getMinimumPoint(), - region.getMaximumPoint()); - } - selector.setWorld(region.getWorld()); - - getSession().setRegionSelector(getWorld(), selector); - } - } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/Platform.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/Platform.java index 96d52beb1..69e01bebb 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/Platform.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/Platform.java @@ -98,7 +98,8 @@ public interface Platform { * * @return the watchdog service, or {@code null} if none */ - default @Nullable Watchdog getWatchdog() { + @Nullable + default Watchdog getWatchdog() { return null; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformCommandManager.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformCommandManager.java index 4444a4524..50ec0c47c 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformCommandManager.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformCommandManager.java @@ -620,7 +620,9 @@ public final class PlatformCommandManager { } public int parseCommand(String args, InjectedValueAccess access) { - if (args.isEmpty()) return 0; + if (args.isEmpty()) { + return 0; + } String[] split = parseArgs(args) .map(Substring::getSubstring) .toArray(String[]::new); @@ -841,6 +843,7 @@ public final class PlatformCommandManager { } throw t; } + event.setSuggestions(suggestions.stream() .map(suggestion -> { int noSlashLength = arguments.length() - 1; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformManager.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformManager.java index b9d9abe57..762c462d4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformManager.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformManager.java @@ -77,7 +77,8 @@ public class PlatformManager { private final PlatformCommandManager platformCommandManager; private final List platforms = new ArrayList<>(); private final Map preferences = new EnumMap<>(Capability.class); - private @Nullable String firstSeenVersion; + @Nullable + private String firstSeenVersion; private final AtomicBoolean initialized = new AtomicBoolean(); private final AtomicBoolean configured = new AtomicBoolean(); @@ -112,9 +113,8 @@ public class PlatformManager { // Make sure that versions are in sync if (firstSeenVersion != null) { if (!firstSeenVersion.equals(platform.getVersion())) { - logger.warn("Multiple ports of WorldEdit are installed but they report different versions ({} and {}). " + - "If these two versions are truly different, then you may run into unexpected crashes and errors.", - new Object[]{ firstSeenVersion, platform.getVersion() }); + logger.warn("Multiple ports of WorldEdit are installed but they report different versions ({} and {}). " + + "If these two versions are truly different, then you may run into unexpected crashes and errors.", firstSeenVersion, platform.getVersion()); } } else { firstSeenVersion = platform.getVersion(); @@ -209,7 +209,8 @@ public class PlatformManager { * @param capability the capability * @return the most preferred platform, or null if no platform was found */ - private synchronized @Nullable Platform findMostPreferred(Capability capability) { + @Nullable + private synchronized Platform findMostPreferred(Capability capability) { Platform preferred = null; Preference highest = null; @@ -352,7 +353,9 @@ public class PlatformManager { } virtual.handleBlockInteract(player, vector.toBlockPoint(), event); - if (event.isCancelled()) return; + if (event.isCancelled()) { + return; + } } if (event.getType() == Interaction.HIT) { @@ -363,8 +366,8 @@ public class PlatformManager { if (superPickaxe != null && superPickaxe.canUse(player)) { player.runAction(() -> reset(superPickaxe) .actPrimary(queryCapability(Capability.WORLD_EDITING), - getConfiguration(), player, session, location), false, true); - event.setCancelled(true); + getConfiguration(), player, session, location), false, true); + event.setCancelled(true); return; } } @@ -373,11 +376,11 @@ public class PlatformManager { if (tool instanceof DoubleActionBlockTool && tool.canUse(player)) { player.runAction(() -> reset((DoubleActionBlockTool) tool) .actSecondary(queryCapability(Capability.WORLD_EDITING), - getConfiguration(), player, session, location), false, true); - event.setCancelled(true); - } + getConfiguration(), player, session, location), false, true); + event.setCancelled(true); + } - } else if (event.getType() == Interaction.OPEN) { + } else if (event.getType() == Interaction.OPEN) { Tool tool = session.getTool(player); if (tool instanceof BlockTool && tool.canUse(player)) { if (player.checkAction()) { @@ -385,14 +388,14 @@ public class PlatformManager { BlockTool blockTool = (BlockTool) tool; if (!(tool instanceof BrushTool)) { blockTool = reset(blockTool); - } + } blockTool.actPrimary(queryCapability(Capability.WORLD_EDITING), - getConfiguration(), player, session, location); + getConfiguration(), player, session, location); }, false, true); event.setCancelled(true); } - } - } + } + } } catch (Throwable e) { handleThrowable(e, actor); } finally { @@ -403,7 +406,7 @@ public class PlatformManager { public void handleThrowable(Throwable e, Actor actor) { FaweException faweException = FaweException.get(e); if (faweException != null) { - actor.print(TranslatableComponent.of("fawe.cancel.worldedit.cancel.reason" , faweException.getComponent())); + actor.print(TranslatableComponent.of("fawe.cancel.worldedit.cancel.reason", faweException.getComponent())); } else { actor.printError("Please report this error: [See console]"); actor.printRaw(e.getClass().getName() + ": " + e.getMessage()); @@ -423,7 +426,9 @@ public class PlatformManager { logger.info("virtualWorld was not null in handlePlayerInput()"); } virtual.handlePlayerInput(player, event); - if (event.isCancelled()) return; + if (event.isCancelled()) { + return; + } } try { @@ -432,10 +437,10 @@ public class PlatformManager { Tool tool = session.getTool(player); if (tool instanceof DoubleActionTraceTool && tool.canUse(player)) { player.runAsyncIfFree(() -> reset((DoubleActionTraceTool) tool).actSecondary(queryCapability(Capability.WORLD_EDITING), - getConfiguration(), player, session)); - event.setCancelled(true); - return; - } + getConfiguration(), player, session)); + event.setCancelled(true); + return; + } break; } @@ -445,10 +450,10 @@ public class PlatformManager { if (tool instanceof TraceTool && tool.canUse(player)) { //todo this needs to be fixed so the event is canceled after actPrimary is used and returns true player.runAction(() -> reset((TraceTool) tool).actPrimary(queryCapability(Capability.WORLD_EDITING), - getConfiguration(), player, session), false, true); - event.setCancelled(true); - return; - } + getConfiguration(), player, session), false, true); + event.setCancelled(true); + return; + } break; } @@ -456,7 +461,7 @@ public class PlatformManager { } catch (Throwable e) { FaweException faweException = FaweException.get(e); if (faweException != null) { - player.print(TranslatableComponent.of("fawe.cancel.worldedit.cancel.reason" , faweException.getComponent())); + player.print(TranslatableComponent.of("fawe.cancel.worldedit.cancel.reason", faweException.getComponent())); } else { player.printError("Please report this error: [See console]"); player.printRaw(e.getClass().getName() + ": " + e.getMessage()); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/Bindings.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/Bindings.java index 19e50170f..ba0916961 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/Bindings.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/Bindings.java @@ -41,7 +41,9 @@ public class Bindings { private boolean register(Method method, InjectedValueStore store, CommandManager manager) { // Check that it has the binding Binding binding = method.getAnnotation(Binding.class); - if (binding == null) return false; + if (binding == null) { + return false; + } Annotation[] annotations = method.getAnnotations(); // Get the key @@ -49,7 +51,7 @@ public class Bindings { Key key; if ( annotations.length == 1) { key = Key.of(ret); - }else if (annotations.length == 2) { + } else if (annotations.length == 2) { Annotation annotation = annotations[0] == binding ? annotations[1] : annotations[0]; key = Key.of(ret, annotation); } else { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/ConsumeBindings.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/ConsumeBindings.java index 0d6d40693..42149269d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/ConsumeBindings.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/ConsumeBindings.java @@ -124,7 +124,7 @@ public class ConsumeBindings extends Bindings { uuid = Fawe.imp().getUUID(argument); } if (uuid == null) { - throw new InputParseException(Caption.toString(Caption.of("fawe.error.player.not.found" , argument))); + throw new InputParseException(Caption.toString(Caption.of("fawe.error.player.not.found", argument))); } return uuid; } @@ -202,7 +202,9 @@ public class ConsumeBindings extends Bindings { public BiomeType getBiomeType(String argument) throws WorldEditException { if (argument != null) { - if (MathMan.isInteger(argument)) return BiomeTypes.getLegacy(Integer.parseInt(argument)); + if (MathMan.isInteger(argument)) { + return BiomeTypes.getLegacy(Integer.parseInt(argument)); + } BiomeRegistry biomeRegistry = WorldEdit.getInstance().getPlatformManager() .queryCapability(Capability.GAME_HOOKS).getRegistries().getBiomeRegistry(); Collection knownBiomes = BiomeType.REGISTRY.values(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/PrimitiveBindings.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/PrimitiveBindings.java index af9cc9a68..af2fb6ce1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/PrimitiveBindings.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/PrimitiveBindings.java @@ -103,7 +103,9 @@ public class PrimitiveBindings extends Bindings { @Binding public Vector3 getVector3(String argument) { String[] radii = argument.split(","); - final double radiusX, radiusY, radiusZ; + final double radiusX; + final double radiusY; + final double radiusZ; switch (radii.length) { case 1: radiusX = radiusY = radiusZ = PrimitiveBindings.parseNumericInput(radii[0]); @@ -133,7 +135,8 @@ public class PrimitiveBindings extends Bindings { public Vector2 getVector2(String argument) { String radiusString = argument; String[] radii = radiusString.split(","); - final double radiusX, radiusZ; + final double radiusX; + final double radiusZ; switch (radii.length) { case 1: radiusX = radiusZ = PrimitiveBindings.parseNumericInput(radii[0]); @@ -161,7 +164,9 @@ public class PrimitiveBindings extends Bindings { public BlockVector3 getBlockVector3(String argument) { String radiusString = argument; String[] radii = radiusString.split(","); - final double radiusX, radiusY, radiusZ; + final double radiusX; + final double radiusY; + final double radiusZ; switch (radii.length) { case 1: radiusX = radiusY = radiusZ = PrimitiveBindings.parseNumericInput(radii[0]); @@ -190,7 +195,8 @@ public class PrimitiveBindings extends Bindings { @Binding public BlockVector2 getBlockVector2(String argument) { String[] radii = argument.split(","); - final double radiusX, radiusZ; + final double radiusX; + final double radiusZ; switch (radii.length) { case 1: radiusX = radiusZ = parseNumericInput(radii[0]); @@ -214,7 +220,8 @@ public class PrimitiveBindings extends Bindings { * @return a number * @throws InputParseException thrown on parse error */ - public static @Nullable Double parseNumericInput(@Nullable String input) { + @Nullable + public static Double parseNumericInput(@Nullable String input) { if (input == null) { return null; } 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 31c42a8ba..5daf419b1 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 @@ -85,8 +85,8 @@ public class AbstractDelegateExtent implements Extent { } @Override - public BaseBlock getFullBlock(int x, int y, int z) { - return extent.getFullBlock(x, y, z); + public BlockState getBlock(int x, int y, int z) { + return extent.getBlock(x, y, z); } @Override @@ -100,39 +100,38 @@ public class AbstractDelegateExtent implements Extent { */ @Override - public boolean isQueueEnabled() { - return extent.isQueueEnabled(); + public BaseBlock getFullBlock(int x, int y, int z) { + return extent.getFullBlock(x, y, z); } @Override - public void disableQueue() { - try { - if (!(extent instanceof ForgetfulExtentBuffer)) { // placeholder - extent.disableQueue(); - } - } catch (FaweException ignored) { - } - if (extent instanceof AbstractDelegateExtent) { - Extent next = ((AbstractDelegateExtent) extent).getExtent(); - new ExtentTraverser(this).setNext(next); - } else { - getLogger(AbstractDelegateExtent.class).debug("Cannot disable queue"); - } + public BiomeType getBiomeType(int x, int y, int z) { + return extent.getBiomeType(x, y, z); } @Override - public void enableQueue() { - try { - extent.enableQueue(); - } catch (FaweException enableQueue) { - // TODO NOT IMPLEMENTED - THIS IS IMPORTANT (ForgetfulExtentBuffer is just a placeholder for now, it won't work) - new ExtentTraverser<>(this).setNext(new ForgetfulExtentBuffer(extent)); - } + public BiomeType getBiome(BlockVector3 position) { + return extent.getBiome(position); } /* History */ + @Override + public int getEmmittedLight(int x, int y, int z) { + return extent.getEmmittedLight(x, y, z); + } + + @Override + public int getSkyLight(int x, int y, int z) { + return extent.getSkyLight(x, y, z); + } + + @Override + public int getBrightness(int x, int y, int z) { + return extent.getBrightness(x, y, z); + } + public void setChangeSet(AbstractChangeSet changeSet) { if (extent instanceof HistoryExtent) { HistoryExtent history = ((HistoryExtent) extent); @@ -148,57 +147,6 @@ public class AbstractDelegateExtent implements Extent { } } - @Override - public int getMaxY() { - return extent.getMaxY(); - } - - @Override - public BlockState getBlock(int x, int y, int z) { - return extent.getBlock(x, y, z); - } - - @Override - @Nullable - public Entity createEntity(Location location, BaseEntity entity) { - return extent.createEntity(location, entity); - } - - @Override - public void removeEntity(int x, int y, int z, UUID uuid) { - extent.removeEntity(x, y, z, uuid); - } - - @Override - public List getEntities() { - return extent.getEntities(); - } - - @Override - public List getEntities(Region region) { - return extent.getEntities(region); - } - - @Override - public boolean fullySupports3DBiomes() { - return extent.fullySupports3DBiomes(); - } - - @Override - public BiomeType getBiome(BlockVector3 position) { - return extent.getBiome(position); - } - - @Override - public BiomeType getBiomeType(int x, int y, int z) { - return extent.getBiomeType(x, y, z); - } - - @Override - public boolean setBiome(int x, int y, int z, BiomeType biome) { - return extent.setBiome(x, y, z, biome); - } - @Override public > boolean setBlock(BlockVector3 position, T block) throws WorldEditException { @@ -216,49 +164,29 @@ public class AbstractDelegateExtent implements Extent { return setBlock(x, y, z, getBlock(x, y, z).toBaseBlock(tile)); } + @Override + public boolean fullySupports3DBiomes() { + return extent.fullySupports3DBiomes(); + } + + @Override + public boolean setBiome(int x, int y, int z, BiomeType biome) { + return extent.setBiome(x, y, z, biome); + } + @Override public boolean setBiome(BlockVector3 position, BiomeType biome) { return extent.setBiome(position.getX(), position.getY(), position.getZ(), biome); } - @Override - public boolean relight(int x, int y, int z) { - return extent.relight(x, y, z); - } - - @Override - public boolean relightBlock(int x, int y, int z) { - return extent.relightBlock(x, y, z); - } - - @Override - public boolean relightSky(int x, int y, int z) { - return extent.relightSky(x, y, z); - } - - @Override - public void setSkyLight(int x, int y, int z, int value) { - extent.setSkyLight(x, y, z, value); - } - @Override public void setBlockLight(int x, int y, int z, int value) { extent.setSkyLight(x, y, z, value); } @Override - public int getSkyLight(int x, int y, int z) { - return extent.getSkyLight(x, y, z); - } - - @Override - public int getEmmittedLight(int x, int y, int z) { - return extent.getEmmittedLight(x, y, z); - } - - @Override - public int getBrightness(int x, int y, int z) { - return extent.getBrightness(x, y, z); + public void setSkyLight(int x, int y, int z, int value) { + extent.setSkyLight(x, y, z, value); } @Override @@ -276,13 +204,61 @@ public class AbstractDelegateExtent implements Extent { return extent.getMaximumPoint(); } - protected Operation commitBefore() { - return null; + @Override + public List getEntities(Region region) { + return extent.getEntities(region); } @Override - public @Nullable - Operation commit() { + public List getEntities() { + return extent.getEntities(); + } + + @Override + @Nullable + public Entity createEntity(Location location, BaseEntity entity) { + return extent.createEntity(location, entity); + } + + @Override + public void removeEntity(int x, int y, int z, UUID uuid) { + extent.removeEntity(x, y, z, uuid); + } + + @Override + public boolean isQueueEnabled() { + return extent.isQueueEnabled(); + } + + @Override + public void enableQueue() { + try { + extent.enableQueue(); + } catch (FaweException enableQueue) { + // TODO NOT IMPLEMENTED - THIS IS IMPORTANT (ForgetfulExtentBuffer is just a placeholder for now, it won't work) + new ExtentTraverser<>(this).setNext(new ForgetfulExtentBuffer(extent)); + } + } + + @Override + public void disableQueue() { + try { + if (!(extent instanceof ForgetfulExtentBuffer)) { // placeholder + extent.disableQueue(); + } + } catch (FaweException ignored) { + } + if (extent instanceof AbstractDelegateExtent) { + Extent next = ((AbstractDelegateExtent) extent).getExtent(); + new ExtentTraverser(this).setNext(next); + } else { + getLogger(AbstractDelegateExtent.class).debug("Cannot disable queue"); + } + } + + @Override + @Nullable + public Operation commit() { Operation ours = commitBefore(); Operation other = null; if (extent != this) { @@ -299,6 +275,26 @@ public class AbstractDelegateExtent implements Extent { } } + @Override + public int getMaxY() { + return extent.getMaxY(); + } + + @Override + public boolean relight(int x, int y, int z) { + return extent.relight(x, y, z); + } + + @Override + public boolean relightBlock(int x, int y, int z) { + return extent.relightBlock(x, y, z); + } + + @Override + public boolean relightSky(int x, int y, int z) { + return extent.relightSky(x, y, z); + } + @Override public Extent addProcessor(IBatchProcessor processor) { if (Settings.IMP.EXPERIMENTAL.OTHER) { @@ -343,4 +339,8 @@ public class AbstractDelegateExtent implements Extent { } return this; } + + protected Operation commitBefore() { + return null; + } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/Extent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/Extent.java index c0e061791..21b2cd39f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/Extent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/Extent.java @@ -141,7 +141,8 @@ public interface Extent extends InputExtent, OutputExtent { * @param location the location * @return a reference to the created entity, or null if the entity could not be created */ - default @Nullable Entity createEntity(Location location, BaseEntity entity) { + @Nullable + default Entity createEntity(Location location, BaseEntity entity) { return null; } @@ -164,11 +165,15 @@ public interface Extent extends InputExtent, OutputExtent { } default void enableQueue() { - if (!isQueueEnabled()) throw FaweException._enableQueue; + if (!isQueueEnabled()) { + throw FaweException._enableQueue; + } } default void disableQueue() { - if (isQueueEnabled()) throw FaweException._disableQueue; + if (isQueueEnabled()) { + throw FaweException._disableQueue; + } } /* @@ -281,18 +286,26 @@ public interface Extent extends InputExtent, OutputExtent { int offset = state ? 0 : 1; for (int d = 0; d <= clearance; d++) { int y1 = y + d; - if (mask.test(MutableBlockVector3.get(x, y1, z)) != state) return y1 - offset; + if (mask.test(MutableBlockVector3.get(x, y1, z)) != state) { + return y1 - offset; + } int y2 = y - d; - if (mask.test(MutableBlockVector3.get(x, y2, z)) != state) return y2 + offset; + if (mask.test(MutableBlockVector3.get(x, y2, z)) != state) { + return y2 + offset; + } } if (clearanceAbove != clearanceBelow) { if (clearanceAbove < clearanceBelow) { for (int layer = y - clearance - 1; layer >= minY; layer--) { - if (mask.test(MutableBlockVector3.get(x, layer, z)) != state) return layer + offset; + if (mask.test(MutableBlockVector3.get(x, layer, z)) != state) { + return layer + offset; + } } } else { for (int layer = y + clearance + 1; layer <= maxY; layer++) { - if (mask.test(MutableBlockVector3.get(x, layer, z)) != state) return layer - offset; + if (mask.test(MutableBlockVector3.get(x, layer, z)) != state) { + return layer - offset; + } } } } @@ -310,26 +323,34 @@ public interface Extent extends InputExtent, OutputExtent { for (int d = 0; d <= clearance; d++) { int y1 = y + d; block = getBlock(x, y1, z); - if (block.getMaterial().isMovementBlocker() == state && block.getBlockType() != BlockTypes.__RESERVED__) return y1 - offset; + if (block.getMaterial().isMovementBlocker() == state && block.getBlockType() != BlockTypes.__RESERVED__) { + return y1 - offset; + } int y2 = y - d; block = getBlock(x, y2, z); - if (block.getMaterial().isMovementBlocker() == state && block.getBlockType() != BlockTypes.__RESERVED__) return y2 + offset; + if (block.getMaterial().isMovementBlocker() == state && block.getBlockType() != BlockTypes.__RESERVED__) { + return y2 + offset; + } } if (clearanceAbove != clearanceBelow) { if (clearanceAbove < clearanceBelow) { for (int layer = y - clearance - 1; layer >= minY; layer--) { block = getBlock(x, layer, z); - if (block.getMaterial().isMovementBlocker() == state && block.getBlockType() != BlockTypes.__RESERVED__) return layer + offset; + if (block.getMaterial().isMovementBlocker() == state && block.getBlockType() != BlockTypes.__RESERVED__) { + return layer + offset; + } } } else { for (int layer = y + clearance + 1; layer <= maxY; layer++) { block = getBlock(x, layer, z); - if (block.getMaterial().isMovementBlocker() == state && block.getBlockType() != BlockTypes.__RESERVED__) return layer - offset; + if (block.getMaterial().isMovementBlocker() == state && block.getBlockType() != BlockTypes.__RESERVED__) { + return layer - offset; + } } } } int result = state ? failedMin : failedMax; - if(result > 0 && !ignoreAir) { + if (result > 0 && !ignoreAir) { block = getBlock(x, result, z); return block.getBlockType().getMaterial().isAir() ? -1 : result; } @@ -464,7 +485,9 @@ public interface Extent extends InputExtent, OutputExtent { ExtentTraverser next = traverser.next(); if (next != null) { Extent child = next.get(); - if (child instanceof NullExtent) return true; + if (child instanceof NullExtent) { + return true; + } traverser.setNext(nullExtent); child.cancel(); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/InputExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/InputExtent.java index b7bec77d2..3d3b695c7 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/InputExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/InputExtent.java @@ -58,7 +58,7 @@ public interface InputExtent { } /** - * Get a immutable snapshot of the block at the given location. + * Get an immutable snapshot of the block at the given location. * * @param position position of the block * @return the block 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 b178c26fc..3b47245fd 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 @@ -124,7 +124,9 @@ public class MaskingExtent extends AbstractDelegateExtent implements IBatchProce @Override public Extent construct(Extent child) { - if (child == getExtent()) return this; + if (child == getExtent()) { + return this; + } return new MaskingExtent(child, this.mask.copy(), this.threadIdToFilter); } 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 ac619de26..d87ea7c2a 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 @@ -100,7 +100,6 @@ public class BlockArrayClipboard implements Clipboard { @Override public void setOrigin(BlockVector3 origin) { -// this.origin = origin; getParent().setOrigin(origin.subtract(region.getMinimumPoint())); } @@ -117,9 +116,9 @@ public class BlockArrayClipboard implements Clipboard { @Override public BlockState getBlock(BlockVector3 position) { if (region.contains(position)) { - int x = position.getBlockX()- origin.getX(); - int y = position.getBlockY()- origin.getY(); - int z = position.getBlockZ()- origin.getZ(); + int x = position.getBlockX() - origin.getX(); + int y = position.getBlockY() - origin.getY(); + int z = position.getBlockZ() - origin.getZ(); return getParent().getBlock(x, y, z); } @@ -128,10 +127,10 @@ public class BlockArrayClipboard implements Clipboard { @Override public BaseBlock getFullBlock(BlockVector3 position) { - if(region.contains(position)) { - int x = position.getBlockX()- origin.getX(); - int y = position.getBlockY()- origin.getY(); - int z = position.getBlockZ()- origin.getZ(); + if (region.contains(position)) { + int x = position.getBlockX() - origin.getX(); + int y = position.getBlockY() - origin.getY(); + int z = position.getBlockZ() - origin.getZ(); return getParent().getFullBlock(x, y, z); } return BlockTypes.AIR.getDefaultState().toBaseBlock(); @@ -320,8 +319,11 @@ public class BlockArrayClipboard implements Clipboard { public static class ClipboardEntity implements Entity { private final BaseEntity entity; private final Clipboard clipboard; - private final double x, y, z; - private final float yaw, pitch; + private final double x; + private final double y; + private final double z; + private final float yaw; + private final float pitch; public ClipboardEntity(Location loc, BaseEntity entity) { this((Clipboard) loc.getExtent(), loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch(), entity); 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 5113003b1..796cf30af 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 @@ -129,7 +129,7 @@ public interface Clipboard extends Extent, Iterable, Closeable { } /** - * Remove entity from clipboard + * Remove entity from clipboard. */ void removeEntity(Entity entity); @@ -184,7 +184,7 @@ public interface Clipboard extends Extent, Iterable, Closeable { } /** - * Forwards to paste(world, to, true, true, null) + * Forwards to {@link #paste(World, BlockVector3, boolean, boolean, Transform)}. */ default EditSession paste(World world, BlockVector3 to) { return paste(world, to, true, true, null); @@ -204,7 +204,7 @@ public interface Clipboard extends Extent, Iterable, Closeable { } /** - * Save this schematic to a stream + * Save this schematic to a stream. */ default void save(OutputStream stream, ClipboardFormat format) throws IOException { checkNotNull(stream); @@ -220,7 +220,7 @@ public interface Clipboard extends Extent, Iterable, Closeable { } /** - * Paste this schematic in a world + * Paste this schematic in a world. */ default EditSession paste(World world, BlockVector3 to, boolean allowUndo, boolean pasteAir, boolean copyEntities, @Nullable Transform transform) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/BuiltInClipboardFormat.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/BuiltInClipboardFormat.java index 9cce51ec8..d01db5dbb 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/BuiltInClipboardFormat.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/BuiltInClipboardFormat.java @@ -34,6 +34,7 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.util.Locale; import java.util.Set; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; @@ -72,7 +73,7 @@ public enum BuiltInClipboardFormat implements ClipboardFormat { @Override public boolean isFormat(File file) { - String name = file.getName().toLowerCase(); + String name = file.getName().toLowerCase(Locale.ROOT); return name.endsWith(".schematic") || name.endsWith(".mcedit") || name.endsWith(".mce"); } }, @@ -108,7 +109,7 @@ public enum BuiltInClipboardFormat implements ClipboardFormat { @Override public boolean isFormat(File file) { - String name = file.getName().toLowerCase(); + String name = file.getName().toLowerCase(Locale.ROOT); return name.endsWith(".schem") || name.endsWith(".sponge"); } @@ -141,13 +142,13 @@ public enum BuiltInClipboardFormat implements ClipboardFormat { @Override public boolean isFormat(File file) { - String name = file.getName().toLowerCase(); + String name = file.getName().toLowerCase(Locale.ROOT); return name.endsWith(".nbt"); } }, /** - * Isometric PNG writer + * Isometric PNG writer. */ PNG("png", "image") { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormat.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormat.java index 53bfb5e9d..a09ac238e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormat.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormat.java @@ -101,7 +101,7 @@ public interface ClipboardFormat { /** * Sets the actor's clipboard. - * @param actor + * @param actor the actor * @param uri the URI of the schematic to hold * @param inputStream the input stream * @throws IOException thrown on I/O error diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormats.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormats.java index aebe1e2ba..28c531f9d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormats.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/ClipboardFormats.java @@ -126,7 +126,7 @@ public class ClipboardFormats { } /** - * Detect the format using the given extension + * Detect the format using the given extension. * * @param extension the extension * @return the format, otherwise null if one cannot be detected @@ -195,8 +195,8 @@ public class ClipboardFormats { return null; } File working = worldEdit.getWorkingDirectoryFile(config.saveDir); - File dir = Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS ? - new File(working, player.getUniqueId().toString()) : working; + File dir = Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS + ? new File(working, player.getUniqueId().toString()) : working; File f; if (input.startsWith("#")) { String[] extensions; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/FastSchematicReader.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/FastSchematicReader.java index bfd2c8301..6433ce318 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/FastSchematicReader.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/FastSchematicReader.java @@ -80,9 +80,14 @@ public class FastSchematicReader extends NBTSchematicReader { private List> tiles; private List> entities; - private int width, height, length; - private int offsetX, offsetY, offsetZ; - private char[] palette, biomePalette; + private int width; + private int height; + private int length; + private int offsetX; + private int offsetY; + private int offsetZ; + private char[] palette; + private char[] biomePalette; private BlockVector3 min = BlockVector3.ZERO; @@ -97,22 +102,30 @@ public class FastSchematicReader extends NBTSchematicReader { } private String fix(String palettePart) { - if (fixer == null || dataVersion == -1) return palettePart; + if (fixer == null || dataVersion == -1) { + return palettePart; + } return fixer.fixUp(DataFixer.FixTypes.BLOCK_STATE, palettePart, dataVersion); } private CompoundTag fixBlockEntity(CompoundTag tag) { - if (fixer == null || dataVersion == -1) return tag; + if (fixer == null || dataVersion == -1) { + return tag; + } return fixer.fixUp(DataFixer.FixTypes.BLOCK_ENTITY, tag, dataVersion); } private CompoundTag fixEntity(CompoundTag tag) { - if (fixer == null || dataVersion == -1) return tag; + if (fixer == null || dataVersion == -1) { + return tag; + } return fixer.fixUp(DataFixer.FixTypes.ENTITY, tag, dataVersion); } private String fixBiome(String biomePalettePart) { - if(fixer == null || dataVersion == -1) return biomePalettePart; + if (fixer == null || dataVersion == -1) { + return biomePalettePart; + } return fixer.fixUp(DataFixer.FixTypes.BIOME, biomePalettePart, dataVersion); } @@ -208,8 +221,12 @@ public class FastSchematicReader extends NBTSchematicReader { throw new IOException("This schematic version is currently not supported"); } - if (blocks != null) blocks.close(); - if (biomes != null) biomes.close(); + if (blocks != null) { + blocks.close(); + } + if (biomes != null) { + biomes.close(); + } blocks = null; biomes = null; @@ -285,7 +302,9 @@ public class FastSchematicReader extends NBTSchematicReader { CompoundTag tile = FaweCache.IMP.asTag(tileRaw); int[] pos = tile.getIntArray("Pos"); - int x,y,z; + int x; + int y; + int z; if (pos.length != 3) { if (!tile.containsKey("x") || !tile.containsKey("y") || !tile.containsKey("z")) { return null; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/MCEditSchematicReader.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/MCEditSchematicReader.java index e35aac429..cc56d5bb7 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/MCEditSchematicReader.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/MCEditSchematicReader.java @@ -190,7 +190,9 @@ public class MCEditSchematicReader extends NBTSchematicReader { Map blockStates = new HashMap<>(); for (Tag tag : tileEntities) { - if (!(tag instanceof CompoundTag)) continue; + if (!(tag instanceof CompoundTag)) { + continue; + } CompoundTag t = (CompoundTag) tag; Map values = new HashMap<>(t.getValue()); String id = t.getString("id"); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SchematicReader.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SchematicReader.java index 9ebc7edec..44ac3c8bf 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SchematicReader.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SchematicReader.java @@ -95,7 +95,7 @@ public class SchematicReader implements ClipboardReader { private NBTInputStream inputStream; private InputStream rootStream; -// private final DataFixer fixer; TODO + // private final DataFixer fixer; TODO private FastByteArrayOutputStream idOut = new FastByteArrayOutputStream(); private FastByteArrayOutputStream dataOut = new FastByteArrayOutputStream(); @@ -110,9 +110,15 @@ public class SchematicReader implements ClipboardReader { private List> tiles; private List> entities; - private int width, height, length; - private int offsetX, offsetY, offsetZ; - private int originX, originY, originZ; + private int width; + private int height; + private int length; + private int offsetX; + private int offsetY; + private int offsetZ; + private int originX; + private int originY; + private int originZ; /** * Create a new instance. @@ -249,10 +255,18 @@ public class SchematicReader implements ClipboardReader { StreamDelegate root = createDelegate(); inputStream.readNamedTagLazy(root); - if (ids != null) ids.close(); - if (datas != null) datas.close(); - if (adds != null) adds.close(); - if (biomes != null) biomes.close(); + if (ids != null) { + ids.close(); + } + if (datas != null) { + datas.close(); + } + if (adds != null) { + adds.close(); + } + if (biomes != null) { + biomes.close(); + } ids = null; datas = null; adds = null; @@ -265,7 +279,7 @@ public class SchematicReader implements ClipboardReader { } Clipboard clipboard = createOutput.apply(dimensions); - try (InputStream dataIn = new LZ4BlockInputStream(new FastByteArraysInputStream(dataOut.toByteArrays()));InputStream idIn = new LZ4BlockInputStream(new FastByteArraysInputStream(idOut.toByteArrays()))) { + try (InputStream dataIn = new LZ4BlockInputStream(new FastByteArraysInputStream(dataOut.toByteArrays())); InputStream idIn = new LZ4BlockInputStream(new FastByteArraysInputStream(idOut.toByteArrays()))) { if (addOut != null) { try (FaweInputStream addIn = new FaweInputStream(new LZ4BlockInputStream(new FastByteArraysInputStream(addOut.toByteArrays())))) { if (clipboard instanceof LinearClipboard) { @@ -368,7 +382,9 @@ public class SchematicReader implements ClipboardReader { private void fixStates(Clipboard fc) { for (BlockVector3 pos : fc) { BlockState block = pos.getBlock(fc); - if (block.getMaterial().isAir()) continue; + if (block.getMaterial().isAir()) { + continue; + } int x = pos.getX(); int y = pos.getY(); @@ -425,13 +441,23 @@ public class SchematicReader implements ClipboardReader { } } else { int group = group(type); - if (group == -1) return; + if (group == -1) { + return; + } BlockState set = block; - if (set.getState(PropertyKey.NORTH) == Boolean.FALSE && merge(fc, group, x, y, z - 1)) set = set.with(PropertyKey.NORTH, true); - if (set.getState(PropertyKey.EAST) == Boolean.FALSE && merge(fc, group, x + 1, y, z)) set = set.with(PropertyKey.EAST, true); - if (set.getState(PropertyKey.SOUTH) == Boolean.FALSE && merge(fc, group, x, y, z + 1)) set = set.with(PropertyKey.SOUTH, true); - if (set.getState(PropertyKey.WEST) == Boolean.FALSE && merge(fc, group, x - 1, y, z)) set = set.with(PropertyKey.WEST, true); + if (set.getState(PropertyKey.NORTH) == Boolean.FALSE && merge(fc, group, x, y, z - 1)) { + set = set.with(PropertyKey.NORTH, true); + } + if (set.getState(PropertyKey.EAST) == Boolean.FALSE && merge(fc, group, x + 1, y, z)) { + set = set.with(PropertyKey.EAST, true); + } + if (set.getState(PropertyKey.SOUTH) == Boolean.FALSE && merge(fc, group, x, y, z + 1)) { + set = set.with(PropertyKey.SOUTH, true); + } + if (set.getState(PropertyKey.WEST) == Boolean.FALSE && merge(fc, group, x - 1, y, z)) { + set = set.with(PropertyKey.WEST, true); + } if (group == 2) { int ns = (set.getState(PropertyKey.NORTH) ? 1 : 0) + ((Boolean) set.getState(PropertyKey.SOUTH) ? 1 : 0); @@ -441,7 +467,9 @@ public class SchematicReader implements ClipboardReader { } } - if (set != block) pos.setBlock(fc, set); + if (set != block) { + pos.setBlock(fc, set); + } } } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/EntityNBTCompatibilityHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/EntityNBTCompatibilityHandler.java index b81bd1039..12c26f0e5 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/EntityNBTCompatibilityHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/EntityNBTCompatibilityHandler.java @@ -24,5 +24,6 @@ import com.sk89q.worldedit.world.entity.EntityType; public interface EntityNBTCompatibilityHandler { boolean isAffectedEntity(EntityType type, CompoundTag entityTag); + CompoundTag updateNBT(EntityType type, CompoundTag entityTag); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/inventory/BlockBag.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/inventory/BlockBag.java index 5d5bc2c77..5ca8aaabe 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/inventory/BlockBag.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/inventory/BlockBag.java @@ -35,8 +35,12 @@ public abstract class BlockBag { */ public void storeDroppedBlock(BlockState blockState) throws BlockBagException { BlockState dropped = blockState; // TODO BlockType.getBlockBagItem(id, data); - if (dropped == null) return; - if (dropped.getBlockType().getMaterial().isAir()) return; + if (dropped == null) { + return; + } + if (dropped.getBlockType().getMaterial().isAir()) { + return; + } storeBlock(dropped); } @@ -55,8 +59,10 @@ public abstract class BlockBag { } fetchBlock(blockState); } catch (OutOfBlocksException e) { - BlockState placed = blockState;// TODO BlockType.getBlockBagItem(id, data); - if (placed == null || placed.getBlockType().getMaterial().isAir()) throw e; // TODO: check + BlockState placed = blockState; // TODO BlockType.getBlockBagItem(id, data); + if (placed == null || placed.getBlockType().getMaterial().isAir()) { + throw e; // TODO: check + } fetchBlock(placed); } 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 ecaf66f2d..130744056 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 @@ -64,7 +64,8 @@ public class BlockBagExtent extends AbstractDelegateExtent { * * @return a block bag, which may be null if none is used */ - public @Nullable BlockBag getBlockBag() { + @Nullable + public BlockBag getBlockBag() { return blockBag; } @@ -76,6 +77,7 @@ public class BlockBagExtent extends AbstractDelegateExtent { public void setBlockBag(@Nullable BlockBag blockBag) { this.blockBag = blockBag; } + /** * Gets the list of missing blocks and clears the list for the next * operation. @@ -122,6 +124,7 @@ public class BlockBagExtent extends AbstractDelegateExtent { } } } + return super.setBlock(x, y, z, block); } } 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 7e4261c96..30e3b0c46 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 @@ -291,7 +291,9 @@ public class BlockTransformExtent extends ResettableExtent { } } } - if (newIndex != null) return newIndex; + if (newIndex != null) { + return newIndex; + } } return newIndex; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionMaskTestFunction.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionMaskTestFunction.java index 462c1eb35..d4f13aeb7 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionMaskTestFunction.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionMaskTestFunction.java @@ -32,7 +32,8 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class RegionMaskTestFunction implements RegionFunction { - private final RegionFunction pass,fail; + private final RegionFunction pass; + private final RegionFunction fail; private Mask mask; /** diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/CavesGen.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/CavesGen.java index a5d23c1b0..9407f6de3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/CavesGen.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/CavesGen.java @@ -80,9 +80,9 @@ public class CavesGen extends GenBase { y += f4; z += MathMan.sinInexact(paramdouble2) * f3; - if (k != 0) + if (k != 0) { paramdouble3 *= 0.92F; - else { + } else { paramdouble3 *= 0.7F; } paramdouble3 += f2 * 0.1F; @@ -117,8 +117,9 @@ public class CavesGen extends GenBase { //Boundaries check. if (x < real_x - 16.0D - d3 * 2.0D || z < real_z - 16.0D - d3 * 2.0D - || x > real_x + 16.0D + d3 * 2.0D || z > real_z + 16.0D + d3 * 2.0D) + || x > real_x + 16.0D + d3 * 2.0D || z > real_z + 16.0D + d3 * 2.0D) { continue; + } int m = (int) (x - d3) - bx - 1; @@ -130,20 +131,25 @@ public class CavesGen extends GenBase { int i3 = (int) (z - d3) - bz - 1; int i4 = (int) (z + d3) - bz + 1; - if (m < 0) + if (m < 0) { m = 0; - if (n > 16) + } + if (n > 16) { n = 16; + } - if (i1 < 1) + if (i1 < 1) { i1 = 1; + } if (i2 > 256 - 8) { i2 = 256 - 8; } - if (i3 < 0) + if (i3 < 0) { i3 = 0; - if (i4 > 16) + } + if (i4 > 16) { i4 = 16; + } // Search for water boolean waterFound = false; @@ -156,8 +162,9 @@ public class CavesGen extends GenBase { waterFound = true; } if (local_y != i1 - 1 && local_x != m && local_x != n - 1 && local_z != i3 - && local_z != i4 - 1) + && local_z != i4 - 1) { local_y = i1; + } } } } @@ -206,8 +213,9 @@ public class CavesGen extends GenBase { } } } - if (isLargeCave) + if (isLargeCave) { break; + } } } @@ -229,19 +237,21 @@ public class CavesGen extends GenBase { public void generateChunk(int chunkX, int chunkZ, BlockVector2 originChunk, Extent chunk) throws WorldEditException { int i = ThreadLocalRandom.current().nextInt(ThreadLocalRandom.current() .nextInt(ThreadLocalRandom.current().nextInt(this.caveFrequency) + 1) + 1); - if (this.evenCaveDistribution) + if (this.evenCaveDistribution) { i = this.caveFrequency; - if (ThreadLocalRandom.current().nextInt(100) >= this.caveRarity) + } + if (ThreadLocalRandom.current().nextInt(100) >= this.caveRarity) { i = 0; + } for (int j = 0; j < i; j++) { double x = (chunkX << 4) + ThreadLocalRandom.current().nextInt(16); double y; - if (this.evenCaveDistribution) + if (this.evenCaveDistribution) { y = ThreadLocalRandom.current().nextInt(this.caveMinAltitude, this.caveMaxAltitude); - else { + } else { y = ThreadLocalRandom.current() .nextInt(ThreadLocalRandom.current() .nextInt(this.caveMaxAltitude - this.caveMinAltitude + 1) + 1) + this.caveMinAltitude; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/GardenPatchGenerator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/GardenPatchGenerator.java index 65ada88cb..428a7a196 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/GardenPatchGenerator.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/GardenPatchGenerator.java @@ -84,8 +84,12 @@ public class GardenPatchGenerator implements RegionFunction { * @param pos the vine position */ private void placeVine(BlockVector3 basePos, BlockVector3 pos) throws MaxChangedBlocksException { - if (pos.distance(basePos) > 4) return; - if (!editSession.getBlock(pos).getBlockType().getMaterial().isAir()) return; + if (pos.distance(basePos) > 4) { + return; + } + if (!editSession.getBlock(pos).getBlockType().getMaterial().isAir()) { + return; + } for (int i = -1; i > -3; --i) { BlockVector3 testPos = pos.add(0, i, 0); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/GenBase.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/GenBase.java index e5bfde9df..3f723022a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/GenBase.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/GenBase.java @@ -10,7 +10,8 @@ public abstract class GenBase { private final int checkAreaSize; private final long seed; - private final long worldSeed1, worldSeed2; + private final long worldSeed1; + private final long worldSeed2; public GenBase(int area) { this.checkAreaSize = area; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/OreGen.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/OreGen.java index f544de178..7e35d0cfc 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/OreGen.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/OreGen.java @@ -102,8 +102,9 @@ public class OreGen implements Resource { double dz = (zz + 0.5D - d9) * id11o2; double dxyz2 = dxy2 + dz * dz; if ((dxyz2 < 1)) { - if (mask.test(mutable)) + if (mask.test(mutable)) { pattern.apply(extent, mutable, mutable); + } } } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/SchemGen.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/SchemGen.java index b0596201a..630090c94 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/SchemGen.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/SchemGen.java @@ -34,7 +34,9 @@ public class SchemGen implements Resource { mutable.mutX(x); mutable.mutZ(z); int y = extent.getNearestSurfaceTerrainBlock(x, z, mutable.getBlockY(), 0, 255); - if (y == -1) return false; + if (y == -1) { + return false; + } mutable.mutY(y); if (!mask.test(mutable)) { return false; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/AbstractExtentMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/AbstractExtentMask.java index c5789eb1a..3ba201cca 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/AbstractExtentMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/AbstractExtentMask.java @@ -40,7 +40,6 @@ public abstract class AbstractExtentMask extends AbstractMask { setExtent(extent); } - /** * Get the extent. * @@ -60,6 +59,6 @@ public abstract class AbstractExtentMask extends AbstractMask { this.extent = extent; } - abstract public boolean test(Extent extent, BlockVector3 position); + public abstract boolean test(Extent extent, BlockVector3 position); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/AbstractMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/AbstractMask.java index 45478ff06..ee4ec6960 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/AbstractMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/AbstractMask.java @@ -35,4 +35,5 @@ public abstract class AbstractMask implements Mask { return null; } } + } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockMask.java index 28b597259..665415618 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockMask.java @@ -182,6 +182,7 @@ public class BlockMask extends ABlockMask { public Collection getBlocks() { return Collections.emptyList(); //TODO Not supported in FAWE yet } + @Override public boolean test(BlockState state) { return ordinals[state.getOrdinal()] || replacesAir() && state.getOrdinal() <= 3; @@ -321,7 +322,7 @@ public class BlockMask extends ABlockMask { for (int i = 0; i < cloned.length; i++) { cloned[i] = !cloned[i]; } - if(replacesAir()){ + if (replacesAir()) { cloned[BlockTypes.AIR.getDefaultState().getOrdinal()] = false; cloned[BlockTypes.CAVE_AIR.getDefaultState().getOrdinal()] = false; cloned[BlockTypes.VOID_AIR.getDefaultState().getOrdinal()] = false; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockMaskBuilder.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockMaskBuilder.java index f075f735c..c22f52a92 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockMaskBuilder.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockMaskBuilder.java @@ -39,7 +39,7 @@ public class BlockMaskBuilder { private static final Operator LESS_EQUAL = (a, b) -> a <= b; private static final Operator NOT = (a, b) -> a != b; - private final static long[] ALL = new long[0]; + private static final long[] ALL = new long[0]; private interface Operator { boolean test(int left, int right); @@ -47,7 +47,9 @@ public class BlockMaskBuilder { private boolean filterRegex(BlockType blockType, PropertyKey key, String regex) { Property property = blockType.getProperty(key); - if (property == null) return false; + if (property == null) { + return false; + } List values = property.getValues(); boolean result = false; for (int i = 0; i < values.size(); i++) { @@ -62,7 +64,9 @@ public class BlockMaskBuilder { private boolean filterOperator(BlockType blockType, PropertyKey key, Operator operator, CharSequence value) { Property property = blockType.getProperty(key); - if (property == null) return false; + if (property == null) { + return false; + } int index = property.getIndexFor(value); List values = property.getValues(); boolean result = false; @@ -98,7 +102,9 @@ public class BlockMaskBuilder { public BlockMaskBuilder addRegex(String input) throws InputParseException { if (input.charAt(input.length() - 1) == ']') { int propStart = StringMan.findMatchingBracket(input, input.length() - 1); - if (propStart == -1) return this; + if (propStart == -1) { + return this; + } MutableCharSequence charSequence = MutableCharSequence.getTemporal(); charSequence.setString(input); @@ -121,7 +127,9 @@ public class BlockMaskBuilder { if (blockTypeList.isEmpty()) { throw new InputParseException("No block found for " + input); } - if (blockTypeList.size() == 1) type = blockTypeList.get(0); + if (blockTypeList.size() == 1) { + type = blockTypeList.get(0); + } } // Empty string charSequence.setSubstring(0, 0); @@ -137,18 +145,23 @@ public class BlockMaskBuilder { case '{': case '(': int next = StringMan.findMatchingBracket(input, i); - if (next != -1) i = next; + if (next != -1) { + i = next; + } break; case ']': case ',': { charSequence.setSubstring(last, i); - if (key == null && PropertyKey.get(charSequence) == null) suggest(input, charSequence.toString(), type != null ? Collections.singleton(type) : blockTypeList); - if (operator == null) throw new SuggestInputParseException("No operator for " + input, "", () -> Arrays.asList("=", "~", "!", "<", ">", "<=", ">=")); + if (key == null && PropertyKey.get(charSequence) == null) { + suggest(input, charSequence.toString(), type != null ? Collections.singleton(type) : blockTypeList); + } + if (operator == null) { + throw new SuggestInputParseException("No operator for " + input, "", () -> Arrays.asList("=", "~", "!", "<", ">", "<=", ">=")); + } boolean filtered = false; if (type != null) { filtered = filterRegexOrOperator(type, key, operator, charSequence); - } - else { + } else { for (BlockType myType : blockTypeList) { filtered |= filterRegexOrOperator(myType, key, operator, charSequence); } @@ -164,8 +177,9 @@ public class BlockMaskBuilder { for (int j = 0; j < p.getValues().size(); j++) { if (has(t, p, j)) { String o = p.getValues().get(j).toString(); - if (o.startsWith(value)) + if (o.startsWith(value)) { values.add(o); + } } } }); @@ -185,7 +199,9 @@ public class BlockMaskBuilder { case '>': { charSequence.setSubstring(last, i); boolean extra = input.charAt(i + 1) == '='; - if (extra) i++; + if (extra) { + i++; + } switch (c) { case '~': operator = EQUAL_OR_NULL; @@ -205,8 +221,9 @@ public class BlockMaskBuilder { } if (charSequence.length() > 0 || key == null) { key = PropertyKey.get(charSequence); - if (key == null) + if (key == null) { suggest(input, charSequence.toString(), type != null ? Collections.singleton(type) : blockTypeList); + } } last = i + 1; break; @@ -232,7 +249,9 @@ public class BlockMaskBuilder { private boolean has(BlockType type, Property property, int index) { AbstractProperty prop = (AbstractProperty) property; long[] states = bitSets[type.getInternalId()]; - if (states == null) return false; + if (states == null) { + return false; + } int localI = index << prop.getBitOffset() >> BlockTypesCache.BIT_OFFSET; return (states == ALL || FastBitSet.get(states, localI)); } @@ -328,10 +347,11 @@ public class BlockMaskBuilder { set = FastBitSet.get(states, stateId); Arrays.fill(states, 0); } - if (set) + if (set) { FastBitSet.set(states, stateId); - else + } else { bitSets[i] = null; + } reset(true); } return this; @@ -350,7 +370,9 @@ public class BlockMaskBuilder { public BlockMaskBuilder filter(Predicate typePredicate, BiPredicate, T>> allowed) { for (int i = 0; i < bitSets.length; i++) { long[] states = bitSets[i]; - if (states == null) continue; + if (states == null) { + continue; + } BlockType type = BlockTypes.get(i); if (!typePredicate.test(type)) { bitSets[i] = null; @@ -398,22 +420,30 @@ public class BlockMaskBuilder { } public > BlockMaskBuilder addBlocks(Collection blocks) { - for (BlockStateHolder block : blocks) add(block); + for (BlockStateHolder block : blocks) { + add(block); + } return this; } public BlockMaskBuilder addTypes(Collection blocks) { - for (BlockType block : blocks) add(block); + for (BlockType block : blocks) { + add(block); + } return this; } public > BlockMaskBuilder addBlocks(T... blocks) { - for (BlockStateHolder block : blocks) add(block); + for (BlockStateHolder block : blocks) { + add(block); + } return this; } public BlockMaskBuilder addTypes(BlockType... blocks) { - for (BlockType block : blocks) add(block); + for (BlockType block : blocks) { + add(block); + } return this; } @@ -430,7 +460,9 @@ public class BlockMaskBuilder { public BlockMaskBuilder addAll(Predicate typePredicate, BiPredicate, ?>> propPredicate) { for (int i = 0; i < bitSets.length; i++) { long[] states = bitSets[i]; - if (states == ALL) continue; + if (states == ALL) { + continue; + } BlockType type = BlockTypes.get(i); if (!typePredicate.test(type)) { continue; @@ -457,7 +489,9 @@ public class BlockMaskBuilder { public BlockMaskBuilder add(BlockType type, Property property, int index) { AbstractProperty prop = (AbstractProperty) property; long[] states = bitSets[type.getInternalId()]; - if (states == ALL) return this; + if (states == ALL) { + return this; + } List values = property.getValues(); int localI = index << prop.getBitOffset() >> BlockTypesCache.BIT_OFFSET; @@ -474,7 +508,9 @@ public class BlockMaskBuilder { public BlockMaskBuilder filter(BlockType type, Property property, int index) { AbstractProperty prop = (AbstractProperty) property; long[] states = bitSets[type.getInternalId()]; - if (states == null) return this; + if (states == null) { + return this; + } List values = property.getValues(); int localI = index << prop.getBitOffset() >> BlockTypesCache.BIT_OFFSET; if (states == ALL || FastBitSet.get(states, localI)) { @@ -499,8 +535,11 @@ public class BlockMaskBuilder { } else { for (int i = 0; i < values.size(); i++) { int index = current.modifyIndex(state, i) >> BlockTypesCache.BIT_OFFSET; - if (set) FastBitSet.set(states, index); - else FastBitSet.clear(states, index); + if (set) { + FastBitSet.set(states, index); + } else { + FastBitSet.clear(states, index); + } } } } @@ -529,7 +568,9 @@ public class BlockMaskBuilder { if (!optimizedStates) { for (int i = 0; i < bitSets.length; i++) { long[] bitSet = bitSets[i]; - if (bitSet == null || bitSet == ALL) continue; + if (bitSet == null || bitSet == ALL) { + continue; + } BlockType type = BlockTypes.get(i); int maxStateId = type.getMaxStateId(); if (maxStateId == 0) { @@ -547,12 +588,18 @@ public class BlockMaskBuilder { List values = prop.getValues(); for (int j = 0; j < values.size(); j++) { int localI = j << prop.getBitOffset() >> BlockTypesCache.BIT_OFFSET; - if (FastBitSet.get(bitSet, localI)) set++; - else clear++; + if (FastBitSet.get(bitSet, localI)) { + set++; + } else { + clear++; + } } } - if (set == 0) bitSets[i] = null; - else if (clear == 0) bitSets[i] = ALL; + if (set == 0) { + bitSets[i] = null; + } else if (clear == 0) { + bitSets[i] = ALL; + } } reset(true); } @@ -564,7 +611,9 @@ public class BlockMaskBuilder { ordinals = new boolean[BlockTypesCache.states.length]; for (int i = 0; i < BlockTypesCache.values.length; i++) { long[] bitSet = bitSets[i]; - if (bitSet == null) continue; + if (bitSet == null) { + continue; + } BlockType type = BlockTypesCache.values[i]; if (bitSet == ALL) { for (BlockState state : type.getAllStates()) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockTypeMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockTypeMask.java index 219591c79..f11e54efa 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockTypeMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockTypeMask.java @@ -110,7 +110,9 @@ public class BlockTypeMask extends AbstractExtentMask { public Collection getBlocks() { Set blocks = new HashSet<>(); for (int i = 0; i < types.length; i++) { - if (types[i]) blocks.add(BlockTypes.get(i)); + if (types[i]) { + blocks.add(BlockTypes.get(i)); + } } return blocks; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskIntersection.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskIntersection.java index d4404176d..7ce86998f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskIntersection.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskIntersection.java @@ -112,7 +112,9 @@ public class MaskIntersection extends AbstractMask { // Optimize sub masks for (int i = 0; i < masksArray.length; i++) { Mask mask = masksArray[i]; - if (ignore.contains(mask)) continue; + if (ignore.contains(mask)) { + continue; + } Mask newMask = mask.tryOptimize(); if (newMask != null) { changed = true; @@ -135,7 +137,9 @@ public class MaskIntersection extends AbstractMask { changed = true; } } - if (formArray) formArray(); + if (formArray) { + formArray(); + } return changed; } @@ -146,9 +150,13 @@ public class MaskIntersection extends AbstractMask { Set> failedCombines = new HashSet<>(); // Combine the masks boolean changed = false; - while (combineMasks(pairingFunction(), failedCombines)) changed = true; + while (combineMasks(pairingFunction(), failedCombines)) { + changed = true; + } // Optimize / combine - do changed |= optimizeMasks(optimized); + do { + changed |= optimizeMasks(optimized); + } while (combineMasks(pairingFunction(), failedCombines) && --maxIteration > 0); if (maxIteration == 0) { @@ -159,8 +167,12 @@ public class MaskIntersection extends AbstractMask { } // Return result formArray(); - if (masks.isEmpty()) return Masks.alwaysTrue(); - if (masks.size() == 1) return masks.iterator().next(); + if (masks.isEmpty()) { + return Masks.alwaysTrue(); + } + if (masks.size() == 1) { + return masks.iterator().next(); + } return changed ? this : null; } @@ -171,9 +183,13 @@ public class MaskIntersection extends AbstractMask { outer: for (Mask mask : masks) { for (Mask other : masks) { - if (mask == other) continue; + if (mask == other) { + continue; + } AbstractMap.SimpleEntry pair = new AbstractMap.SimpleEntry<>(mask, other); - if (failedCombines.contains(pair)) continue; + if (failedCombines.contains(pair)) { + continue; + } Mask combined = pairing.apply(pair); if (combined != null) { result = new Mask[]{combined, mask, other}; @@ -183,7 +199,9 @@ public class MaskIntersection extends AbstractMask { } } } - if (result == null) break; + if (result == null) { + break; + } masks.remove(result[1]); masks.remove(result[2]); masks.add(result[0]); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/BackwardsExtentBlockCopy.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/BackwardsExtentBlockCopy.java index 881781271..7d6ba5697 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/BackwardsExtentBlockCopy.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/BackwardsExtentBlockCopy.java @@ -38,7 +38,7 @@ public class BackwardsExtentBlockCopy extends RegionVisitor implements Operation for (BlockVector3 pt : destRegion) { BlockVector3 copyFrom = transform(inverse, pt); if (region.contains(copyFrom)) { - if(function.apply(pt)) { + if (function.apply(pt)) { affected++; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/ChangeSetExecutor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/ChangeSetExecutor.java index d378a79eb..9ed32f4a7 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/ChangeSetExecutor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/ChangeSetExecutor.java @@ -47,10 +47,10 @@ public class ChangeSetExecutor implements Operation { public void perform(Change change, UndoContext context) { change.redo(context); } - } - ; + }; - public void perform(Change change, UndoContext context) {} + public void perform(Change change, UndoContext context) { + } } private final Iterator iterator; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/ForwardExtentCopy.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/ForwardExtentCopy.java index 912bcae43..0ac331042 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/ForwardExtentCopy.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/ForwardExtentCopy.java @@ -367,8 +367,11 @@ public class ForwardExtentCopy implements Operation { copy = new IntersectRegionFunction(filterFunction, copy); } if (sourceMask != Masks.alwaysTrue()) { - if (maskFunc != null) copy = new RegionMaskTestFunction(sourceMask, copy, maskFunc); - else copy = new RegionMaskingFilter(source, sourceMask, copy); + if (maskFunc != null) { + copy = new RegionMaskTestFunction(sourceMask, copy, maskFunc); + } else { + copy = new RegionMaskingFilter(source, sourceMask, copy); + } } if (copyingBiomes && (source.isWorld() || region instanceof FlatRegion)) { copy = CombinedRegionFunction.combine(copy, new BiomeCopy(source, finalDest)); 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 d37510caa..46e89e397 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 @@ -77,7 +77,9 @@ public class RandomPattern extends AbstractPattern { public void add(Pattern pattern, double chance) { checkNotNull(pattern); Double existingWeight = weights.get(pattern); - if (existingWeight != null) chance += existingWeight; + if (existingWeight != null) { + chance += existingWeight; + } weights.put(pattern, chance); collection = RandomCollection.of(weights, random); this.patterns.add(pattern); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/WaterloggedRemover.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/WaterloggedRemover.java index 1a3445eba..3af0bd293 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/WaterloggedRemover.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/WaterloggedRemover.java @@ -39,7 +39,9 @@ public class WaterloggedRemover extends AbstractExtentPattern { private synchronized BlockState[] getRemap() { BlockState[] remap = cache.get(); - if (remap != null) return remap; + if (remap != null) { + return remap; + } cache = new SoftReference<>(remap = new BlockState[BlockTypesCache.states.length]); // init 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 00e78a0cf..e73407b38 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 @@ -236,7 +236,9 @@ public abstract class BreadthFirstSearch implements Operation { BlockVectorSet tempQueue = new BlockVectorSet(); for (currentDepth = 0; !queue.isEmpty() && currentDepth <= maxDepth; currentDepth++) { for (BlockVector3 from : queue) { - if (function.apply(from)) affected++; + if (function.apply(from)) { + affected++; + } for (int i = 0, j = 0; i < dirs.length && j < maxBranch; i++) { BlockVector3 direction = dirs[i]; int y = from.getBlockY() + direction.getY(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/ScanChunk.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/ScanChunk.java index 92ebb7673..2c73101fa 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/ScanChunk.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/ScanChunk.java @@ -13,9 +13,9 @@ import java.util.concurrent.ConcurrentLinkedQueue; * A chunk based search algorithm */ public class ScanChunk { - private static final int MAX_QUEUE = 34816; public static final BlockVector3[] DEFAULT_DIRECTIONS = new BlockVector3[6]; public static final BlockVector3[] DIAGONAL_DIRECTIONS; + private static final int MAX_QUEUE = 34816; static { DEFAULT_DIRECTIONS[0] = BlockVector3.at(0, -1, 0); @@ -45,6 +45,7 @@ public class ScanChunk { private final BlockVector3[] directions; private final Long2ObjectOpenHashMap visits; private final Long2ObjectOpenHashMap queues; + private ConcurrentLinkedQueue queuePool = new ConcurrentLinkedQueue<>(); public ScanChunk(RegionFunction function) { this.function = function; @@ -63,10 +64,14 @@ public class ScanChunk { int Z = z >> 4; long pair = pairInt(X, Z); long[][] chunk = visits.get(pair); - if (chunk == null) return false; + if (chunk == null) { + return false; + } int layer = y >> 4; long[] section = chunk[layer]; - if (section == null) return false; + if (section == null) { + return false; + } return get(section, getLocalIndex(x & 15, y & 15, z & 15)); } @@ -134,23 +139,22 @@ public class ScanChunk { public void process() { LongArraySet set = new LongArraySet(); + /* while (!queues.isEmpty()) { -// ObjectIterator> iter = queues.long2ObjectEntrySet().fastIterator(); -// Long2ObjectMap.Entry entry = iter.next(); -// long index = entry.getLongKey(); -// int X = MathMan.unpairIntX(index); -// int Z = MathMan.unpairIntY(index); -// // check that adjacent chunks aren;t being processed -// -// char[] queue = entry.getValue(); -// long[][] visit = visits.get(index); -// if (visit == null) { -// visits.put(index, visit = new long[16][]); -// } - } - } + ObjectIterator> iter = queues.long2ObjectEntrySet().fastIterator(); + Long2ObjectMap.Entry entry = iter.next(); + long index = entry.getLongKey(); + int X = MathMan.unpairIntX(index); + int Z = MathMan.unpairIntY(index); + // check that adjacent chunks aren;t being processed - private ConcurrentLinkedQueue queuePool = new ConcurrentLinkedQueue<>(); + char[] queue = entry.getValue(); + long[][] visit = visits.get(index); + if (visit == null) { + visits.put(index, visit = new long[16][]); + } + */ + } private char[] newQueue() { char[] arr = queuePool.poll(); @@ -178,7 +182,7 @@ public class ScanChunk { apply(xx + x, yy + y, zz + z); - int x1 = x, x2 = x; + int x1 = x; // find start of scan-line int i1 = index; @@ -187,7 +191,9 @@ public class ScanChunk { // queue in west chunk break; } - if (get(visit, i1)) break; + if (get(visit, i1)) { + break; + } // visit set(visit, i1); @@ -199,12 +205,15 @@ public class ScanChunk { // find end of scan-line int i2 = index; + int x2 = x; while (true) { if (x2 > 15) { // queue in east chunk break; } - if (get(visit, i2)) break; + if (get(visit, i2)) { + break; + } set(visit, i2); i2++; x2++; @@ -220,9 +229,9 @@ public class ScanChunk { } - public void process4(int X, int Z, char[][] queues, long[][] visit) { - int xx = X << 4; - int zz = Z << 4; + public void process4(int chunkX, int chunkZ, char[][] queues, long[][] visit) { + int xx = chunkX << 4; + int zz = chunkZ << 4; // TODO fetch instead of create final BlockVector3[] dirs = directions; @@ -231,7 +240,9 @@ public class ScanChunk { boolean empty = true; for (int layer = 0; layer < 16; layer++) { char[] queue = queues[layer]; - if (queue == null) continue; + if (queue == null) { + continue; + } char index; while ((index = queue[0]) != queue[1]) { queue[0]++; @@ -246,73 +257,75 @@ public class ScanChunk { continue; } - if (empty) break; + if (empty) { + break; + } } // empty queues -// while (indexStart != indexEnd) { -// char index = queue[indexStart++]; -// byte dirs = 0xF; -// int x = index & 15; -// int z = (index >> 4) & 15; -// int y = index >> 8; -// -// int layer = y >> 4; -// long[] visitBits = visit[layer]; -// -// int x1 = x; -// int x2 = x; -// -// // find start of scan-line -// int i1 = index; -// while (true) { -// if (x1 < 0) { -// // queue in adjacent chunk -// break; -// } -// if (get(visitBits, i1--)) break; -// x1--; -// } -// i1++; -// x1++; -// -// // find end of scan-line -// int i2 = index; -// while (true) { -// if (x2 > 15) { -// // queue in adjacent chunk -// break; -// } -// if (get(visitBits, i2++)) break; -// x2++; -// } -// i2--; -// x2--; -// -// boolean scanUp = false; -// boolean scanDown = false; -// boolean scanLeft = false; -// boolean scanRight = false; -// -// for (int i = i1; i <= i2; i++) { -// if (!scanDown && y > 0 && ) -// } -// -// for (int i=x1; i<=x2; i++) { // find scan-lines above this one -// if (!inScanLine && y>0 && ip.getPixel(i,y-1)==color) -// {push(i, y-1); inScanLine = true;} -// else if (inScanLine && y>0 && ip.getPixel(i,y-1)!=color) -// inScanLine = false; -// } -// -// inScanLine = false; -// for (int i=x1; i<=x2; i++) { // find scan-lines below this one -// if (!inScanLine && y> 4) & 15; + int y = index >> 8; + + int layer = y >> 4; + long[] visitBits = visit[layer]; + + int x1 = x; + int x2 = x; + + // find start of scan-line + int i1 = index; + while (true) { + if (x1 < 0) { + // queue in adjacent chunk + break; + } + if (get(visitBits, i1--)) break; + x1--; + } + i1++; + x1++; + + // find end of scan-line + int i2 = index; + while (true) { + if (x2 > 15) { + // queue in adjacent chunk + break; + } + if (get(visitBits, i2++)) break; + x2++; + } + i2--; + x2--; + + boolean scanUp = false; + boolean scanDown = false; + boolean scanLeft = false; + boolean scanRight = false; + + for (int i = i1; i <= i2; i++) { + if (!scanDown && y > 0 && ) + } + + for (int i=x1; i<=x2; i++) { // find scan-lines above this one + if (!inScanLine && y>0 && ip.getPixel(i,y-1)==color) + {push(i, y-1); inScanLine = true;} + else if (inScanLine && y>0 && ip.getPixel(i,y-1)!=color) + inScanLine = false; + } + + inScanLine = false; + for (int i=x1; i<=x2; i++) { // find scan-lines below this one + if (!inScanLine && y chunkSorter = Comparator.comparing( - pos -> (pos.getBlockX() & 31) + (pos.getBlockZ() & 31) * 32); + pos -> (pos.getBlockX() & 31) + (pos.getBlockZ() & 31) * 32 + ); - private static Gson chunkDeleterGson = new GsonBuilder() + private static final Gson chunkDeleterGson = new GsonBuilder() .registerTypeAdapter(BlockVector2.class, new BlockVector2Adapter()) .setPrettyPrinting() .create(); @@ -95,13 +96,13 @@ public final class ChunkDeleter { } catch (IOException ignored) { } if (!deletedFile) { - logger.warn("Chunk deletion file could not be cleaned up. This may have unintended consequences" + - " on next startup, or if /delchunks is used again."); + logger.warn("Chunk deletion file could not be cleaned up. This may have unintended consequences" + + " on next startup, or if /delchunks is used again."); } } } else { - logger.error("Error occurred while deleting chunks. " + - "If world errors occur, stop the server and restore the *.bak backup files."); + logger.error("Error occurred while deleting chunks. " + + "If world errors occur, stop the server and restore the *.bak backup files."); } } @@ -118,7 +119,7 @@ public final class ChunkDeleter { } private final ChunkDeletionInfo chunkDeletionInfo; - private Set backedUpRegions = new HashSet<>(); + private final Set backedUpRegions = new HashSet<>(); private boolean shouldPreload; private int debugRate = 100; private int totalChunksDeleted = 0; @@ -139,7 +140,9 @@ public final class ChunkDeleter { return regionToChunkList.entrySet().stream().allMatch(entry -> { Path regionPath = entry.getKey(); - if (!Files.exists(regionPath)) return true; + if (!Files.exists(regionPath)) { + return true; + } if (chunkBatch.backup && !backedUpRegions.contains(regionPath)) { try { backupRegion(regionPath); @@ -156,10 +159,10 @@ public final class ChunkDeleter { Path worldPath = Paths.get(chunkBatch.worldPath); if (chunkBatch.chunks != null) { return chunkBatch.chunks.stream() - .collect(Collectors.groupingBy(RegionFilePos::new)) - .entrySet().stream().collect(Collectors.toMap( - e -> worldPath.resolve("region").resolve(e.getKey().getFileName()), - e -> e.getValue().stream().sorted(chunkSorter))); + .collect(Collectors.groupingBy(RegionFilePos::new)) + .entrySet().stream().collect(Collectors.toMap( + e -> worldPath.resolve("region").resolve(e.getKey().getFileName()), + e -> e.getValue().stream().sorted(chunkSorter))); } else { final BlockVector2 minChunk = chunkBatch.minChunk; final BlockVector2 maxChunk = chunkBatch.maxChunk; @@ -169,7 +172,9 @@ public final class ChunkDeleter { for (int regX = minRegion.getX(); regX <= maxRegion.getX(); regX++) { for (int regZ = minRegion.getZ(); regZ <= maxRegion.getZ(); regZ++) { final Path regionPath = worldPath.resolve("region").resolve(new RegionFilePos(regX, regZ).getFileName()); - if (!Files.exists(regionPath)) continue; + if (!Files.exists(regionPath)) { + continue; + } int startX = regX << 5; int endX = (regX << 5) + 31; int startZ = regZ << 5; @@ -180,17 +185,17 @@ public final class ChunkDeleter { int maxX = Math.min(Math.max(startX, endX), maxChunk.getBlockX()); int maxZ = Math.min(Math.max(startZ, endZ), maxChunk.getBlockZ()); Stream stream = Stream.iterate(BlockVector2.at(minX, minZ), - bv2 -> { - int nextX = bv2.getBlockX(); - int nextZ = bv2.getBlockZ(); - if (++nextX > maxX) { - nextX = minX; - if (++nextZ > maxZ) { - return null; - } + bv2 -> { + int nextX = bv2.getBlockX(); + int nextZ = bv2.getBlockZ(); + if (++nextX > maxX) { + nextX = minX; + if (++nextZ > maxZ) { + return null; } - return BlockVector2.at(nextX, nextZ); - }); + } + return BlockVector2.at(nextX, nextZ); + }); groupedChunks.put(regionPath, stream); } } @@ -199,7 +204,9 @@ public final class ChunkDeleter { } private BiPredicate createPredicates(List deletionPredicates) { - if (deletionPredicates == null) return (r, p) -> true; + if (deletionPredicates == null) { + return (r, p) -> true; + } return deletionPredicates.stream() .map(this::createPredicate) .reduce(BiPredicate::and) @@ -249,7 +256,9 @@ public final class ChunkDeleter { try (RegionAccess region = new RegionAccess(regionFile, shouldPreload)) { for (Iterator iterator = chunks.iterator(); iterator.hasNext();) { BlockVector2 chunk = iterator.next(); - if (chunk == null) break; + if (chunk == null) { + break; + } if (deletionPredicate.test(region, chunk)) { region.deleteChunk(chunk); totalChunksDeleted++; @@ -322,12 +331,18 @@ public final class ChunkDeleter { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } RegionFilePos that = (RegionFilePos) o; - if (x != that.x) return false; + if (x != that.x) { + return false; + } return z == that.z; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/anvil/ChunkDeletionInfo.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/anvil/ChunkDeletionInfo.java index 9ce404597..adf001f80 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/anvil/ChunkDeletionInfo.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/anvil/ChunkDeletionInfo.java @@ -40,7 +40,9 @@ public class ChunkDeletionInfo { public BlockVector2 maxChunk; public int getChunkCount() { - if (chunks != null) return chunks.size(); + if (chunks != null) { + return chunks.size(); + } final BlockVector2 dist = maxChunk.subtract(minChunk).add(1, 1); return dist.getBlockX() * dist.getBlockZ(); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/block/BlockStateIdAccess.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/block/BlockStateIdAccess.java index 503772114..bcffdc98f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/block/BlockStateIdAccess.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/block/BlockStateIdAccess.java @@ -42,6 +42,7 @@ public final class BlockStateIdAccess { public interface BlockStateInternalId { int getInternalId(BlockState blockState); + void setInternalId(BlockState blockState, int internalId); } @@ -52,6 +53,7 @@ public final class BlockStateIdAccess { } /** + * An invalid internal ID, for verification purposes. * @return an internal ID which is never valid */ public static int invalidId() { @@ -67,7 +69,8 @@ public final class BlockStateIdAccess { //return blockStateInternalId.getInternalId(holder); } - public static @Nullable BlockState getBlockStateById(int id) { + @Nullable + public static BlockState getBlockStateById(int id) { return BlockState.getFromOrdinal(id); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandArgParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandArgParser.java index a7a9d2bc1..092844b12 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandArgParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandArgParser.java @@ -69,6 +69,9 @@ public class CommandArgParser { break; case QUOTE: handleQuote(nextPart); + break; + default: + break; } } if (currentArg.size() > 0) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/CUIRegion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/CUIRegion.java index 2f565beea..81360cd07 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/CUIRegion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/CUIRegion.java @@ -23,43 +23,43 @@ import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.extension.platform.Actor; public interface CUIRegion { - + /** * Sends CUI events describing the region for * versions of CUI equal to or greater than the * value supplied by getProtocolVersion(). - * + * */ void describeCUI(LocalSession session, Actor player); - + /** * Sends CUI events describing the region for - * versions of CUI smaller than the value + * versions of CUI smaller than the value * supplied by getProtocolVersion(). - * + * */ void describeLegacyCUI(LocalSession session, Actor player); - + /** * Returns the CUI version that is required to send * up-to-date data. If the CUI version is smaller than * this value, the legacy methods will be called. - * + * * @return the protocol version */ int getProtocolVersion(); - + /** * Returns the type ID to send to CUI in the selection event. * * @return the type ID */ String getTypeID(); - + /** * Returns the type ID to send to CUI in the selection * event if the CUI is in legacy mode. - * + * * @return the legacy type ID */ String getLegacyTypeID(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/ServerCUIHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/ServerCUIHandler.java index 8ff9a5f0c..591dcca39 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/ServerCUIHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/ServerCUIHandler.java @@ -63,8 +63,12 @@ public class ServerCUIHandler { LocalSession session = WorldEdit.getInstance().getSessionManager().get(player); RegionSelector regionSelector = session.getRegionSelector(player.getWorld()); - int posX, posY, posZ; - int width, height, length; + int posX; + int posY; + int posZ; + int width; + int height; + int length; if (regionSelector instanceof CuboidRegionSelector) { if (regionSelector.isDefined()) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/ExpressionEnvironment.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/ExpressionEnvironment.java index 0fc0ec484..061a520a9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/ExpressionEnvironment.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/ExpressionEnvironment.java @@ -25,10 +25,15 @@ package com.sk89q.worldedit.internal.expression; public interface ExpressionEnvironment { int getBlockType(double x, double y, double z); + int getBlockData(double x, double y, double z); + int getBlockTypeAbs(double x, double y, double z); + int getBlockDataAbs(double x, double y, double z); + int getBlockTypeRel(double x, double y, double z); + int getBlockDataRel(double x, double y, double z); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/ExpressionHelper.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/ExpressionHelper.java index 0e84947e6..916460ceb 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/ExpressionHelper.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/ExpressionHelper.java @@ -84,9 +84,8 @@ public class ExpressionHelper { ? (mh.type().parameterCount() - 1) + "+" : String.valueOf(mh.type().parameterCount())) .collect(Collectors.joining("/")); - throw evalException(ctx, "Incorrect number of arguments for function '" + fnName + "', " + - "expected " + possibleCounts + ", " + - "got " + ctx.args.size()); + throw evalException(ctx, "Incorrect number of arguments for function '" + fnName + "', " + + "expected " + possibleCounts + ", " + "got " + ctx.args.size()); } // Special argument handle names diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/Functions.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/Functions.java index a25b2c7cd..0b8f651e0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/Functions.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/Functions.java @@ -267,10 +267,10 @@ public final class Functions { for (int i = 0; i < count; ++i) { double currentX = getBufferItem(megabuf, index) - x; - double currentY = getBufferItem(megabuf, index+1) - y; - double currentZ = getBufferItem(megabuf, index+2) - z; + double currentY = getBufferItem(megabuf, index + 1) - y; + double currentZ = getBufferItem(megabuf, index + 2) - z; - double currentDistanceSquared = currentX*currentX + currentY*currentY + currentZ*currentZ; + double currentDistanceSquared = currentX * currentX + currentY * currentY + currentZ * currentZ; if (currentDistanceSquared < minDistanceSquared) { minDistanceSquared = currentDistanceSquared; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/invoke/CompilingVisitor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/invoke/CompilingVisitor.java index 5a892b767..7f9b2841e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/invoke/CompilingVisitor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/invoke/CompilingVisitor.java @@ -475,11 +475,15 @@ class CompilingVisitor extends ExpressionBaseVisitor { long aLong = Double.doubleToRawLongBits(a); // Make aLong lexicographically ordered as a twos-complement long - if (aLong < 0) aLong = 0x8000000000000000L - aLong; + if (aLong < 0) { + aLong = 0x8000000000000000L - aLong; + } long bLong = Double.doubleToRawLongBits(b); // Make bLong lexicographically ordered as a twos-complement long - if (bLong < 0) bLong = 0x8000000000000000L - bLong; + if (bLong < 0) { + bLong = 0x8000000000000000L - bLong; + } final long longDiff = Math.abs(aLong - bLong); return longDiff <= 450359963L; @@ -555,8 +559,8 @@ class CompilingVisitor extends ExpressionBaseVisitor { value -= arg; break; default: - throw ExpressionHelper.evalException(ctx, "Invalid text for assign expr: " + - ctx.assignmentOperator().getText()); + throw ExpressionHelper.evalException(ctx, "Invalid text for assign expr: " + + ctx.assignmentOperator().getText()); } } variable.setValue(value); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/AbstractFactory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/AbstractFactory.java index f6c51b51f..f7625de31 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/AbstractFactory.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/AbstractFactory.java @@ -23,6 +23,8 @@ import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.NoMatchException; import com.sk89q.worldedit.extension.input.ParserContext; +import com.sk89q.worldedit.util.formatting.text.TextComponent; +import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; import java.util.ArrayList; import java.util.Collections; @@ -79,7 +81,7 @@ public abstract class AbstractFactory { } } - throw new NoMatchException("No match for '" + input + "'"); + throw new NoMatchException(TranslatableComponent.of("worldedit.error.no-match", TextComponent.of(input))); } public List getSuggestions(String input) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector2.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector2.java index 2b6d739b8..390e4fd87 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector2.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector2.java @@ -79,7 +79,7 @@ public class BlockVector2 { protected int x; protected int z; - protected BlockVector2(){ + protected BlockVector2() { } /** diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableVector3.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableVector3.java index 5454eb88e..e32489230 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableVector3.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableVector3.java @@ -11,14 +11,6 @@ public class MutableVector3 extends Vector3 { public MutableVector3() { } - public static MutableVector3 get(int x, int y, int z) { - return FaweCache.IMP.MUTABLE_VECTOR3.get().setComponents(x, y, z); - } - - public static MutableVector3 get(double x, double y, double z) { - return FaweCache.IMP.MUTABLE_VECTOR3.get().setComponents(x, y, z); - } - public MutableVector3(double x, double y, double z) { this.x = x; this.y = y; @@ -33,6 +25,74 @@ public class MutableVector3 extends Vector3 { this(other.getX(), other.getY(), other.getZ()); } + public static MutableVector3 get(int x, int y, int z) { + return FaweCache.IMP.MUTABLE_VECTOR3.get().setComponents(x, y, z); + } + + public static MutableVector3 get(double x, double y, double z) { + return FaweCache.IMP.MUTABLE_VECTOR3.get().setComponents(x, y, z); + } + + @Override + public MutableVector3 setComponents(Vector3 other) { + this.x = other.getX(); + this.y = other.getY(); + this.z = other.getZ(); + return this; + } + + @Override + public MutableVector3 setComponents(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + return this; + } + + @Override + public MutableVector3 setComponents(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + return this; + } + + @Override + public MutableVector3 mutX(int x) { + this.x = x; + return this; + } + + @Override + public MutableVector3 mutX(double x) { + this.x = x; + return this; + } + + @Override + public MutableVector3 mutY(int y) { + this.y = y; + return this; + } + + @Override + public MutableVector3 mutY(double y) { + this.y = y; + return this; + } + + @Override + public MutableVector3 mutZ(int z) { + this.z = z; + return this; + } + + @Override + public MutableVector3 mutZ(double z) { + this.z = z; + return this; + } + @Override public double getX() { return x; @@ -48,64 +108,4 @@ public class MutableVector3 extends Vector3 { return z; } - @Override - public MutableVector3 setComponents(Vector3 other) { - this.x = other.getX(); - this.y = other.getY(); - this.z = other.getZ(); - return this; - } - - @Override - public MutableVector3 setComponents(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - return this; - } - - @Override - public MutableVector3 setComponents(int x, int y, int z) { - this.x = x; - this.y = y; - this.z = z; - return this; - } - - @Override - public MutableVector3 mutX(int x) { - this.x = x; - return this; - } - - @Override - public MutableVector3 mutZ(int z) { - this.z = z; - return this; - } - - @Override - public MutableVector3 mutX(double x) { - this.x = x; - return this; - } - - @Override - public MutableVector3 mutZ(double z) { - this.z = z; - return this; - } - - @Override - public MutableVector3 mutY(int y) { - this.y = y; - return this; - } - - @Override - public MutableVector3 mutY(double y) { - this.y = y; - return this; - } - } 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 c93fe5d58..f0b75a9d3 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 @@ -120,6 +120,8 @@ public class HeightMap { yTmp = maxY; invalid[index] = true; break; + default: + break; } data[index] = yTmp; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/CylinderRegion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/CylinderRegion.java index 317fda0b0..50f3d94af 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/CylinderRegion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/CylinderRegion.java @@ -274,7 +274,6 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * Contract the region. * * @param changes array/arguments with multiple related changes - * @throws RegionOperationException */ @Override public void contract(BlockVector3... changes) throws RegionOperationException { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/RegionSelector.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/RegionSelector.java index bd5138f86..30af99121 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/RegionSelector.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/RegionSelector.java @@ -199,10 +199,10 @@ public interface RegionSelector { } /** - * Get the vertices + * Get the vertices. * - * @return - * @throws IncompleteRegionException + * @return the list of vertices + * @throws IncompleteRegionException thrown if a region has not been fully defined */ default List getVertices() throws IncompleteRegionException { return Collections.singletonList(getPrimaryPosition()); 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 8b13c6901..d265a4ed8 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 @@ -56,7 +56,9 @@ public class DirectionalProperty extends AbstractProperty { @Override public int getIndexFor(CharSequence string) throws IllegalArgumentException { Direction dir = Direction.get(string); - if (dir == null) return -1; + if (dir == null) { + return -1; + } return getIndex(dir); } 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 21355a022..c5caa0dd3 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 @@ -51,7 +51,7 @@ public class IntegerProperty extends AbstractProperty { public int getIndex(Integer value) { try { return this.map[value]; - } catch (IndexOutOfBoundsException ignore) { + } catch (IndexOutOfBoundsException ignored) { return -1; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/PropertyGroup.java b/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/PropertyGroup.java index fc2fee400..0105909cb 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/PropertyGroup.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/PropertyGroup.java @@ -41,8 +41,12 @@ public class PropertyGroup { } public PropertyGroupBuilder add(PropertyKey key, Function getProcessor, Function setProcessor) { - if (getProcessor == null) getProcessor = VOID_FUNCTION; - if (setProcessor == null) setProcessor = VOID_FUNCTION; + if (getProcessor == null) { + getProcessor = VOID_FUNCTION; + } + if (setProcessor == null) { + setProcessor = VOID_FUNCTION; + } Object[] pf = new Object[]{key, getProcessor, setProcessor}; funcs.add(pf); return this; @@ -81,7 +85,9 @@ public class PropertyGroup { public > G get(BlockStateHolder state) { BlockType type = state.getBlockType(); PropertyFunction func = states[type.getInternalId()]; - if (func == null) return defaultValue; + if (func == null) { + return defaultValue; + } Object value = state.getState(func.key); return (G) func.getFunc.apply(value); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/PropertyKey.java b/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/PropertyKey.java index 0b0776215..5689e7a64 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/PropertyKey.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/PropertyKey.java @@ -7,7 +7,7 @@ import java.util.Locale; import java.util.Map; /** - * This class will be generated at runtime - these are just example values + * This class will be generated at runtime - these are just example values. */ public enum PropertyKey { // TODO FIXME Generate this at runtime @@ -70,22 +70,18 @@ public enum PropertyKey { SIGNAL_FIRE, HANGING, HAS_BOOK, - BOTTOM, - - - - ; + BOTTOM; private final String id; PropertyKey() { - this.id = name().toLowerCase(); + this.id = name().toLowerCase(Locale.ROOT); } private static final Map keys = new HashMap<>(); static { for (PropertyKey key : values()) { - keys.put(key.name().toLowerCase(), key); + keys.put(key.name().toLowerCase(Locale.ROOT), key); } } @@ -98,7 +94,7 @@ public enum PropertyKey { } /** - * Get or create the property key + * Get or create the property key. * @param id The name of the property (e.g., `waterlogged`) * @return PropertyKey enum */ @@ -113,7 +109,7 @@ public enum PropertyKey { throw new RuntimeException("Could not register property with an id of " + id , e); } } - keys.put(property.name().toLowerCase(), property); + keys.put(property.name().toLowerCase(Locale.ROOT), property); } return property; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/NashornCraftScriptEngine.java b/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/NashornCraftScriptEngine.java index 6fde6898d..0a45367ee 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/NashornCraftScriptEngine.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/NashornCraftScriptEngine.java @@ -47,7 +47,9 @@ public class NashornCraftScriptEngine implements CraftScriptEngine { ClassLoader cl = Fawe.get().getClass().getClassLoader(); Thread.currentThread().setContextClassLoader(cl); synchronized (NashornCraftScriptEngine.class) { - if (FACTORY == null) FACTORY = new NashornScriptEngineFactory(); + if (FACTORY == null) { + FACTORY = new NashornScriptEngineFactory(); + } } ScriptEngine engine = FACTORY.getScriptEngine("--language=es6"); SimpleBindings bindings = new SimpleBindings(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/session/ClipboardHolder.java b/worldedit-core/src/main/java/com/sk89q/worldedit/session/ClipboardHolder.java index 6a7d987d1..c74b594ef 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/session/ClipboardHolder.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/session/ClipboardHolder.java @@ -49,9 +49,11 @@ public class ClipboardHolder { /** * Get the clipboard. + * *

* If there is a transformation applied, the returned clipboard will * not contain its effect. + *

* * @deprecated FAWE supports multiple loaded schematics {@link #getClipboards()} * @return the clipboard diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/session/request/Request.java b/worldedit-core/src/main/java/com/sk89q/worldedit/session/request/Request.java index d6b47db91..a94e0ced8 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/session/request/Request.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/session/request/Request.java @@ -36,11 +36,16 @@ public final class Request { private static final CleanableThreadLocal threadLocal = new CleanableThreadLocal<>(Request::new); - private @Nullable World world; - private @Nullable Actor actor; - private @Nullable LocalSession session; - private @Nullable EditSession editSession; - private @Nullable Extent extent; + @Nullable + private World world; + @Nullable + private Actor actor; + @Nullable + private LocalSession session; + @Nullable + private EditSession editSession; + @Nullable + private Extent extent; private boolean valid; private Request() { @@ -55,7 +60,8 @@ public final class Request { * * @return the world, which may be null */ - public @Nullable World getWorld() { + @Nullable + public World getWorld() { return world; } @@ -72,10 +78,17 @@ public final class Request { this.extent = extent; } - public @Nullable Extent getExtent() { - if (extent != null) return extent; - if (editSession != null) return editSession; - if (world != null) return world; + @Nullable + public Extent getExtent() { + if (extent != null) { + return extent; + } + if (editSession != null) { + return editSession; + } + if (world != null) { + return world; + } return null; } @@ -93,7 +106,8 @@ public final class Request { * * @return the session, which may be null */ - public @Nullable LocalSession getSession() { + @Nullable + public LocalSession getSession() { return session; } @@ -111,7 +125,8 @@ public final class Request { * * @return the edit session, which may be null */ - public @Nullable EditSession getEditSession() { + @Nullable + public EditSession getEditSession() { return editSession; } 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 1a97e0409..35c259f31 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 @@ -25,6 +25,7 @@ import com.sk89q.worldedit.math.Vector3; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Optional; import java.util.OptionalInt; import javax.annotation.Nullable; @@ -73,7 +74,7 @@ public enum Direction { static { for (Direction dir : Direction.values()) { map.put(dir.name(), dir); - map.put(dir.name().toLowerCase(), dir); + map.put(dir.name().toLowerCase(Locale.ROOT), dir); } } @@ -273,9 +274,9 @@ public enum Direction { return Optional.of(SOUTHEAST); case 15: return Optional.of(SOUTH_SOUTHEAST); + default: + return Optional.empty(); } - - return Optional.empty(); } public OptionalInt toRotationIndex() { @@ -312,8 +313,9 @@ public enum Direction { return OptionalInt.of(14); case SOUTH_SOUTHEAST: return OptionalInt.of(15); + default: + return OptionalInt.empty(); } - return OptionalInt.empty(); } /** diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/Location.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/Location.java index 75ad0e090..4dce38b99 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/Location.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/Location.java @@ -307,17 +307,33 @@ public class Location extends Vector3Impl { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } Location location = (Location) o; - if (Double.doubleToLongBits(pitch) != Double.doubleToLongBits(location.pitch)) return false; - if (Double.doubleToLongBits(yaw) != Double.doubleToLongBits(location.yaw)) return false; - if (this.getX() != location.getX()) return false; - if (this.getZ() != location.getZ()) return false; - if (this.getY() != location.getY()) return false; - if (!extent.equals(location.extent)) return false; + if (Double.doubleToLongBits(pitch) != Double.doubleToLongBits(location.pitch)) { + return false; + } + if (Double.doubleToLongBits(yaw) != Double.doubleToLongBits(location.yaw)) { + return false; + } + if (this.getX() != location.getX()) { + return false; + } + if (this.getZ() != location.getZ()) { + return false; + } + if (this.getY() != location.getY()) { + return false; + } + if (!extent.equals(location.extent)) { + return false; + } return true; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/collection/BlockMap.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/collection/BlockMap.java index 6d4c8c418..beddc4624 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/collection/BlockMap.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/collection/BlockMap.java @@ -240,7 +240,7 @@ public class BlockMap extends AbstractMap { entrySet = es = new AbstractSet>() { @Override public Iterator> iterator() { - return new Iterator>() { + return new Iterator>() { private final ObjectIterator>> primaryIterator = Long2ObjectMaps.fastIterator(maps); @@ -346,8 +346,9 @@ public class BlockMap extends AbstractMap { } public boolean equals(Object o) { - if (!(o instanceof Map.Entry)) + if (!(o instanceof Map.Entry)) { return false; + } Entry e = (Entry) o; if (o instanceof BlockMap.LazyEntry) { @SuppressWarnings("unchecked") diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/collection/LocatedBlockList.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/collection/LocatedBlockList.java index 67beee295..d0a0c56bc 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/collection/LocatedBlockList.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/collection/LocatedBlockList.java @@ -65,7 +65,8 @@ public class LocatedBlockList implements Iterable { return blocks.containsKey(location); } - public @Nullable BaseBlock get(BlockVector3 location) { + @Nullable + public BaseBlock get(BlockVector3 location) { return blocks.get(location); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/EventHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/EventHandler.java index 7e66ecf57..c5bf4369c 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/EventHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/EventHandler.java @@ -97,9 +97,7 @@ public abstract class EventHandler implements Comparable { @Override public String toString() { - return "EventHandler{" + - "priority=" + priority + - '}'; + return "EventHandler{" + "priority=" + priority + '}'; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/MethodEventHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/MethodEventHandler.java index b6b8439fa..03f69fb5b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/MethodEventHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/eventbus/MethodEventHandler.java @@ -60,14 +60,21 @@ public class MethodEventHandler extends EventHandler { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } MethodEventHandler that = (MethodEventHandler) o; - if (!method.equals(that.method)) return false; - if (object != null ? !object.equals(that.object) : that.object != null) + if (!method.equals(that.method)) { return false; + } + if (object != null ? !object.equals(that.object) : that.object != null) { + return false; + } return true; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/CodeFormat.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/CodeFormat.java index a4bba721b..6f3640d3e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/CodeFormat.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/CodeFormat.java @@ -37,7 +37,7 @@ public class CodeFormat extends TextComponentProducer { * @param texts The text * @return The Component */ - public static TextComponent wrap(String ... texts) { + public static TextComponent wrap(String... texts) { CodeFormat code = new CodeFormat(); for (String text: texts) { code.append(text); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/ErrorFormat.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/ErrorFormat.java index 38e446a19..5b60afb3f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/ErrorFormat.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/ErrorFormat.java @@ -40,7 +40,7 @@ public class ErrorFormat extends TextComponentProducer { * @param texts The text * @return The Component */ - public static TextComponent wrap(String ... texts) { + public static TextComponent wrap(String... texts) { ErrorFormat error = new ErrorFormat(); for (String component : texts) { error.append(component); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/PaginationBox.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/PaginationBox.java index 44b4b7db6..9301a0493 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/PaginationBox.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/PaginationBox.java @@ -79,7 +79,7 @@ public abstract class PaginationBox extends MessageBox { if (pageCommand != null && !pageCommand.contains("%page%")) { if (pageCommand.contains("-p ")) { pageCommand = pageCommand.replaceAll("-p [0-9]+", "-p %page%"); - } else{ + } else { pageCommand = pageCommand + " -p %page%"; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/SubtleFormat.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/SubtleFormat.java index 65f1e5f5a..735b6cf40 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/SubtleFormat.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/SubtleFormat.java @@ -40,7 +40,7 @@ public class SubtleFormat extends TextComponentProducer { * @param texts The text * @return The Component */ - public static TextComponent wrap(String ... texts) { + public static TextComponent wrap(String... texts) { SubtleFormat subtle = new SubtleFormat(); for (String component : texts) { subtle.append(component); 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 c6754f388..0fdf93185 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 @@ -33,7 +33,7 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class LevenshteinDistance implements Function { - public final static Pattern STANDARD_CHARS = Pattern.compile("[ _\\-]"); + public static final Pattern STANDARD_CHARS = Pattern.compile("[ _\\-]"); private final String baseString; private final boolean caseSensitive; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/io/file/ArchiveNioSupports.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/io/file/ArchiveNioSupports.java index c1370dac0..39ac0158f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/io/file/ArchiveNioSupports.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/io/file/ArchiveNioSupports.java @@ -37,7 +37,7 @@ public class ArchiveNioSupports { ImmutableList.Builder builder = ImmutableList.builder(); try { builder.add(TrueVfsArchiveNioSupport.getInstance()); - } catch (NoClassDefFoundError ignore) { + } catch (NoClassDefFoundError ignored) { // No TrueVFS available. That's OK. } SUPPORTS = builder.add(ZipArchiveNioSupport.getInstance()) 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 4edf814b5..4a36e2a6b 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 @@ -36,10 +36,14 @@ import javax.annotation.Nullable; */ public class DynamicStreamHandler extends StreamHandler { - private @Nullable StreamHandler handler; - private @Nullable Formatter formatter; - private @Nullable Filter filter; - private @Nullable String encoding; + @Nullable + private StreamHandler handler; + @Nullable + private Formatter formatter; + @Nullable + private Filter filter; + @Nullable + private String encoding; private Level level = Level.ALL; /** @@ -47,7 +51,8 @@ public class DynamicStreamHandler extends StreamHandler { * * @return the delegate handler (Which may be null) */ - public @Nullable synchronized StreamHandler getHandler() { + @Nullable + public synchronized StreamHandler getHandler() { return handler; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/AbstractWorld.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/AbstractWorld.java index babefbc3e..7f76462c9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/AbstractWorld.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/AbstractWorld.java @@ -138,7 +138,8 @@ public abstract class AbstractWorld implements World { } @Override - public @Nullable Operation commit() { + @Nullable + public Operation commit() { return null; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/NullWorld.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/NullWorld.java index e4c89b2ab..1d2ff9e97 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/NullWorld.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/NullWorld.java @@ -160,7 +160,7 @@ public class NullWorld extends AbstractWorld { } @Override - public void refreshChunk(int X, int Z) { + public void refreshChunk(int chunkX, int chunkZ) { } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/RegenOptions.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/RegenOptions.java index 6b87165b6..3fcb79307 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/RegenOptions.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/RegenOptions.java @@ -20,14 +20,14 @@ package com.sk89q.worldedit.world; import com.google.auto.value.AutoValue; -import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.regions.Region; import java.util.OptionalLong; import javax.annotation.Nullable; /** - * Regeneration options for {@link World#regenerate(Region, EditSession, RegenOptions)}. + * Regeneration options for {@link World#regenerate(Region, Extent, RegenOptions)}. */ @AutoValue public abstract class RegenOptions { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BaseBlock.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BaseBlock.java index fe9f9f11e..36af08c10 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BaseBlock.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BaseBlock.java @@ -66,6 +66,7 @@ public class BaseBlock implements BlockStateHolder, TileEntityBlock { public BaseBlock(BlockType blockType) { this(blockType.getDefaultState()); } + /** * Construct a block with a state. * @@ -230,7 +231,9 @@ public class BaseBlock implements BlockStateHolder, TileEntityBlock { @Override public void applyTileEntity(OutputExtent output, int x, int y, int z) { CompoundTag nbt = getNbtData(); - if (nbt != null) output.setTile(x, y, z, nbt); + if (nbt != null) { + output.setTile(x, y, z, nbt); + } } @Override @@ -276,11 +279,8 @@ public class BaseBlock implements BlockStateHolder, TileEntityBlock { @Override public String toString() { -// if (getNbtData() != null) { // TODO Maybe make some JSON serialiser to make this not awful. -// return blockState.getAsString() + " {" + String.valueOf(getNbtData()) + "}"; -// } else { - return blockState.getAsString(); -// } + // TODO use a json serializer for the NBT data + return blockState.getAsString() + (hasNbtData() ? "{hasNbt}" : ""); } public BlockState toBlockState() { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockID.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockID.java index d72a3ab41..47d74fe97 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockID.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockID.java @@ -37,7 +37,7 @@ public class BlockID { public static final int BARRIER = 24; public static final int BEACON = 25; public static final int BEDROCK = 26; - public static final int BEE_NEST= 677; + public static final int BEE_NEST = 677; public static final int BEEHIVE = 678; // highest public static final int BEETROOTS = 27; public static final int BELL = 605; 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 234ced77f..6e020852f 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 @@ -71,9 +71,8 @@ public class BlockState implements BlockStateHolder, Pattern { } /** - * Returns a temporary BlockState for a given internal id - * @param combinedId - * @deprecated magic number + * Returns a temporary BlockState for a given internal id. + * @deprecated Magic Numbers * @return BlockState */ @@ -88,7 +87,7 @@ public class BlockState implements BlockStateHolder, Pattern { } /** - * Returns a temporary BlockState for a given type and string + * Returns a temporary BlockState for a given type and string. * @param state String e.g., minecraft:water[level=4] * @return BlockState */ @@ -97,8 +96,10 @@ public class BlockState implements BlockStateHolder, Pattern { } /** - * Returns a temporary BlockState for a given type and string - * - It's faster if a BlockType is provided compared to parsing the string + * Returns a temporary BlockState for a given type and string. + * + *

It's faster if a BlockType is provided compared to parsing the string.

+ * * @param type BlockType e.g., BlockTypes.STONE (or null) * @param state String e.g., minecraft:water[level=4] * @return BlockState @@ -108,8 +109,10 @@ public class BlockState implements BlockStateHolder, Pattern { } /** - * Returns a temporary BlockState for a given type and string - * - It's faster if a BlockType is provided compared to parsing the string + * Returns a temporary BlockState for a given type and string. + * + *

It's faster if a BlockType is provided compared to parsing the string.

+ * * @param type BlockType e.g., BlockTypes.STONE (or null) * @param state String e.g., minecraft:water[level=4] * @return BlockState @@ -143,7 +146,9 @@ public class BlockState implements BlockStateHolder, Pattern { List propList = type.getProperties(); - if (state.charAt(state.length() - 1) != ']') state = state + "]"; + if (state.charAt(state.length() - 1) != ']') { + state = state + "]"; + } MutableCharSequence charSequence = MutableCharSequence.getTemporal(); charSequence.setString(state); @@ -222,6 +227,7 @@ public class BlockState implements BlockStateHolder, Pattern { public BlockType getBlockType() { return this.blockType; } + @Override public boolean apply(Extent extent, BlockVector3 get, BlockVector3 set) throws WorldEditException { return set.setBlock(extent, this); @@ -242,8 +248,7 @@ public class BlockState implements BlockStateHolder, Pattern { } /** - * The internal id with no type information - * @return + * The internal id with no type information. */ @Deprecated @Override @@ -405,7 +410,7 @@ public class BlockState implements BlockStateHolder, Pattern { public boolean isAir() { try { return material.isAir(); - } catch (NullPointerException ignore) { + } catch (NullPointerException ignored) { return getMaterial().isAir(); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockStateHolder.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockStateHolder.java index 5c58b1936..97cd8ebde 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockStateHolder.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockStateHolder.java @@ -37,23 +37,20 @@ import javax.annotation.Nullable; public interface BlockStateHolder> extends TileEntityBlock, Pattern { /** - * Get the block type + * Get the block type. * * @return The type */ BlockType getBlockType(); /** - * Magic number (legacy uses) - * @param propertyId - * @return + * Magic number (legacy uses). */ @Deprecated B withPropertyId(int propertyId); /** - * Get combined id (legacy uses) - * @return + * Get combined id (legacy uses). */ @Deprecated int getInternalId(); @@ -67,14 +64,13 @@ public interface BlockStateHolder> extends TileEnt BlockMaterial getMaterial(); /** - * Get type id (legacy uses) - * @return + * Get type id (legacy uses). */ @Deprecated int getInternalBlockTypeId(); + /** - * Get the block data (legacy uses) - * @return + * Get the block data (legacy uses). */ @Deprecated int getInternalPropertiesId(); @@ -98,7 +94,7 @@ public interface BlockStateHolder> extends TileEnt B with(final PropertyKey property, final V value); /** - * Gets the value at the given state + * Gets the value for the given state. * * @param property The state * @return The value @@ -106,7 +102,7 @@ public interface BlockStateHolder> extends TileEnt V getState(Property property); /** - * Gets the value at the given state + * Gets the value for the given state. * * @param property The state * @return The value diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockType.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockType.java index 1dd60bfe9..8ccb2b136 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockType.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockType.java @@ -186,7 +186,7 @@ public class BlockType implements Keyed, Pattern { public Property getProperty(PropertyKey key) { try { return (Property) this.settings.propertiesMapArr[key.ordinal()]; - } catch (IndexOutOfBoundsException ignore) { + } catch (IndexOutOfBoundsException ignored) { return null; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypeSwitchBuilder.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypeSwitchBuilder.java index e31885305..11b1c3d4b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypeSwitchBuilder.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypeSwitchBuilder.java @@ -32,7 +32,9 @@ public class BlockTypeSwitchBuilder { public BlockTypeSwitch build() { for (int i = 0; i < runnables.length; i++) { - if (runnables[i] == null) runnables[i] = defaultTask; + if (runnables[i] == null) { + runnables[i] = defaultTask; + } } return new BlockTypeSwitch(runnables); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypeUtil.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypeUtil.java index 136d21dce..546623c54 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypeUtil.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypeUtil.java @@ -38,7 +38,8 @@ public class BlockTypeUtil { case BlockID.CREEPER_WALL_HEAD: case BlockID.DRAGON_WALL_HEAD: case BlockID.PLAYER_WALL_HEAD: - case BlockID.ZOMBIE_WALL_HEAD: return 0.25; + case BlockID.ZOMBIE_WALL_HEAD: + return 0.25; case BlockID.ACACIA_SLAB: case BlockID.BIRCH_SLAB: case BlockID.BRICK_SLAB: @@ -59,13 +60,16 @@ public class BlockTypeUtil { case BlockID.STONE_BRICK_SLAB: case BlockID.STONE_SLAB: { String state = (String) block.getState(PropertyKey.TYPE); - if (state == null) return 0; + if (state == null) { + return 0; + } switch (state) { - case "double": - case "bottom": - return 0; case "top": return 0.5; + case "double": + case "bottom": + default: + return 0; } } case BlockID.ACACIA_TRAPDOOR: @@ -87,9 +91,12 @@ public class BlockTypeUtil { case BlockID.DARK_OAK_FENCE_GATE: case BlockID.JUNGLE_FENCE_GATE: case BlockID.OAK_FENCE_GATE: - case BlockID.SPRUCE_FENCE_GATE: return block.getState(PropertyKey.OPEN) == Boolean.TRUE ? 1 : 0; + case BlockID.SPRUCE_FENCE_GATE: + return block.getState(PropertyKey.OPEN) == Boolean.TRUE ? 1 : 0; default: - if (type.getMaterial().isMovementBlocker()) return 0; + if (type.getMaterial().isMovementBlocker()) { + return 0; + } return 1; } } @@ -119,29 +126,39 @@ public class BlockTypeUtil { case BlockID.PURPLE_BED: case BlockID.RED_BED: case BlockID.WHITE_BED: - case BlockID.YELLOW_BED: return 0.5625; - case BlockID.BREWING_STAND: return 0.875; - case BlockID.CAKE: return (block.getState(PropertyKey.BITES) == (Integer) 6) ? 0 : 0.4375; - case BlockID.CAULDRON: return 0.3125; - case BlockID.COCOA: return 0.750; - case BlockID.ENCHANTING_TABLE: return 0.75; - case BlockID.END_PORTAL_FRAME: return block.getState(PropertyKey.EYE) == Boolean.TRUE ? 1 : 0.8125; + case BlockID.YELLOW_BED: + return 0.5625; + case BlockID.BREWING_STAND: + return 0.875; + case BlockID.CAKE: + return (block.getState(PropertyKey.BITES) == (Integer) 6) ? 0 : 0.4375; + case BlockID.CAULDRON: + return 0.3125; + case BlockID.COCOA: + return 0.750; + case BlockID.ENCHANTING_TABLE: + return 0.75; + case BlockID.END_PORTAL_FRAME: + return block.getState(PropertyKey.EYE) == Boolean.TRUE ? 1 : 0.8125; case BlockID.CREEPER_HEAD: case BlockID.DRAGON_HEAD: case BlockID.PISTON_HEAD: case BlockID.PLAYER_HEAD: - case BlockID.ZOMBIE_HEAD: return 0.5; + case BlockID.ZOMBIE_HEAD: + return 0.5; case BlockID.CREEPER_WALL_HEAD: case BlockID.DRAGON_WALL_HEAD: case BlockID.PLAYER_WALL_HEAD: - case BlockID.ZOMBIE_WALL_HEAD: return 0.75; + case BlockID.ZOMBIE_WALL_HEAD: + return 0.75; case BlockID.ACACIA_FENCE: case BlockID.BIRCH_FENCE: case BlockID.DARK_OAK_FENCE: case BlockID.JUNGLE_FENCE: case BlockID.NETHER_BRICK_FENCE: case BlockID.OAK_FENCE: - case BlockID.SPRUCE_FENCE: return 1.5; + case BlockID.SPRUCE_FENCE: + return 1.5; case BlockID.ACACIA_SLAB: case BlockID.BIRCH_SLAB: case BlockID.BRICK_SLAB: @@ -162,7 +179,9 @@ public class BlockTypeUtil { case BlockID.STONE_BRICK_SLAB: case BlockID.STONE_SLAB: { String state = (String) block.getState(PropertyKey.TYPE); - if (state == null) return 0.5; + if (state == null) { + return 0.5; + } switch (state) { case "bottom": return 0.5; @@ -171,15 +190,23 @@ public class BlockTypeUtil { return 1; } } - case BlockID.LILY_PAD: return 0.015625; - case BlockID.REPEATER: return 0.125; - case BlockID.SOUL_SAND: return 0.875; + case BlockID.LILY_PAD: + return 0.015625; + case BlockID.REPEATER: + return 0.125; + case BlockID.SOUL_SAND: + return 0.875; case BlockID.COBBLESTONE_WALL: - case BlockID.MOSSY_COBBLESTONE_WALL: return 1.5; - case BlockID.FLOWER_POT: return 0.375; - case BlockID.COMPARATOR: return 0.125; - case BlockID.DAYLIGHT_DETECTOR: return 0.375; - case BlockID.HOPPER: return 0.625; + case BlockID.MOSSY_COBBLESTONE_WALL: + return 1.5; + case BlockID.FLOWER_POT: + return 0.375; + case BlockID.COMPARATOR: + return 0.125; + case BlockID.DAYLIGHT_DETECTOR: + return 0.375; + case BlockID.HOPPER: + return 0.625; case BlockID.ACACIA_TRAPDOOR: case BlockID.BIRCH_TRAPDOOR: case BlockID.DARK_OAK_TRAPDOOR: @@ -199,12 +226,15 @@ public class BlockTypeUtil { case BlockID.DARK_OAK_FENCE_GATE: case BlockID.JUNGLE_FENCE_GATE: case BlockID.OAK_FENCE_GATE: - case BlockID.SPRUCE_FENCE_GATE: return block.getState(PropertyKey.OPEN) == Boolean.TRUE ? 0 : 1.5; + case BlockID.SPRUCE_FENCE_GATE: + return block.getState(PropertyKey.OPEN) == Boolean.TRUE ? 0 : 1.5; default: if (type.hasProperty(PropertyKey.LAYERS)) { return PropertyGroup.LEVEL.get(block) * 0.0625; } - if (!type.getMaterial().isMovementBlocker()) return 0; + if (!type.getMaterial().isMovementBlocker()) { + return 0; + } return 1; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypesCache.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypesCache.java index 897340388..f37067989 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypesCache.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypesCache.java @@ -31,7 +31,7 @@ public class BlockTypesCache { Settings ----------------------------------------------------- */ - protected final static class Settings { + protected static final class Settings { protected final int internalId; protected final BlockState defaultState; protected final AbstractProperty[] propertiesMapArr; @@ -124,7 +124,9 @@ public class BlockTypesCache { private static int[] generateStateOrdinals(int internalId, int ordinal, int maxStateId, List> props) { - if (props.isEmpty()) return null; + if (props.isEmpty()) { + return null; + } int[] result = new int[maxStateId]; Arrays.fill(result, -1); int[] state = new int[props.size()]; @@ -146,7 +148,9 @@ public class BlockTypesCache { while (++state[index] == sizes[index]) { state[index] = 0; index++; - if (index == state.length) break outer; + if (index == state.length) { + break outer; + } } index = 0; } @@ -162,8 +166,8 @@ public class BlockTypesCache { public static final int BIT_OFFSET; // Used internally protected static final int BIT_MASK; // Used internally -// private static final Map $REGISTRY = new HashMap<>(); -// public static final NamespacedRegistry REGISTRY = new NamespacedRegistry<>("block type", $REGISTRY); + //private static final Map $REGISTRY = new HashMap<>(); + //public static final NamespacedRegistry REGISTRY = new NamespacedRegistry<>("block type", $REGISTRY); public static final BlockType[] values; public static final BlockState[] states; @@ -184,7 +188,9 @@ public class BlockTypesCache { int size = blockMap.size() + 1; Field[] idFields = BlockID.class.getDeclaredFields(); - for (Field field : idFields) size = Math.max(field.getInt(null) + 1, size); + for (Field field : idFields) { + size = Math.max(field.getInt(null) + 1, size); + } BIT_OFFSET = MathMan.log2nlz(size); BIT_MASK = ((1 << BIT_OFFSET) - 1); values = new BlockType[size]; @@ -216,13 +222,17 @@ public class BlockTypesCache { for (Map.Entry entry : blockMap.entrySet()) { String defaultState = entry.getValue(); // Skip already registered ids - for (; values[internalId] != null; internalId++); + for (; values[internalId] != null; internalId++) { + ; + } BlockType type = register(defaultState, internalId, stateList, tickList); values[internalId] = type; } } for (int i = 0; i < values.length; i++) { - if (values[i] == null) values[i] = values[0]; + if (values[i] == null) { + values[i] = values[0]; + } } states = stateList.toArray(new BlockState[stateList.size()]); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/CompoundInput.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/CompoundInput.java index cd25c817b..b3af18520 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/CompoundInput.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/CompoundInput.java @@ -9,10 +9,9 @@ public enum CompoundInput { public BaseBlock get(BlockState state, ITileInput input, int x, int y, int z) { return state.toBaseBlock(input.getTile(x, y, z)); } - } + }; - ; public BaseBlock get(BlockState state, ITileInput input, int x, int y, int z) { return state.toBaseBlock(); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk.java index e7f5944f1..dd8e407b9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk.java @@ -85,14 +85,14 @@ public class AnvilChunk implements Chunk { } blocks[y] = NBTUtils.getChildTag(sectionTag.getValue(), - "Blocks", ByteArrayTag.class).getValue(); + "Blocks", ByteArrayTag.class).getValue(); data[y] = NBTUtils.getChildTag(sectionTag.getValue(), "Data", - ByteArrayTag.class).getValue(); + ByteArrayTag.class).getValue(); // 4096 ID block support if (sectionTag.getValue().containsKey("Add")) { blocksAdd[y] = NBTUtils.getChildTag(sectionTag.getValue(), - "Add", ByteArrayTag.class).getValue(); + "Add", ByteArrayTag.class).getValue(); } } @@ -100,16 +100,17 @@ public class AnvilChunk implements Chunk { for (byte[] block : blocks) { if (block.length != sectionsize) { throw new InvalidFormatException( - "Chunk blocks byte array expected " + "to be " + sectionsize + " bytes; found " - + block.length); + "Chunk blocks byte array expected " + "to be " + + sectionsize + " bytes; found " + + block.length); } } for (byte[] aData : data) { if (aData.length != (sectionsize / 2)) { - throw new InvalidFormatException( - "Chunk block data byte array " + "expected to be " + sectionsize - + " bytes; found " + aData.length); + throw new InvalidFormatException("Chunk block data byte array " + + "expected to be " + sectionsize + " bytes; found " + + aData.length); } } } @@ -178,7 +179,8 @@ public class AnvilChunk implements Chunk { * Used to load the tile entities. */ private void populateTileEntities() throws DataException { - List tags = NBTUtils.getChildTag(rootTag.getValue(), "TileEntities", ListTag.class).getValue(); + List tags = NBTUtils.getChildTag(rootTag.getValue(), + "TileEntities", ListTag.class).getValue(); tileEntities = new HashMap<>(); @@ -254,8 +256,7 @@ public class AnvilChunk implements Chunk { BlockState state = LegacyMapper.getInstance().getBlockFromLegacy(id, data); if (state == null) { - WorldEdit.logger.warn("Unknown legacy block " + id + ":" + data - + " found when loading legacy anvil chunk."); + WorldEdit.logger.warn("Unknown legacy block " + id + ":" + data + " found when loading legacy anvil chunk."); return BlockTypes.AIR.getDefaultState().toBaseBlock(); } CompoundTag tileEntity = getBlockTileEntity(position); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk13.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk13.java index aa7fe471d..4c4ce9e51 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk13.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/AnvilChunk13.java @@ -50,7 +50,7 @@ public class AnvilChunk13 implements Chunk { private int rootX; private int rootZ; - private Map> tileEntities; + private Map> tileEntities; /** * Construct the chunk with a compound tag. @@ -163,8 +163,6 @@ public class AnvilChunk13 implements Chunk { /** * Used to load the tile entities. - * - * @throws DataException */ private void populateTileEntities() throws DataException { tileEntities = new HashMap<>(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/fluid/FluidCategories.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/fluid/FluidCategories.java index 165223d23..b236a3914 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/fluid/FluidCategories.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/fluid/FluidCategories.java @@ -40,7 +40,8 @@ public final class FluidCategories { return FluidCategory.REGISTRY.register(tag.getId(), tag); } - public static @Nullable FluidCategory get(final String id) { + @Nullable + public static FluidCategory get(final String id) { return FluidCategory.REGISTRY.get(id); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/fluid/FluidTypes.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/fluid/FluidTypes.java index 493e0778d..13851f5e1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/fluid/FluidTypes.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/fluid/FluidTypes.java @@ -43,7 +43,8 @@ public final class FluidTypes { return FluidType.REGISTRY.register(fluid.getId(), fluid); } - public static @Nullable FluidType get(final String id) { + @Nullable + public static FluidType get(final String id) { return FluidType.REGISTRY.get(id); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BlockMaterial.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BlockMaterial.java index e4a4816bd..064a58c86 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BlockMaterial.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BlockMaterial.java @@ -95,7 +95,7 @@ public interface BlockMaterial { int getLightValue(); /** - * Get the opacity of the block + * Get the opacity of the block. * @return opacity */ int getLightOpacity(); @@ -159,14 +159,14 @@ public interface BlockMaterial { boolean isTranslucent(); /** - * Gets whether the block has a container (Item container) + * Gets whether the block has a container (Item container). * * @return If it has a container */ boolean hasContainer(); /** - * Get the map color + * Get the map color. * @return or 0 */ int getMapColor(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BlockRegistry.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BlockRegistry.java index f48e8e111..de439dcf9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BlockRegistry.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BlockRegistry.java @@ -75,7 +75,7 @@ public interface BlockRegistry { OptionalInt getInternalBlockStateId(BlockState state); /** - * Register all blocks + * Register all blocks. */ default Collection values() { return Collections.emptyList(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/EntityRegistry.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/EntityRegistry.java index 910637b0e..af3b3f8f9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/EntityRegistry.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/EntityRegistry.java @@ -45,7 +45,7 @@ public interface EntityRegistry { } /** - * Register all entities + * Register all entities. */ default Collection registerEntities() { return Collections.emptyList(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/LegacyMapper.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/LegacyMapper.java index e2ef7eda1..89cda0206 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/LegacyMapper.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/LegacyMapper.java @@ -158,7 +158,9 @@ public final class LegacyMapper { int base = blockArr[combinedId]; if (base != 0) { for (int data_ = 0; data_ < 16; data_++, combinedId++) { - if (blockArr[combinedId] == 0) blockArr[combinedId] = base; + if (blockArr[combinedId] == 0) { + blockArr[combinedId] = base; + } } } } @@ -193,12 +195,16 @@ public final class LegacyMapper { } public ItemType getItemFromLegacy(String input) { - if (input.startsWith("minecraft:")) input = input.substring(10); + if (input.startsWith("minecraft:")) { + input = input.substring(10); + } return itemMap.get(getCombinedId(input)); } public BlockState getBlockFromLegacy(String input) { - if (input.startsWith("minecraft:")) input = input.substring(10); + if (input.startsWith("minecraft:")) { + input = input.substring(10); + } try { return BlockState.getFromInternalId(blockArr[getCombinedId(input)]); } catch (InputParseException e) { @@ -246,13 +252,15 @@ public final class LegacyMapper { if (combinedId < blockArr.length) { try { int internalId = blockArr[combinedId]; - if (internalId == 0) return null; + if (internalId == 0) { + return null; + } try { return BlockState.getFromInternalId(internalId); } catch (InputParseException e) { e.printStackTrace(); } - } catch (IndexOutOfBoundsException ignore) { + } catch (IndexOutOfBoundsException ignored) { return null; } } @@ -279,7 +287,9 @@ public final class LegacyMapper { @Nullable public Integer getLegacyCombined(BlockState blockState) { Integer result = blockStateToLegacyId4Data.get(blockState.getInternalId()); - if (result == null) result = blockStateToLegacyId4Data.get(blockState.getInternalBlockTypeId()); + if (result == null) { + result = blockStateToLegacyId4Data.get(blockState.getInternalBlockTypeId()); + } return result; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/Snapshot.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/Snapshot.java index da8dd8a95..c3cee3b6e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/Snapshot.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/Snapshot.java @@ -64,8 +64,8 @@ public class Snapshot implements Comparable { * Get a chunk store. * * @return a chunk store - * @throws IOException - * @throws DataException + * @throws IOException if there is an error loading the chunk store + * @throws DataException if there is an error loading the chunk store */ public ChunkStore getChunkStore() throws IOException, DataException { ChunkStore chunkStore = internalGetChunkStore(); @@ -80,8 +80,8 @@ public class Snapshot implements Comparable { * Get a chunk store. * * @return a chunk store - * @throws IOException - * @throws DataException + * @throws IOException if there is an error loading the chunk store + * @throws DataException if there is an error loading the chunk store */ private ChunkStore internalGetChunkStore() throws IOException, DataException { String lowerCaseFileName = file.getName().toLowerCase(Locale.ROOT); @@ -205,8 +205,10 @@ public class Snapshot implements Comparable { public int compareTo(Snapshot o) { if (o.date == null || date == null) { // Remove the folder from the name - int i = name.indexOf('/'), j = o.name.indexOf('/'); - return name.substring((i > 0 ? 0 : i)).compareTo(o.name.substring((j > 0 ? 0 : j))); + int ourIndex = name.indexOf('/'); + int theirIndex = o.name.indexOf('/'); + return name.substring(Math.min(ourIndex, 0)) + .compareTo(o.name.substring(Math.min(theirIndex, 0))); } else { return date.compareTo(o.date); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/SnapshotRestore.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/SnapshotRestore.java index 5b579fa23..13ee5f549 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/SnapshotRestore.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/SnapshotRestore.java @@ -103,8 +103,9 @@ public class SnapshotRestore { } private void checkAndAddBlock(BlockVector3 pos) { - if (editSession.getMask() != null && !editSession.getMask().test(pos)) + if (editSession.getMask() != null && !editSession.getMask().test(pos)) { return; + } BlockVector2 chunkPos = ChunkStore.toChunk(pos); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/SnapshotInfo.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/SnapshotInfo.java index 6f1a12595..5a8b969d1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/SnapshotInfo.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/SnapshotInfo.java @@ -60,11 +60,15 @@ public final class SnapshotInfo implements Comparable { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } SnapshotInfo that = (SnapshotInfo) o; - return Objects.equals(name, that.name) && - Objects.equals(dateTime, that.dateTime); + return Objects.equals(name, that.name) + && Objects.equals(dateTime, that.dateTime); } @Override @@ -74,10 +78,10 @@ public final class SnapshotInfo implements Comparable { @Override public String toString() { - return "SnapshotInfo{" + - "name='" + name + '\'' + - ",date=" + dateTime + - '}'; + return "SnapshotInfo{" + + "name='" + name + '\'' + + ",date=" + dateTime + + '}'; } @Override diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/SnapshotRestore.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/SnapshotRestore.java index b1196404b..cce124cf4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/SnapshotRestore.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/SnapshotRestore.java @@ -101,8 +101,9 @@ public class SnapshotRestore { } private void checkAndAddBlock(BlockVector3 pos) { - if (editSession.getMask() != null && !editSession.getMask().test(pos)) + if (editSession.getMask() != null && !editSession.getMask().test(pos)) { return; + } BlockVector2 chunkPos = ChunkStore.toChunk(pos); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/fs/FolderSnapshot.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/fs/FolderSnapshot.java index 22a36718b..b646a945d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/fs/FolderSnapshot.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/snapshot/experimental/fs/FolderSnapshot.java @@ -95,7 +95,8 @@ public class FolderSnapshot implements Snapshot { private final SnapshotInfo info; private final Path folder; private final AtomicReference regionFolder = new AtomicReference<>(); - private final @Nullable Closer closeCallback; + @Nullable + private final Closer closeCallback; public FolderSnapshot(SnapshotInfo info, Path folder, @Nullable Closer closeCallback) { this.info = info; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/ChunkStore.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/ChunkStore.java index 55dc5ce59..7123dce30 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/ChunkStore.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/ChunkStore.java @@ -35,14 +35,22 @@ import java.io.IOException; public abstract class ChunkStore implements Closeable { /** + * The shift for converting to/from a chunk position. + * + *

* {@code >>} - to chunk * {@code <<} - from chunk + *

*/ public static final int CHUNK_SHIFTS = 4; /** + * The shift for converting to/from a 3D chunk position. + * + *

* {@code >>} - to Y of 3D-chunk * {@code <<} - from Y of 3D-chunk + *

*/ public static final int CHUNK_SHIFTS_Y = 8; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/ChunkStoreHelper.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/ChunkStoreHelper.java index 6928964ae..70f189f6f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/ChunkStoreHelper.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/ChunkStoreHelper.java @@ -88,7 +88,9 @@ public class ChunkStoreHelper { } int dataVersion = rootTag.getInt("DataVersion"); - if (dataVersion == 0) dataVersion = -1; + if (dataVersion == 0) { + dataVersion = -1; + } final Platform platform = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING); final int currentDataVersion = platform.getDataVersion(); if (tag.getValue().containsKey("Sections") && dataVersion < currentDataVersion) { // only fix up MCA format, DFU doesn't support MCR chunks diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/FileLegacyChunkStore.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/FileLegacyChunkStore.java index aa879e2c7..3037d29f2 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/FileLegacyChunkStore.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/FileLegacyChunkStore.java @@ -24,7 +24,6 @@ import com.sk89q.worldedit.world.DataException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; -import java.io.IOException; import java.io.InputStream; /** @@ -32,7 +31,7 @@ import java.io.InputStream; */ public class FileLegacyChunkStore extends LegacyChunkStore { - private File path; + private final File path; /** * Create an instance. The passed path is the folder to read the @@ -51,11 +50,10 @@ public class FileLegacyChunkStore extends LegacyChunkStore { * @param f2 the second part of the pathname * @param name the name of the file * @return an input stream - * @throws DataException - * @throws IOException + * @throws DataException if there is an error getting data for this chunk */ @Override - protected InputStream getInputStream(String f1, String f2, String name) throws DataException, IOException { + protected InputStream getInputStream(String f1, String f2, String name) throws DataException { String file = f1 + File.separator + f2 + File.separator + name; try { return new FileInputStream(new File(path, file)); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/FileMcRegionChunkStore.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/FileMcRegionChunkStore.java index 569545725..b9a045de4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/FileMcRegionChunkStore.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/FileMcRegionChunkStore.java @@ -62,7 +62,9 @@ public class FileMcRegionChunkStore extends McRegionChunkStore { } try { - if (file == null) throw new FileNotFoundException(); + if (file == null) { + throw new FileNotFoundException(); + } return new FileInputStream(file); } catch (FileNotFoundException e) { throw new MissingChunkException(); @@ -71,8 +73,8 @@ public class FileMcRegionChunkStore extends McRegionChunkStore { @Override public boolean isValid() { - return new File(path, "region").isDirectory() || - new File(path, "DIM-1" + File.separator + "region").isDirectory(); + return new File(path, "region").isDirectory() + || new File(path, "DIM-1" + File.separator + "region").isDirectory(); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/TrueZipLegacyChunkStore.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/TrueZipLegacyChunkStore.java index 7d4c9fffe..fd083fa48 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/TrueZipLegacyChunkStore.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/TrueZipLegacyChunkStore.java @@ -36,8 +36,8 @@ import java.util.zip.ZipException; */ public class TrueZipLegacyChunkStore extends LegacyChunkStore { - private File zipFile; - private ZipFile zip; + private final File zipFile; + private final ZipFile zip; private String folder; /** @@ -47,8 +47,8 @@ public class TrueZipLegacyChunkStore extends LegacyChunkStore { * * @param zipFile the ZIP file to open * @param folder the folder to look into in the ZIP - * @throws IOException - * @throws ZipException + * @throws IOException if there is an error opening the zip + * @throws ZipException if there is an error opening the zip */ public TrueZipLegacyChunkStore(File zipFile, String folder) throws IOException, ZipException { this.zipFile = zipFile; @@ -62,8 +62,8 @@ public class TrueZipLegacyChunkStore extends LegacyChunkStore { * be detected. * * @param zipFile the ZIP file to open - * @throws IOException - * @throws ZipException + * @throws IOException if there is an error opening the zip + * @throws ZipException if there is an error opening the zip */ public TrueZipLegacyChunkStore(File zipFile) throws IOException, ZipException { this.zipFile = zipFile; @@ -78,8 +78,8 @@ public class TrueZipLegacyChunkStore extends LegacyChunkStore { * @param f2 the second part of the filename * @param name the name of the file * @return an input stream - * @throws IOException - * @throws DataException + * @throws IOException if there is an error getting the chunk data + * @throws DataException if there is an error getting the chunk data */ @Override @SuppressWarnings("unchecked") diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/TrueZipMcRegionChunkStore.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/TrueZipMcRegionChunkStore.java index e942a1665..679d7257c 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/TrueZipMcRegionChunkStore.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/TrueZipMcRegionChunkStore.java @@ -49,8 +49,8 @@ public class TrueZipMcRegionChunkStore extends McRegionChunkStore { * * @param zipFile the ZIP file * @param folder the folder to look into - * @throws IOException - * @throws ZipException + * @throws IOException if there is an error opening the zip + * @throws ZipException if there is an error opening the zip */ public TrueZipMcRegionChunkStore(File zipFile, String folder) throws IOException, ZipException { this.zipFile = zipFile; @@ -64,8 +64,8 @@ public class TrueZipMcRegionChunkStore extends McRegionChunkStore { * be detected. * * @param zipFile the ZIP file - * @throws IOException - * @throws ZipException + * @throws IOException if there is an error opening the zip + * @throws ZipException if there is an error opening the zip */ public TrueZipMcRegionChunkStore(File zipFile) throws IOException, ZipException { this.zipFile = zipFile; @@ -79,8 +79,8 @@ public class TrueZipMcRegionChunkStore extends McRegionChunkStore { * @param name the name * @param worldName the world name * @return an input stream - * @throws IOException - * @throws DataException + * @throws IOException if there is an error getting the chunk data + * @throws DataException if there is an error getting the chunk data */ @Override @SuppressWarnings("unchecked") @@ -97,11 +97,18 @@ public class TrueZipMcRegionChunkStore extends McRegionChunkStore { for (Enumeration e = zip.entries(); e.hasMoreElements(); ) { ZipEntry testEntry = e.nextElement(); // Check for world - if (worldPattern.matcher(testEntry.getName()).matches()) { + String entryName = testEntry.getName(); + if (worldPattern.matcher(entryName).matches()) { // Check for file - if (pattern.matcher(testEntry.getName()).matches()) { - folder = testEntry.getName().substring(0, testEntry.getName().lastIndexOf('/')); - if (folder.endsWith("poi")) continue; + if (pattern.matcher(entryName).matches()) { + int endIndex = entryName.lastIndexOf('/'); + if (endIndex < 0) { + endIndex = entryName.lastIndexOf('\\'); + } + folder = entryName.substring(0, endIndex); + if (folder.endsWith("poi")) { + continue; + } name = folder + "/" + name; break; } diff --git a/worldedit-core/src/main/java/net/jpountz/util/Native.java b/worldedit-core/src/main/java/net/jpountz/util/Native.java index 796acd252..5e7c3b6f4 100644 --- a/worldedit-core/src/main/java/net/jpountz/util/Native.java +++ b/worldedit-core/src/main/java/net/jpountz/util/Native.java @@ -12,7 +12,7 @@ package net.jpountz.util; * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * This file has been modified for use in the FAWE project. */ @@ -74,14 +74,14 @@ public enum Native { File[] tempLibFiles = dir.listFiles((dir1, name) -> name.startsWith("liblz4-java-") && !name.endsWith(".lck")); - if(tempLibFiles != null) { - for(File tempLibFile : tempLibFiles) { + if (tempLibFiles != null) { + for (File tempLibFile : tempLibFiles) { File lckFile = new File(tempLibFile.getAbsolutePath() + ".lck"); - if(!lckFile.exists()) { + if (!lckFile.exists()) { try { tempLibFile.delete(); } - catch(SecurityException e) { + catch (SecurityException e) { System.err.println("Failed to delete old temp lib" + e.getMessage()); } } diff --git a/worldedit-core/src/main/resources/cs_adv.js b/worldedit-core/src/main/resources/cs_adv.js index f619c3e49..c0f6e7081 100644 --- a/worldedit-core/src/main/resources/cs_adv.js +++ b/worldedit-core/src/main/resources/cs_adv.js @@ -5,7 +5,7 @@ var a = func.toString().replace(STRIP_COMMENTS, ''); var r = a.slice(a.indexOf('(')+1, a.indexOf(')')).match(ARGUMENT_NAMES); var l = new java.util.ArrayList(); - if(r !== null) { + if (r !== null) { for (var i = 0; i < r.length; i++) { l.add(r[i]); } @@ -13,10 +13,10 @@ return l; } - function getAllFunctions(){ + function getAllFunctions() { var a = new java.util.ArrayList(); - for (var f in this){ - if (this.hasOwnProperty(f) && this[f] instanceof Function && !/a/i.test(f)){ + for (var f in this) { + if (this.hasOwnProperty(f) && this[f] instanceof Function && !/a/i.test(f)) { a.add(this[f]); } } @@ -48,4 +48,4 @@ } } commands; -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/resources/lang/strings.json b/worldedit-core/src/main/resources/lang/strings.json index 016a3d60d..b86e09a95 100644 --- a/worldedit-core/src/main/resources/lang/strings.json +++ b/worldedit-core/src/main/resources/lang/strings.json @@ -98,7 +98,6 @@ "fawe.error.setting.disable": "Lacking setting: {0}", "fawe.error.brush.not.found": "Available brushes: {0}", "fawe.error.brush.incompatible": "Brush not compatible with this version", - "fawe.error.schematic.not.found": "Schematic not found: {0}", "fawe.error.no.region": "You have no current allowed region", "fawe.error.player.not.found": "Player not found: {0}", "fawe.error.worldedit.some.fails": "{0} blocks weren't placed because they were outside your allowed region.",