diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index f8b8492f7..000000000 --- a/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: java -notifications: - email: false -before_install: chmod +x gradlew -install: ./gradlew setupCIWorkspace -s -script: ./gradlew build -s -jdk: - - oraclejdk8 -# Caching for Gradle files, prevents hitting Maven too much. -before_cache: - - find $HOME/.gradle/ -name '*.lock' -print -exec rm -f {} \; -cache: - directories: - - $HOME/.gradle/caches/ - - $HOME/.gradle/wrapper/ - -# Faster builds without sudo. -sudo: false diff --git a/COMPILING.md b/COMPILING.md deleted file mode 100644 index d3e5bac5c..000000000 --- a/COMPILING.md +++ /dev/null @@ -1,50 +0,0 @@ -Compiling -========= - -You can compile WorldEdit as long as you have the [Java Development Kit (JDK)](http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html) for Java 8 or newer. -You only need one version of the JDK installed. - -The build process uses Gradle, which you do *not* need to download. WorldEdit is a multi-module project with four modules: - -* `worldedit-core` contains the WorldEdit API -* `worldedit-bukkit` is the Bukkit plugin -* `worldedit-sponge` is the Sponge plugin -* `worldedit-forge` is the Forge mod - -## To compile... - -### On Windows - -1. Shift + right click the folder with WorldEdit's files and click "Open command prompt". -2. `gradlew clean setupDecompWorkspace` -3. `gradlew build` - -### On Linux, BSD, or Mac OS X - -1. In your terminal, navigate to the folder with WorldEdit's files (`cd /folder/of/worldedit/files`) -2. `./gradlew clean setupDecompWorkspace` -3. `./gradlew build` - -## Then you will find... - -You will find: - -* The core WorldEdit API in **worldedit-core/build/libs** -* WorldEdit for Bukkit in **worldedit-bukkit/build/libs** -* WorldEdit for Sponge in **worldedit-sponge/build/libs** -* WorldEdit for Forge in **worldedit-forge/build/libs** - -If you want to use WorldEdit, use the `-dist` version. - -(The -dist version includes WorldEdit + necessary libraries.) - -### Note regarding `setupDecompWorkspace` -`setupDecompWorkspace` requires more memory than is usually given to Gradle by default. -If it fails, you should put `org.gradle.jvmargs=-Xmx3G` in `gradle.properties`. -Please don't commit this change! - -## Other commands - -* `gradlew idea` will generate an [IntelliJ IDEA](http://www.jetbrains.com/idea/) module for each folder. -* `gradlew eclipse` will generate an [Eclipse](https://www.eclipse.org/downloads/) project for each folder. -* Use `setupCIWorkspace` instead of `setupDecompWorkspace` if you are doing this on a CI server. diff --git a/README.md b/README.md index 973c8968a..c8494060a 100644 --- a/README.md +++ b/README.md @@ -15,17 +15,18 @@ FAWE is a fork of WorldEdit that has huge speed and memory improvements and cons ## Downloads ### 1.13+ -* [Download](https://empcraft.com/fawe/download/?bukkit113) -* [Jenkins](https://ci.athion.net/job/FAWE-1.13/) +* [Download](https://incendo.org/download/) +* [Jenkins](https://ci.athion.net/job/FastAsyncWorldEdit-1.13/) -### <1.12.2 -* [Download](https://empcraft.com/fawe/download/?bukkit) +### < 1.12.2 +* [Download](https://incendo.org/download/) * [Jenkins](https://ci.athion.net/job/FastAsyncWorldEdit/) * [Repository](https://github.com/boy0001/FastAsyncWorldedit) ## Building -FAWE uses gradle to build +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 diff --git a/build.gradle b/build.gradle index afd809465..ac4274c38 100644 --- a/build.gradle +++ b/build.gradle @@ -27,7 +27,11 @@ plugins { apply plugin: 'java' clean { delete "target" } -print new File('splash.txt').text + +def splashFile = new File('splash.txt') +if (splashFile.exists()) { + print splashFile.text +} group = 'com.boydti.fawe' @@ -78,11 +82,10 @@ subprojects { maven { url "http://maven.sk89q.com/repo/" } maven { url "http://repo.maven.apache.org/maven2" } // Fawe - maven {url "http://ci.athion.net/job/FAWE-WorldGuard-1.13/ws/mvn/"} maven {url "https://mvnrepository.com/artifact/"} maven {url "http://repo.dmulloy2.net/content/groups/public/"} maven {url "https://repo.destroystokyo.com/repository/maven-public//"} - maven {url "http://ci.athion.net/job/PlotSquared-Legacy/ws/mvn/"} + maven {url "http://ci.athion.net/job/PlotSquared-Breaking/ws/mvn/"} mavenLocal() maven {url "http://empcraft.com/maven2"} maven {url "https://hub.spigotmc.org/nexus/content/groups/public/"} diff --git a/config/checkstyle/import-control.xml b/config/checkstyle/import-control.xml index 2fe94d97d..eedd07857 100644 --- a/config/checkstyle/import-control.xml +++ b/config/checkstyle/import-control.xml @@ -14,6 +14,7 @@ + @@ -30,6 +31,7 @@ + diff --git a/contrib/craftscripts/README.txt b/contrib/craftscripts/README.txt index 607196a4e..7638e67ed 100644 --- a/contrib/craftscripts/README.txt +++ b/contrib/craftscripts/README.txt @@ -2,7 +2,7 @@ CraftScripts are script files for WorldEdit that let you write world editing scripts with JavaScript easily. Example usage: -/cs maze.js lightstone 10 10 +/cs maze.js glowstone 10 10 You may or may not install these scripts -- it is optional. If you are, however, place the entire craftscripts/ folder into the respective directory for the platform diff --git a/contrib/craftscripts/SUBMITTING.txt b/contrib/craftscripts/SUBMITTING.txt index d39505cf5..b519effe8 100644 --- a/contrib/craftscripts/SUBMITTING.txt +++ b/contrib/craftscripts/SUBMITTING.txt @@ -7,4 +7,4 @@ Note: Legally you should not release things to the public domain as not all countries have the concept of public domain in their copyright law. You can also post your scripts here: -http://forum.sk89q.com/forums/craftscripts.6/ \ No newline at end of file +https://discord.gg/YKbmj7V or http://forum.sk89q.com/forums/craftscripts.6/ \ No newline at end of file diff --git a/contrib/craftscripts/draw.js b/contrib/craftscripts/draw.js index 0454864f3..bc78843b9 100644 --- a/contrib/craftscripts/draw.js +++ b/contrib/craftscripts/draw.js @@ -43,8 +43,26 @@ var clothColors = [ makeColor(100, 60, 0), // Brown makeColor(48, 80, 0), // Cactus green makeColor(255, 0, 0), // Red - makeColor(0, 0, 0), // Black -] + makeColor(0, 0, 0) // Black +]; +var clothBlocks = [ + context.getBlock("white_wool"), + context.getBlock("orange_wool"), + context.getBlock("magenta_wool"), + context.getBlock("light_blue_wool"), + context.getBlock("yellow_wool"), + context.getBlock("lime_wool"), + context.getBlock("pink_wool"), + context.getBlock("gray_wool"), + context.getBlock("light_gray_wool"), + context.getBlock("cyan_wool"), + context.getBlock("purple_wool"), + context.getBlock("blue_wool"), + context.getBlock("brown_wool"), + context.getBlock("green_wool"), + context.getBlock("red_wool"), + context.getBlock("black_wool") +]; var clothColorsOpt = [ makeColor(178, 178, 178), // White makeColor(187, 102, 44), // Orange @@ -61,8 +79,8 @@ var clothColorsOpt = [ makeColor(68, 41, 22), // Brown makeColor(44, 61, 19), // Cactus green makeColor(131, 36, 32), // Red - makeColor(21, 18, 18), // Black -] + makeColor(21, 18, 18) // Black +]; var clothColorsOptHD = [ makeColor(168, 168, 168), // White makeColor(143, 59, 0), // Orange @@ -79,8 +97,8 @@ var clothColorsOptHD = [ makeColor(52, 25, 0), // Brown makeColor(10, 76, 10), // Cactus green makeColor(127, 9, 9), // Red - makeColor(17, 17, 17), // Black -] + makeColor(17, 17, 17) // Black +]; // http://stackoverflow.com/questions/2103368/color-logic-algorithm/2103608#2103608 function colorDistance(c1, c2) { @@ -90,7 +108,7 @@ function colorDistance(c1, c2) { var b = c1.getBlue() - c2.getBlue(); var weightR = 2 + rmean/256; var weightG = 4.0; - var weightB = 2 + (255-rmean)/256 + var weightB = 2 + (255-rmean)/256; return Math.sqrt(weightR*r*r + weightG*g*g + weightB*b*b); } @@ -113,14 +131,14 @@ function findClosestWoolColor(col, clothColors) { context.checkArgs(1, 3, " "); -var f = context.getSafeFile("drawings", argv[1]); +var f = context.getSafeOpenFile("drawings", argv[1], "png", ["png", "jpg", "jpeg", "bmp"]); var sess = context.remember(); -var upright = argv[2] == "v"; +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"); } @@ -132,7 +150,7 @@ if (!f.exists()) { var width = img.getWidth(); var height = img.getHeight(); - var origin = player.getBlockIn(); + var origin = player.getBlockIn().toVector().toBlockPoint(); for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { @@ -141,9 +159,9 @@ if (!f.exists()) { // Added this to enable the user to create images upright // rather than flat on the ground if (!upright) { - sess.setBlock(origin.add(x, 0, y), new BaseBlock(35, data)); + sess.setBlock(origin.add(x, 0, y), clothBlocks[data]); } else { - sess.setBlock(origin.add(x, height - y, 0), new BaseBlock(35, data)); + sess.setBlock(origin.add(x, height - y, 0), clothBlocks[data]); } } } diff --git a/contrib/craftscripts/maze.js b/contrib/craftscripts/maze.js index dd5ca6a52..ea97ea042 100644 --- a/contrib/craftscripts/maze.js +++ b/contrib/craftscripts/maze.js @@ -19,6 +19,7 @@ importPackage(Packages.com.sk89q.worldedit); importPackage(Packages.com.sk89q.worldedit.blocks); +importPackage(Packages.com.sk89q.worldedit.math); usage = " [width] [length] [height] [size] [thickness] flags\n"; usage += "\n"; @@ -40,10 +41,15 @@ usage += "• b places blue wool if unvisited"; context.checkArgs(1, -1, usage); sess = context.remember(); -origin = player.getBlockIn(); +origin = player.getBlockIn().toVector().toBlockPoint(); // This may throw an exception that is caught by the script processor block = context.getBlock(argv[1]); +airBlock = context.getBlock("air"); +glassBlock = context.getBlock("glass"); +limeWoolBlock = context.getBlock("lime_wool"); +redWoolBlock = context.getBlock("red_wool"); +blueWoolBlock = context.getBlock("blue_wool"); if (argv.length > 7) flags = String(argv[7]); else flags = false; @@ -74,20 +80,20 @@ if (argv.length > 2) { } else w = 5; if (flags) { - ee = flags.search("i") != -1 ? true : false; - r = flags.search("y") != -1 ? true : false; + ee = flags.search("i") != -1; + r = flags.search("y") != -1; if (r) ee = true; - f = flags.search("f") != -1 ? true : false; - c = flags.search("c") != -1 ? true : false; - e = flags.search("e") != -1 ? true : false; - ao = flags.search("a") != -1 ? true : false; + f = flags.search("f") != -1; + c = flags.search("c") != -1; + e = flags.search("e") != -1; + ao = flags.search("a") != -1; if (ao) f = c = false, e = true; - v = flags.search("v") != -1 ? true : false; - so = flags.search("s") != -1 ? true : false; + v = flags.search("v") != -1; + so = flags.search("s") != -1; if (so) ee = true; - g = flags.search("g") != -1 ? true : false; - re = flags.search("r") != -1 ? true : false; - bl = flags.search("b") != -1 ? true : false; + g = flags.search("g") != -1; + re = flags.search("r") != -1; + bl = flags.search("b") != -1; if (g || re || bl) so = ee = true; } else ee = r = f = c = e = ao = v = so = g = re = bl = false; @@ -208,8 +214,8 @@ for (y = 0; y <= l; y++) for (x = 0; x <= w; x++) { } } else if (e && cell != id(x, l)) { for (z = 0; z < h; z++) for (yi = 0; yi < s; yi++) for (xi = 1; xi <= wa; xi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, z, y * (s + wa) + yi), BaseBlock(0)); - else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, -z), BaseBlock(0)); + if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, z, y * (s + wa) + yi), airBlock); + else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, -z), airBlock); } } @@ -222,8 +228,8 @@ for (y = 0; y <= l; y++) for (x = 0; x <= w; x++) { } } else if (e && cell != id(w, y)) { for (z = 0; z < h; z++) for (yi = 1; yi <= wa; yi++) for (xi = 0; xi < s; xi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, z, y * (s + wa) - yi), BaseBlock(0)); - else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, -z), BaseBlock(0)); + if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, z, y * (s + wa) - yi), airBlock); + else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, -z), airBlock); } } @@ -236,8 +242,8 @@ for (y = 0; y <= l; y++) for (x = 0; x <= w; x++) { if (e && cell != id(x, l) && cell != id(w, y)) { for (z = 0; z < h; z++) for (yi = 0; yi < s; yi++) for (xi = 0; xi < s; xi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, z, y * (s + wa) + yi), BaseBlock(0)); - else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) + yi, -z), BaseBlock(0)); + if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, z, y * (s + wa) + yi), airBlock); + else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) + yi, -z), airBlock); } } } @@ -281,51 +287,51 @@ if (so) { if (visited[cell] && !wrong[cell]) { for (yi = 0; yi < s; yi++) for (xi = 0; xi < s; xi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) + yi), BaseBlock(35, 5)); - else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) + yi, +1), BaseBlock(35, 5)); + if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) + yi), limeWoolBlock); + else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) + yi, +1), limeWoolBlock); } } if ((visited[cell] && !wrong[cell] && visited[id(x - 1, y)] && !wrong[id(x - 1, y)] && noWallLeft[cell]) || cell == start || id(x - 1, y) == end) { for (xi = 1; xi <= wa; xi++) for (yi = 0; yi < s; yi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, -1, y * (s + wa) + yi), BaseBlock(35, 5)); - else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, +1), BaseBlock(35, 5)); + if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, -1, y * (s + wa) + yi), limeWoolBlock); + else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, +1), limeWoolBlock); } } if (visited[cell] && !wrong[cell] && visited[id(x, y - 1)] && !wrong[id(x, y - 1)] && noWallAbove[cell]) { for (xi = 0; xi < s; xi++) for (yi = 1; yi <= wa; yi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) - yi), BaseBlock(35, 5)); - else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, +1), BaseBlock(35, 5)); + if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) - yi), limeWoolBlock); + else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, +1), limeWoolBlock); } } if (g) { if (visited[cell] && !wrong[cell] && (!visited[id(x - 1, y)] || wrong[id(x - 1, y)]) && noWallLeft[cell] && cell != start) { for (z = 0; z < h; z++) for (xi = 1; xi <= wa; xi++) for (yi = 0; yi < s; yi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, z, y * (s + wa) + yi), BaseBlock(20)); - else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, -z), BaseBlock(20)); + if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, z, y * (s + wa) + yi), glassBlock); + else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, -z), glassBlock); } } if ((!visited[cell] || wrong[cell]) && visited[id(x - 1, y)] && !wrong[id(x - 1, y)] && noWallLeft[cell] && id(x - 1, y) != end) { for (z = 0; z < h; z++) for (xi = 1; xi <= wa; xi++) for (yi = 0; yi < s; yi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, z, y * (s + wa) + yi), BaseBlock(20)); - else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, -z), BaseBlock(20)); + if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, z, y * (s + wa) + yi), glassBlock); + else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, -z), glassBlock); } } if (visited[cell] && !wrong[cell] && (!visited[id(x, y - 1)] || wrong[id(x, y - 1)]) && noWallAbove[cell]) { for (z = 0; z < h; z++) for (xi = 0; xi < s; xi++) for (yi = 1; yi <= wa; yi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, z, y * (s + wa) - yi), BaseBlock(20)); - else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, -z), BaseBlock(20)); + if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, z, y * (s + wa) - yi), glassBlock); + else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, -z), glassBlock); } } if ((!visited[cell] || wrong[cell]) && visited[id(x, y - 1)] && !wrong[id(x, y - 1)] && noWallAbove[cell]) { for (z = 0; z < h; z++) for (xi = 0; xi < s; xi++) for (yi = 1; yi <= wa; yi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, z, y * (s + wa) - yi), BaseBlock(20)); - else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, -z), BaseBlock(20)); + if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, z, y * (s + wa) - yi), glassBlock); + else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, -z), glassBlock); } } } @@ -333,22 +339,22 @@ if (so) { if (re) { if (wrong[cell]) { for (yi = 0; yi < s; yi++) for (xi = 0; xi < s; xi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) + yi), BaseBlock(35, 14)); - else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) + yi, +1), BaseBlock(35, 14)); + if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) + yi), redWoolBlock); + else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) + yi, +1), redWoolBlock); } } if ((wrong[cell] || wrong[id(x - 1, y)]) && noWallLeft[cell]) { for (xi = 1; xi <= wa; xi++) for (yi = 0; yi < s; yi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, -1, y * (s + wa) + yi), BaseBlock(35, 14)); - else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, +1), BaseBlock(35, 14)); + if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, -1, y * (s + wa) + yi), redWoolBlock); + else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, +1), redWoolBlock); } } if ((wrong[cell] || wrong[id(x, y - 1)]) && noWallAbove[cell]) { for (xi = 0; xi < s; xi++) for (yi = 1; yi <= wa; yi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) - yi), BaseBlock(35, 14)); - else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, +1), BaseBlock(35, 14)); + if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) - yi), redWoolBlock); + else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, +1), redWoolBlock); } } } @@ -356,22 +362,22 @@ if (so) { if (bl) { if (!visited[cell] && y < l && x < w) { for (yi = 0; yi < s; yi++) for (xi = 0; xi < s; xi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) + yi), BaseBlock(35, 11)); - else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) + yi, +1), BaseBlock(35, 11)); + if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) + yi), blueWoolBlock); + else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) + yi, +1), blueWoolBlock); } } if ((!visited[cell] || !visited[id(x - 1, y)]) && noWallLeft[cell] && x > 0 && x < w) { for (xi = 1; xi <= wa; xi++) for (yi = 0; yi < s; yi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, -1, y * (s + wa) + yi), BaseBlock(35, 11)); - else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, +1), BaseBlock(35, 11)); + if (!v) sess.setBlock(origin.add(x * (s + wa) - xi, -1, y * (s + wa) + yi), blueWoolBlock); + else sess.setBlock(origin.add(x * (s + wa) - xi, y * (s + wa) + yi, +1), blueWoolBlock); } } if ((!visited[cell] || !visited[id(x, y - 1)]) && noWallAbove[cell]) { for (xi = 0; xi < s; xi++) for (yi = 1; yi <= wa; yi++) { - if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) - yi), BaseBlock(35, 11)); - else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, +1), BaseBlock(35, 11)); + if (!v) sess.setBlock(origin.add(x * (s + wa) + xi, -1, y * (s + wa) - yi), blueWoolBlock); + else sess.setBlock(origin.add(x * (s + wa) + xi, y * (s + wa) - yi, +1), blueWoolBlock); } } } diff --git a/contrib/craftscripts/quickshot.js b/contrib/craftscripts/quickshot.js index e47820ea7..27480e282 100644 --- a/contrib/craftscripts/quickshot.js +++ b/contrib/craftscripts/quickshot.js @@ -20,11 +20,11 @@ importPackage(Packages.com.sk89q.worldedit); importPackage(Packages.com.sk89q.worldedit.blocks); -var torchDirs = {} -torchDirs[PlayerDirection.NORTH] = [2, 4]; -torchDirs[PlayerDirection.SOUTH] = [1, 3]; -torchDirs[PlayerDirection.WEST] = [3, 2]; -torchDirs[PlayerDirection.EAST] = [4, 1]; +var torchDirs = {}; +torchDirs[Direction.NORTH] = [2, 4]; +torchDirs[Direction.SOUTH] = [1, 3]; +torchDirs[Direction.WEST] = [3, 2]; +torchDirs[Direction.EAST] = [4, 1]; var pitches = { "f#": 0, diff --git a/contrib/craftscripts/roof.js b/contrib/craftscripts/roof.js index 35e03c244..b1201ea3a 100644 --- a/contrib/craftscripts/roof.js +++ b/contrib/craftscripts/roof.js @@ -16,20 +16,20 @@ * along with this program. If not, see . */ -importPackage(Packages.java.io); -importPackage(Packages.java.awt); importPackage(Packages.com.sk89q.worldedit); +importPackage(Packages.com.sk89q.worldedit.math); importPackage(Packages.com.sk89q.worldedit.blocks); var blocks = context.remember(); var session = context.getSession(); -var region = session.getRegion(); +var player = context.getPlayer(); +var region = session.getRegionSelector(player.getWorld()).getRegion(); context.checkArgs(1, 1, ""); var blocktype = context.getBlock(argv[1]); -var cycles = region.getLength() +var cycles = region.getLength(); if (region.getWidth() > cycles){ cycles = region.getWidth(); @@ -40,12 +40,12 @@ cycles = cycles / 2; for (var c = 0; c < cycles; c++) { for (var w = 0; w < region.getWidth() - (c * 2); w++) { for (var l = 0; l < region.getLength() - (c * 2); l++) { - if (w == 0 || w == (region.getWidth() - (c * 2)) - 1 || l == 0 || l == (region.getLength() - (c * 2)) - 1) { - var vec = new Vector( + if (w === 0 || w === (region.getWidth() - (c * 2)) - 1 || l === 0 || l === (region.getLength() - (c * 2)) - 1) { + var vec = BlockVector3.at( region.getMinimumPoint().getX() + (w + c), region.getMaximumPoint().getY() + c, region.getMinimumPoint().getZ() + (l + c)); - + blocks.setBlock(vec, blocktype); } } diff --git a/favs/build.gradle b/favs/build.gradle index 778e6aee2..7aded4c06 100644 --- a/favs/build.gradle +++ b/favs/build.gradle @@ -1,3 +1,6 @@ +apply plugin: 'eclipse' +apply plugin: 'maven' + repositories { maven {url "https://ci.athion.net/job/FAWE-WorldGuard-1.13/lastSuccessfulBuild/artifact/mvn"} } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/Brushes.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/Brushes.java index 77fcc072b..3517a1d05 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/Brushes.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/Brushes.java @@ -79,7 +79,7 @@ public class Brushes */ public Set getSniperBrushHandles(Class clazz) { - return new HashSet(brushes.get(clazz)); + return new HashSet<>(brushes.get(clazz)); } /** diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/Message.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/Message.java index 340fcf282..34e991325 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/Message.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/Message.java @@ -158,12 +158,9 @@ public class Message } else { - StringBuilder returnValueBuilder = new StringBuilder(); - returnValueBuilder.append(ChatColor.DARK_GREEN); - returnValueBuilder.append("Block Types Selected: "); - returnValueBuilder.append(ChatColor.AQUA); - returnValueBuilder.append(snipeData.getVoxelList()); - snipeData.sendMessage(returnValueBuilder.toString()); + String returnValueBuilder = ChatColor.DARK_GREEN + "Block Types Selected: " + ChatColor.AQUA + + snipeData.getVoxelList(); + snipeData.sendMessage(returnValueBuilder); } } } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/PaintingWrapper.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/PaintingWrapper.java index 25df54ee1..78a75ef49 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/PaintingWrapper.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/PaintingWrapper.java @@ -40,8 +40,8 @@ public final class PaintingWrapper @SuppressWarnings("deprecation") public static void paint(final Player p, final boolean auto, final boolean back, final int choice) { - Location targetLocation = p.getTargetBlock((Set) null, 4).getLocation(); - Chunk paintingChunk = p.getTargetBlock((Set) null, 4).getLocation().getChunk(); + Location targetLocation = p.getTargetBlock(null, 4).getLocation(); + Chunk paintingChunk = p.getTargetBlock(null, 4).getLocation().getChunk(); Double bestDistanceMatch = 50D; Painting bestMatch = null; @@ -66,7 +66,7 @@ public final class PaintingWrapper { try { - final int i = bestMatch.getArt().getId() + (back ? -1 : 1) + Art.values().length % Art.values().length; + final int i = bestMatch.getArt().getId() + (back ? -1 : 1); Art art = Art.getById(i); if (art == null) diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/SnipeData.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/SnipeData.java index e997e5ec6..9e606daff 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/SnipeData.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/SnipeData.java @@ -77,7 +77,7 @@ public class SnipeData { */ private int voxelHeight = SnipeData.DEFAULT_VOXEL_HEIGHT; /** - * Voxel centroid -- set Cylynder center /vc #. + * Voxel centroid -- set Cylinder center /vc #. */ private int cCen = SnipeData.DEFAULT_CYLINDER_CENTER; private int range = 0; @@ -272,7 +272,7 @@ public class SnipeData { * @param voxelId the voxelId to set */ public final void setVoxelId(final int voxelId) { - if (WorldEdit.getInstance().getConfiguration().disallowedBlocks.contains(voxelId)) { + if (WorldEdit.getInstance().getConfiguration().disallowedBlocks.contains(BlockTypes.getFromStateId(voxelId).getId())) { if (owner != null) { Player plr = owner.getPlayer(); if (plr != null) { @@ -325,4 +325,4 @@ public class SnipeData { public static Class inject() { return SnipeData.class; } -} \ No newline at end of file +} diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/Sniper.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/Sniper.java index 4c8e102a9..b0ec73c77 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/Sniper.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/Sniper.java @@ -94,7 +94,7 @@ public class Sniper { } public String getCurrentToolId() { - return getToolId((getPlayer().getItemInHand() != null) ? getPlayer().getItemInHand().getType() : null); + return getToolId((getPlayer().getInventory().getItemInMainHand() != null) ? getPlayer().getInventory().getItemInMainHand().getType() : null); } public String getToolId(Material itemInHand) { @@ -169,17 +169,10 @@ public class Sniper { try { Player player = getPlayer(); final FawePlayer fp = FawePlayer.wrap(player); - TaskManager.IMP.taskNow(new Runnable() { - @Override - public void run() { - if (!fp.runAction(new Runnable() { - @Override - public void run() { - snipeOnCurrentThread(fp, action, itemInHand, clickedBlock, clickedFace, sniperTool, toolId); - } - }, false, true)) { - BBC.WORLDEDIT_COMMAND_LIMIT.send(fp); - } + TaskManager.IMP.taskNow(() -> { + if (!fp.runAction( + () -> snipeOnCurrentThread(fp, action, itemInHand, clickedBlock, clickedFace, sniperTool, toolId), false, true)) { + BBC.WORLDEDIT_COMMAND_LIMIT.send(fp); } }, Fawe.isMainThread()); return true; @@ -660,9 +653,7 @@ public class Sniper { private IBrush instantiateBrush(Class brush) { try { return brush.newInstance(); - } catch (InstantiationException e) { - return null; - } catch (IllegalAccessException e) { + } catch (InstantiationException | IllegalAccessException e) { return null; } } @@ -671,4 +662,4 @@ public class Sniper { public static Class inject() { return Sniper.class; } -} \ No newline at end of file +} diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/Undo.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/Undo.java index 31c17960e..a999f7bf4 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/Undo.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/Undo.java @@ -26,9 +26,10 @@ package com.thevoxelbox.voxelsniper; import org.bukkit.World; import org.bukkit.block.Block; +import org.bukkit.block.BlockState; /** - * Holds {@link org.bukkit.block.BlockState}s that can be later on used to reset those block + * Holds {@link BlockState}s that can be later on used to reset those block * locations back to the recorded states. */ public class Undo { @@ -67,4 +68,4 @@ public class Undo { public void undo() { } -} \ No newline at end of file +} diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/VoxelSniper.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/VoxelSniper.java index f86410a6f..715d774fa 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/VoxelSniper.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/VoxelSniper.java @@ -169,6 +169,7 @@ public class VoxelSniper extends JavaPlugin brushManager.registerSniperBrush(EntityRemovalBrush.class, "er", "entityremoval"); brushManager.registerSniperBrush(EraserBrush.class, "erase", "eraser"); brushManager.registerSniperBrush(ErodeBrush.class, "e", "erode"); + brushManager.registerSniperBrush(ErodeBlendBrush.class, "eb", "erodeblend", "erodeblendball"); brushManager.registerSniperBrush(ExtrudeBrush.class, "ex", "extrude"); brushManager.registerSniperBrush(FillDownBrush.class, "fd", "filldown"); brushManager.registerSniperBrush(FlatOceanBrush.class, "fo", "flatocean"); @@ -218,6 +219,7 @@ public class VoxelSniper extends JavaPlugin brushManager.registerSniperBrush(VoxelDiscBrush.class, "vd", "voxeldisc"); brushManager.registerSniperBrush(VoxelDiscFaceBrush.class, "vdf", "voxeldiscface"); brushManager.registerSniperBrush(WarpBrush.class, "w", "warp"); + brushManager.registerSniperBrush(WallSider.class, "wallsider", "sider"); } public void setupCommand(final String label, final FaweCommand cmd) { diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/VoxelSniperListener.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/VoxelSniperListener.java index 0c7d26c4c..ffa8189d5 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/VoxelSniperListener.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/VoxelSniperListener.java @@ -26,7 +26,7 @@ public class VoxelSniperListener implements Listener private static final String SNIPER_PERMISSION = "voxelsniper.sniper"; private final VoxelSniper plugin; - private Map commands = new HashMap(); + private Map commands = new HashMap<>(); /** * @param plugin @@ -79,35 +79,32 @@ public class VoxelSniperListener implements Listener } FawePlayer fp = FawePlayer.wrap(player); - if (!fp.runAction(new Runnable() { - @Override - public void run() { - ExceptionConverter exceptionConverter = CommandManager.getInstance().getExceptionConverter(); + if (!fp.runAction(() -> { + ExceptionConverter exceptionConverter = CommandManager.getInstance().getExceptionConverter(); + try { try { - try { - found.onCommand(player, split); - return; - } catch (Throwable t) { - Throwable next = t; + found.onCommand(player, split); + return; + } catch (Throwable t) { + Throwable next = t; + exceptionConverter.convert(next); + while (next.getCause() != null) { + next = next.getCause(); exceptionConverter.convert(next); - while (next.getCause() != null) { - next = next.getCause(); - exceptionConverter.convert(next); - } - throw next; } - } catch (CommandException e) { - String message = e.getMessage(); - if (message != null) { - fp.sendMessage(e.getMessage()); - return; - } - e.printStackTrace(); - } catch (Throwable e) { - e.printStackTrace(); + throw next; } - fp.sendMessage("An unknown FAWE error has occurred! Please see console."); + } catch (CommandException e) { + String message = e.getMessage(); + if (message != null) { + fp.sendMessage(e.getMessage()); + return; + } + e.printStackTrace(); + } catch (Throwable e) { + e.printStackTrace(); } + fp.sendMessage("An unknown FAWE error has occurred! Please see console."); }, false, true)) { BBC.WORLDEDIT_COMMAND_LIMIT.send(fp); } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BiomeBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BiomeBrush.java index 788574e01..2e2ea9e73 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BiomeBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BiomeBrush.java @@ -82,17 +82,18 @@ public class BiomeBrush extends Brush if (args[1].equalsIgnoreCase("info")) { v.sendMessage(ChatColor.GOLD + "Biome Brush Parameters:"); - String availableBiomes = ""; + StringBuilder availableBiomes = new StringBuilder(); for (final Biome biome : Biome.values()) { - if (availableBiomes.isEmpty()) + if (availableBiomes.length() == 0) { - availableBiomes = ChatColor.DARK_GREEN + biome.name(); + availableBiomes = new StringBuilder(ChatColor.DARK_GREEN + biome.name()); continue; } - availableBiomes += ChatColor.RED + ", " + ChatColor.DARK_GREEN + biome.name(); + availableBiomes.append(ChatColor.RED + ", " + ChatColor.DARK_GREEN) + .append(biome.name()); } v.sendMessage(ChatColor.DARK_BLUE + "Available biomes: " + availableBiomes); @@ -100,15 +101,15 @@ public class BiomeBrush extends Brush else { // allows biome names with spaces in their name - String biomeName = args[1]; + StringBuilder biomeName = new StringBuilder(args[1]); for (int i = 2; i < args.length; i++) { - biomeName += " " + args[i]; + biomeName.append(" ").append(args[i]); } for (final Biome biome : Biome.values()) { - if (biome.name().equalsIgnoreCase(biomeName)) + if (biome.name().equalsIgnoreCase(biomeName.toString())) { this.selectedBiome = biome; break; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendBallBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendBallBrush.java index 1da2ec01d..34da2c707 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendBallBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendBallBrush.java @@ -1,5 +1,6 @@ package com.thevoxelbox.voxelsniper.brush; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.thevoxelbox.voxelsniper.SnipeData; import com.thevoxelbox.voxelsniper.Undo; @@ -48,10 +49,8 @@ public class BlendBallBrush extends BlendBrushBase { for (int y = 0; y <= brushSizeDoubled; y++) { - for (int z = 0; z <= brushSizeDoubled; z++) - { - newMaterials[x][y][z] = oldMaterials[x + 1][y + 1][z + 1]; - } + System.arraycopy(oldMaterials[x + 1][y + 1], 1, newMaterials[x][y], 0, + brushSizeDoubled + 1); } } @@ -82,7 +81,7 @@ public class BlendBallBrush extends BlendBrushBase } // Find most common neighboring material. - for (BlockTypes type : BlockTypes.values) + for (BlockType type : BlockTypes.values) { int i = type.getInternalId(); if (materialFrequency[i] > modeMatCount && !(this.excludeAir && type.getMaterial().isAir()) && !(this.excludeWater && (type == BlockTypes.WATER))) @@ -94,7 +93,7 @@ public class BlendBallBrush extends BlendBrushBase // Make sure there'world not a tie for most common for (int i = 0; i < modeMatId; i++) { - BlockTypes type = BlockTypes.get(i); + BlockType type = BlockTypes.get(i); if (materialFrequency[i] == modeMatCount && !(this.excludeAir && type.getMaterial().isAir()) && !(this.excludeWater && (type == BlockTypes.WATER))) { tiecheck = false; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendDiscBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendDiscBrush.java index 75130f9e9..8e2434f61 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendDiscBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendDiscBrush.java @@ -1,5 +1,6 @@ package com.thevoxelbox.voxelsniper.brush; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.thevoxelbox.voxelsniper.SnipeData; import com.thevoxelbox.voxelsniper.Undo; @@ -41,10 +42,7 @@ public class BlendDiscBrush extends BlendBrushBase // Log current materials into newmats for (int x = 0; x <= brushSizeDoubled; x++) { - for (int z = 0; z <= brushSizeDoubled; z++) - { - newMaterials[x][z] = oldMaterials[x + 1][z + 1]; - } + System.arraycopy(oldMaterials[x + 1], 1, newMaterials[x], 0, brushSizeDoubled + 1); } // Blend materials @@ -69,7 +67,7 @@ public class BlendDiscBrush extends BlendBrushBase } // Find most common neighboring material. - for (BlockTypes type : BlockTypes.values) + for (BlockType type : BlockTypes.values) { int i = type.getInternalId(); if (materialFrequency[i] > modeMatCount && !(this.excludeAir && type.getMaterial().isAir()) && !(this.excludeWater && (type == BlockTypes.WATER))) @@ -81,7 +79,7 @@ public class BlendDiscBrush extends BlendBrushBase // Make sure there'world not a tie for most common for (int i = 0; i < modeMatId; i++) { - BlockTypes type = BlockTypes.get(i); + BlockType type = BlockTypes.get(i); if (materialFrequency[i] == modeMatCount && !(this.excludeAir && type.getMaterial().isAir()) && !(this.excludeWater && (type == BlockTypes.WATER))) { tiecheck = false; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendVoxelBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendVoxelBrush.java index 30cf38268..088797779 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendVoxelBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendVoxelBrush.java @@ -1,5 +1,6 @@ package com.thevoxelbox.voxelsniper.brush; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.thevoxelbox.voxelsniper.SnipeData; import com.thevoxelbox.voxelsniper.Undo; @@ -48,10 +49,8 @@ public class BlendVoxelBrush extends BlendBrushBase { for (int y = 0; y <= brushSizeDoubled; y++) { - for (int z = 0; z <= brushSizeDoubled; z++) - { - newMaterials[x][y][z] = oldMaterials[x + 1][y + 1][z + 1]; - } + System.arraycopy(oldMaterials[x + 1][y + 1], 1, newMaterials[x][y], 0, + brushSizeDoubled + 1); } } @@ -82,7 +81,7 @@ public class BlendVoxelBrush extends BlendBrushBase } // Find most common neighboring material. - for (BlockTypes type : BlockTypes.values) + for (BlockType type : BlockTypes.values) { int i = type.getInternalId(); if (materialFrequency[i] > modeMatCount && !(this.excludeAir && type.getMaterial().isAir()) && !(this.excludeWater && (type == BlockTypes.WATER))) @@ -94,7 +93,7 @@ public class BlendVoxelBrush extends BlendBrushBase // Make sure there'world not a tie for most common for (int i = 0; i < modeMatId; i++) { - BlockTypes type = BlockTypes.get(i); + BlockType type = BlockTypes.get(i); if (materialFrequency[i] == modeMatCount && !(this.excludeAir && type.getMaterial().isAir()) && !(this.excludeWater && (type == BlockTypes.WATER))) { tiecheck = false; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendVoxelDiscBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendVoxelDiscBrush.java index 56a670f0b..089710e05 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendVoxelDiscBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlendVoxelDiscBrush.java @@ -1,5 +1,6 @@ package com.thevoxelbox.voxelsniper.brush; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.thevoxelbox.voxelsniper.SnipeData; import com.thevoxelbox.voxelsniper.Undo; @@ -41,10 +42,7 @@ public class BlendVoxelDiscBrush extends BlendBrushBase // Log current materials into newmats for (int x = 0; x <= brushSizeDoubled; x++) { - for (int z = 0; z <= brushSizeDoubled; z++) - { - newMaterials[x][z] = oldMaterials[x + 1][z + 1]; - } + System.arraycopy(oldMaterials[x + 1], 1, newMaterials[x], 0, brushSizeDoubled + 1); } // Blend materials @@ -69,7 +67,7 @@ public class BlendVoxelDiscBrush extends BlendBrushBase } // Find most common neighboring material. - for (BlockTypes type : BlockTypes.values) + for (BlockType type : BlockTypes.values) { int i = type.getInternalId(); if (materialFrequency[i] > modeMatCount && !(this.excludeAir && type.getMaterial().isAir()) && !(this.excludeWater && (type == BlockTypes.WATER))) @@ -81,7 +79,7 @@ public class BlendVoxelDiscBrush extends BlendBrushBase // Make sure there'world not a tie for most common for (int i = 0; i < modeMatId; i++) { - BlockTypes type = BlockTypes.get(i); + BlockType type = BlockTypes.get(i); if (materialFrequency[i] == modeMatCount && !(this.excludeAir && type.getMaterial().isAir()) && !(this.excludeWater && (type == BlockTypes.WATER))) { tiecheck = false; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlobBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlobBrush.java index cf51dca5e..0279d2f9e 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlobBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlobBrush.java @@ -120,10 +120,7 @@ public class BlobBrush extends PerformBrush { for (int y = brushSizeDoubled; y >= 0; y--) { - for (int z = brushSizeDoubled; z >= 0; z--) - { - splat[x][y][z] = tempSplat[x][y][z]; - } + System.arraycopy(tempSplat[x][y], 0, splat[x][y], 0, brushSizeDoubled + 1); } } } @@ -218,10 +215,7 @@ public class BlobBrush extends PerformBrush { for (int y = brushSizeDoubled; y >= 0; y--) { - for (int z = brushSizeDoubled; z >= 0; z--) - { - splat[x][y][z] = tempSplat[x][y][z]; - } + System.arraycopy(tempSplat[x][y], 0, splat[x][y], 0, brushSizeDoubled + 1); } } } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlockResetBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlockResetBrush.java index 6738b696a..180939755 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlockResetBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlockResetBrush.java @@ -13,7 +13,7 @@ import org.bukkit.block.Block; */ public class BlockResetBrush extends Brush { - private static final ArrayList DENIED_UPDATES = new ArrayList(); + private static final ArrayList DENIED_UPDATES = new ArrayList<>(); static { diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlockResetSurfaceBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlockResetSurfaceBrush.java index de93fa6eb..332699ce2 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlockResetSurfaceBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/BlockResetSurfaceBrush.java @@ -4,8 +4,8 @@ import java.util.ArrayList; import com.boydti.fawe.bukkit.wrapper.AsyncBlock; import com.boydti.fawe.bukkit.wrapper.AsyncWorld; -import com.sk89q.worldedit.blocks.BlockMaterial; import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.registry.BlockMaterial; import com.thevoxelbox.voxelsniper.Message; import com.thevoxelbox.voxelsniper.SnipeData; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/DomeBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/DomeBrush.java index 19e1322a8..4983bf52a 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/DomeBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/DomeBrush.java @@ -54,7 +54,7 @@ public class DomeBrush extends Brush final int absoluteHeight = Math.abs(v.getVoxelHeight()); final boolean negative = v.getVoxelHeight() < 0; - final Set changeablePositions = new HashSet(); + final Set changeablePositions = new HashSet<>(); final Undo undo = new Undo(); diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/EntityRemovalBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/EntityRemovalBrush.java index 0d6871621..727a6a58c 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/EntityRemovalBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/EntityRemovalBrush.java @@ -16,7 +16,7 @@ import java.util.regex.PatternSyntaxException; */ public class EntityRemovalBrush extends Brush { - private final List exemptions = new ArrayList(3); + private final List exemptions = new ArrayList<>(3); /** * @@ -82,7 +82,7 @@ public class EntityRemovalBrush extends Brush private boolean isClassInExemptionList(Class entityClass) throws PatternSyntaxException { // Create a list of superclasses and interfaces implemented by the current entity type - final List entityClassHierarchy = new ArrayList(); + final List entityClassHierarchy = new ArrayList<>(); Class currentClass = entityClass; while (currentClass != null && !currentClass.equals(Object.class)) diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ErodeBlendBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ErodeBlendBrush.java new file mode 100644 index 000000000..3f81e05f4 --- /dev/null +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ErodeBlendBrush.java @@ -0,0 +1,52 @@ +package com.thevoxelbox.voxelsniper.brush; + +import com.thevoxelbox.voxelsniper.Message; +import com.thevoxelbox.voxelsniper.SnipeData; + +public class ErodeBlendBrush extends Brush{ + + private BlendBallBrush blendBall; + private ErodeBrush erode; + + public ErodeBlendBrush() { + this.blendBall = new BlendBallBrush(); + this.erode = new ErodeBrush(); + this.setName("Erode BlendBall"); + } + + @Override + protected final void arrow(final SnipeData v) { + this.blendBall.excludeAir = false; + this.blendBall.setTargetBlock(this.getTargetBlock()); + this.blendBall.arrow(v); + this.erode.setTargetBlock(this.getTargetBlock()); + this.erode.arrow(v); + } + + @Override + protected final void powder(final SnipeData v) { + this.blendBall.excludeAir = false; + this.blendBall.setTargetBlock(this.getTargetBlock()); + this.blendBall.arrow(v); + this.erode.setTargetBlock(this.getTargetBlock()); + this.erode.powder(v); + } + + @Override + public final void parameters(final String[] par, final SnipeData v) { + this.blendBall.parameters(par, v); + this.erode.parameters(par, v); + } + + @Override + public String getPermissionNode() { + return "voxelsniper.brush.erodeblend"; + } + + @Override + public void info(Message vm) { + this.erode.info(vm); + this.blendBall.info(vm); + } + +} diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ErodeBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ErodeBrush.java index 0f678c88b..6d2b5e12e 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ErodeBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ErodeBrush.java @@ -133,7 +133,7 @@ public class ErodeBrush extends Brush int count = 0; - final Map blockCount = new HashMap(); + final Map blockCount = new HashMap<>(); for (final Vector vector : ErodeBrush.FACES_TO_CHECK) { @@ -363,8 +363,8 @@ public class ErodeBrush extends Brush public BlockChangeTracker(final AsyncWorld world) { - this.blockChanges = new HashMap>(); - this.flatChanges = new HashMap(); + this.blockChanges = new HashMap<>(); + this.flatChanges = new HashMap<>(); this.world = world; } @@ -400,7 +400,7 @@ public class ErodeBrush extends Brush { if (!this.blockChanges.containsKey(iteration)) { - this.blockChanges.put(iteration, new HashMap()); + this.blockChanges.put(iteration, new HashMap<>()); } this.blockChanges.get(iteration).put(position, changedBlock); diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/GenerateTreeBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/GenerateTreeBrush.java index 4a9067442..e38d8e277 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/GenerateTreeBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/GenerateTreeBrush.java @@ -24,7 +24,7 @@ public class GenerateTreeBrush extends Brush { // Tree Variables. private Random randGenerator = new Random(); - private ArrayList branchBlocks = new ArrayList(); + private ArrayList branchBlocks = new ArrayList<>(); private Undo undo; // If these default values are edited. Remember to change default values in the default preset. private Material leafType = Material.OAK_LEAVES; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/HeatRayBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/HeatRayBrush.java index 1ac689d24..b50611818 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/HeatRayBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/HeatRayBrush.java @@ -44,7 +44,7 @@ public class HeatRayBrush extends Brush private static final double REQUIRED_FIRE_DENSITY = -0.25; private static final double REQUIRED_AIR_DENSITY = 0; - private static final ArrayList FLAMABLE_BLOCKS = new ArrayList(); + private static final ArrayList FLAMABLE_BLOCKS = new ArrayList<>(); private int octaves = 5; private double frequency = 1; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/JockeyBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/JockeyBrush.java index a4477dd1b..c1e579771 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/JockeyBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/JockeyBrush.java @@ -83,11 +83,11 @@ public class JockeyBrush extends Brush { if (jockeyType == JockeyType.INVERSE_PLAYER_ONLY || jockeyType == JockeyType.INVERSE_ALL_ENTITIES) { - player.setPassenger(closest); + player.addPassenger(closest); } else { - closest.setPassenger(player); + closest.addPassenger(player); jockeyedEntity = closest; } v.sendMessage(ChatColor.GREEN + "You are now saddles on entity: " + closest.getEntityId()); @@ -113,7 +113,7 @@ public class JockeyBrush extends Brush { if (jockeyType == JockeyType.STACK_ALL_ENTITIES) { - lastEntity.setPassenger(entity); + lastEntity.addPassenger(entity); lastEntity = entity; stackHeight++; } @@ -121,7 +121,7 @@ public class JockeyBrush extends Brush { if (entity instanceof Player) { - lastEntity.setPassenger(entity); + lastEntity.addPassenger(entity); lastEntity = entity; stackHeight++; } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/MoveBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/MoveBrush.java index b59d0ece1..9329fbf5f 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/MoveBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/MoveBrush.java @@ -58,7 +58,7 @@ public class MoveBrush extends Brush final AsyncWorld world = selection.getBlockStates().get(0).getWorld(); final Undo undo = new Undo(); - final HashSet undoSet = new HashSet(); + final HashSet undoSet = new HashSet<>(); final Selection newSelection = new Selection(); final Location movedLocation1 = selection.getLocation1(); @@ -214,7 +214,7 @@ public class MoveBrush extends Brush /** * Calculated BlockStates of the selection. */ - private final ArrayList blockStates = new ArrayList(); + private final ArrayList blockStates = new ArrayList<>(); /** * */ diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/OverlayBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/OverlayBrush.java index fa599b04d..e8a3b9ea7 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/OverlayBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/OverlayBrush.java @@ -1,7 +1,9 @@ package com.thevoxelbox.voxelsniper.brush; -import com.sk89q.worldedit.blocks.BlockMaterial; +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.world.registry.BlockMaterial; import com.thevoxelbox.voxelsniper.Message; import com.thevoxelbox.voxelsniper.SnipeData; import com.thevoxelbox.voxelsniper.brush.perform.PerformBrush; @@ -13,8 +15,7 @@ import org.bukkit.Material; * * @author Gavjenks */ -public class OverlayBrush extends PerformBrush -{ +public class OverlayBrush extends PerformBrush { private static final int DEFAULT_DEPTH = 3; private int depth = DEFAULT_DEPTH; private boolean allBlocks = false; @@ -22,40 +23,38 @@ public class OverlayBrush extends PerformBrush /** * */ - public OverlayBrush() - { + public OverlayBrush() { this.setName("Overlay (Topsoil Filling)"); } - private void overlay(final SnipeData v) - { + private void overlay(final SnipeData v) { final int brushSize = v.getBrushSize(); final double brushSizeSquared = Math.pow(brushSize + 0.5, 2); - for (int z = brushSize; z >= -brushSize; z--) - { - for (int x = brushSize; x >= -brushSize; x--) - { + for (int z = brushSize; z >= -brushSize; z--) { + for (int x = brushSize; x >= -brushSize; x--) { // check if column is valid // column is valid if it has no solid block right above the clicked layer - final int materialId = this.getBlockIdAt(this.getTargetBlock().getX() + x, this.getTargetBlock().getY() + 1, this.getTargetBlock().getZ() + z); - if (isIgnoredBlock(materialId)) - { - if ((Math.pow(x, 2) + Math.pow(z, 2)) <= brushSizeSquared) - { - for (int y = this.getTargetBlock().getY(); y > 0; y--) - { + final int materialId = this.getBlockIdAt(this.getTargetBlock().getX() + x, + this.getTargetBlock().getY() + 1, this.getTargetBlock().getZ() + z); + if (isIgnoredBlock(materialId)) { + if ((Math.pow(x, 2) + Math.pow(z, 2)) <= brushSizeSquared) { + for (int y = this.getTargetBlock().getY(); y > 0; y--) { // check for surface - final int layerBlockId = this.getBlockIdAt(this.getTargetBlock().getX() + x, y, this.getTargetBlock().getZ() + z); - if (!isIgnoredBlock(layerBlockId)) - { - for (int currentDepth = y; y - currentDepth < depth; currentDepth--) - { - final int currentBlockId = this.getBlockIdAt(this.getTargetBlock().getX() + x, currentDepth, this.getTargetBlock().getZ() + z); - if (isOverrideableMaterial(currentBlockId)) - { - this.current.perform(this.clampY(this.getTargetBlock().getX() + x, currentDepth, this.getTargetBlock().getZ() + z)); + final int layerBlockId = + this.getBlockIdAt(this.getTargetBlock().getX() + x, y, + this.getTargetBlock().getZ() + z); + if (!isIgnoredBlock(layerBlockId)) { + for (int currentDepth = y; + y - currentDepth < depth; currentDepth--) { + final int currentBlockId = + this.getBlockIdAt(this.getTargetBlock().getX() + x, + currentDepth, this.getTargetBlock().getZ() + z); + if (isOverrideableMaterial(currentBlockId)) { + this.current.perform( + this.clampY(this.getTargetBlock().getX() + x, + currentDepth, this.getTargetBlock().getZ() + z)); } } break; @@ -69,82 +68,75 @@ public class OverlayBrush extends PerformBrush v.owner().storeUndo(this.current.getUndo()); } - @SuppressWarnings("deprecation") - private boolean isIgnoredBlock(int materialId) - { - BlockTypes type = BlockTypes.get(materialId); - switch (type) { - case WATER: - case LAVA: - case CACTUS: - return true; + @SuppressWarnings("deprecation") private boolean isIgnoredBlock(int materialId) { + BlockType type = BlockTypes.get(materialId); + String s = type.getResource().toUpperCase(); + if (type == BlockTypes.WATER || type == BlockTypes.LAVA || type == BlockTypes.CACTUS) { + return true; } BlockMaterial mat = type.getMaterial(); return mat.isTranslucent(); } - @SuppressWarnings("deprecation") - private boolean isOverrideableMaterial(int materialId) - { + @SuppressWarnings("deprecation") private boolean isOverrideableMaterial(int materialId) { BlockMaterial mat = BlockTypes.get(materialId).getMaterial(); - if (allBlocks && !(mat.isAir())) - { + if (allBlocks && !(mat.isAir())) { return true; } - if (!mat.isFragileWhenPushed() && mat.isFullCube()) { - return true; - } - return false; + return !mat.isFragileWhenPushed() && mat.isFullCube(); } - private void overlayTwo(final SnipeData v) - { + private void overlayTwo(final SnipeData v) { final int brushSize = v.getBrushSize(); final double brushSizeSquared = Math.pow(brushSize + 0.5, 2); final int[][] memory = new int[brushSize * 2 + 1][brushSize * 2 + 1]; - for (int z = brushSize; z >= -brushSize; z--) - { - for (int x = brushSize; x >= -brushSize; x--) - { + for (int z = brushSize; z >= -brushSize; z--) { + for (int x = brushSize; x >= -brushSize; x--) { boolean surfaceFound = false; - for (int y = this.getTargetBlock().getY(); y > 0 && !surfaceFound; y--) - { // start scanning from the height you clicked at - if (memory[x + brushSize][z + brushSize] != 1) - { // if haven't already found the surface in this column - if ((Math.pow(x, 2) + Math.pow(z, 2)) <= brushSizeSquared) - { // if inside of the column... - if (!this.getBlockAt(this.getTargetBlock().getX() + x, y - 1, this.getTargetBlock().getZ() + z).isEmpty()) - { // if not a floating block (like one of Notch'world pools) - if (this.getBlockAt(this.getTargetBlock().getX() + x, y + 1, this.getTargetBlock().getZ() + z).isEmpty()) - { // must start at surface... this prevents it filling stuff in if + for (int y = this.getTargetBlock().getY(); + y > 0 && !surfaceFound; y--) { // start scanning from the height you clicked at + if (memory[x + brushSize][z + brushSize] + != 1) { // if haven't already found the surface in this column + if ((Math.pow(x, 2) + Math.pow(z, 2)) + <= brushSizeSquared) { // if inside of the column... + if (!this.getBlockAt(this.getTargetBlock().getX() + x, y - 1, + this.getTargetBlock().getZ() + z) + .isEmpty()) { // if not a floating block (like one of Notch'world pools) + if (this.getBlockAt(this.getTargetBlock().getX() + x, y + 1, + this.getTargetBlock().getZ() + z) + .isEmpty()) { // must start at surface... this prevents it filling stuff in if // you click in a wall and it starts out below surface. - if (!this.allBlocks) - { // if the override parameter has not been activated, go to the switch that filters out manmade stuff. + if (!this.allBlocks) { // if the override parameter has not been activated, go to the switch that filters out manmade stuff. - BlockTypes type = BlockTypes.get(this.getBlockIdAt(this.getTargetBlock().getX() + x, y, this.getTargetBlock().getZ() + z)); + BlockType type = BukkitAdapter.asBlockType((this + .getBlockType(this.getTargetBlock().getX() + x, y, + this.getTargetBlock().getZ() + z))); BlockMaterial mat = type.getMaterial(); - if (mat.isSolid() && mat.isFullCube() && !mat.hasContainer()) { + if (mat.isSolid() && mat.isFullCube() && !mat + .hasContainer()) { for (int d = 1; (d < this.depth + 1); d++) { - this.current.perform(this.clampY(this.getTargetBlock().getX() + x, y + d, this.getTargetBlock().getZ() + z)); // fills down as many layers as you specify + this.current.perform( + this.clampY(this.getTargetBlock().getX() + x, + y + d, this.getTargetBlock().getZ() + + z)); // fills down as many layers as you specify // in parameters - memory[x + brushSize][z + brushSize] = 1; // stop it from checking any other blocks in this vertical 1x1 column. + memory[x + brushSize][z + brushSize] = + 1; // stop it from checking any other blocks in this vertical 1x1 column. } surfaceFound = true; - continue; - } else { - continue; } - } - else - { - for (int d = 1; (d < this.depth + 1); d++) - { - this.current.perform(this.clampY(this.getTargetBlock().getX() + x, y + d, this.getTargetBlock().getZ() + z)); // fills down as many layers as you specify in + } else { + for (int d = 1; (d < this.depth + 1); d++) { + this.current.perform( + this.clampY(this.getTargetBlock().getX() + x, y + d, + this.getTargetBlock().getZ() + + z)); // fills down as many layers as you specify in // parameters - memory[x + brushSize][z + brushSize] = 1; // stop it from checking any other blocks in this vertical 1x1 column. + memory[x + brushSize][z + brushSize] = + 1; // stop it from checking any other blocks in this vertical 1x1 column. } surfaceFound = true; } @@ -160,74 +152,58 @@ public class OverlayBrush extends PerformBrush v.owner().storeUndo(this.current.getUndo()); } - @Override - protected final void arrow(final SnipeData v) - { + @Override protected final void arrow(final SnipeData v) { this.overlay(v); } - @Override - protected final void powder(final SnipeData v) - { + @Override protected final void powder(final SnipeData v) { this.overlayTwo(v); } - @Override - public final void info(final Message vm) - { + @Override public final void info(final Message vm) { vm.brushName(this.getName()); vm.size(); } - @Override - public final void parameters(final String[] par, final SnipeData v) - { - for (int i = 1; i < par.length; i++) - { + @Override public final void parameters(final String[] par, final SnipeData v) { + for (int i = 1; i < par.length; i++) { final String parameter = par[i]; - if (parameter.equalsIgnoreCase("info")) - { + if (parameter.equalsIgnoreCase("info")) { v.sendMessage(ChatColor.GOLD + "Overlay brush parameters:"); - v.sendMessage(ChatColor.AQUA + "d[number] (ex: d3) How many blocks deep you want to replace from the surface."); - v.sendMessage(ChatColor.BLUE + "all (ex: /b over all) Sets the brush to overlay over ALL materials, not just natural surface ones (will no longer ignore trees and buildings). The parameter /some will set it back to default."); + v.sendMessage(ChatColor.AQUA + + "d[number] (ex: d3) How many blocks deep you want to replace from the surface."); + v.sendMessage(ChatColor.BLUE + + "all (ex: /b over all) Sets the brush to overlay over ALL materials, not just natural surface ones (will no longer ignore trees and buildings). The parameter /some will set it back to default."); return; } - if (parameter.startsWith("d")) - { + if (parameter.startsWith("d")) { try { this.depth = Integer.parseInt(parameter.replace("d", "")); - if (this.depth < 1) - { + if (this.depth < 1) { this.depth = 1; } v.sendMessage(ChatColor.AQUA + "Depth set to " + this.depth); - } catch (NumberFormatException e) { + } catch (NumberFormatException e) { v.sendMessage(ChatColor.RED + "Depth isn't a number."); } - } - else if (parameter.startsWith("all")) - { + } else if (parameter.startsWith("all")) { this.allBlocks = true; v.sendMessage(ChatColor.BLUE + "Will overlay over any block." + this.depth); - } - else if (parameter.startsWith("some")) - { + } else if (parameter.startsWith("some")) { this.allBlocks = false; - v.sendMessage(ChatColor.BLUE + "Will overlay only natural block types." + this.depth); - } - else - { - v.sendMessage(ChatColor.RED + "Invalid brush parameters! use the info parameter to display parameter info."); + v.sendMessage( + ChatColor.BLUE + "Will overlay only natural block types." + this.depth); + } else { + v.sendMessage(ChatColor.RED + + "Invalid brush parameters! use the info parameter to display parameter info."); } } } - @Override - public String getPermissionNode() - { + @Override public String getPermissionNode() { return "voxelsniper.brush.overlay"; } } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/PullBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/PullBrush.java index 7ec40bfe4..83c4a21bb 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/PullBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/PullBrush.java @@ -14,7 +14,7 @@ import java.util.HashSet; */ public class PullBrush extends Brush { - private final HashSet surface = new HashSet(); + private final HashSet surface = new HashSet<>(); private int vh; private double c1 = 1; private double c2 = 0; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot2DBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot2DBrush.java index 90733c6a7..b7b30c599 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot2DBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot2DBrush.java @@ -163,16 +163,11 @@ public class Rot2DBrush extends Brush { this.bSize = v.getBrushSize(); - switch (this.mode) - { - case 0: - this.getMatrix(); - this.rotate(v); - break; - - default: - v.sendMessage(ChatColor.RED + "Something went wrong."); - break; + if (this.mode == 0) { + this.getMatrix(); + this.rotate(v); + } else { + v.sendMessage(ChatColor.RED + "Something went wrong."); } } @@ -181,16 +176,11 @@ public class Rot2DBrush extends Brush { this.bSize = v.getBrushSize(); - switch (this.mode) - { - case 0: - this.getMatrix(); - this.rotate(v); - break; - - default: - v.sendMessage(ChatColor.RED + "Something went wrong."); - break; + if (this.mode == 0) { + this.getMatrix(); + this.rotate(v); + } else { + v.sendMessage(ChatColor.RED + "Something went wrong."); } } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot2DvertBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot2DvertBrush.java index f34c43486..c656682f0 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot2DvertBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot2DvertBrush.java @@ -164,16 +164,11 @@ public class Rot2DvertBrush extends Brush { this.bSize = v.getBrushSize(); - switch (this.mode) - { - case 0: - this.getMatrix(); - this.rotate(v); - break; - - default: - v.owner().getPlayer().sendMessage(ChatColor.RED + "Something went wrong."); - break; + if (this.mode == 0) { + this.getMatrix(); + this.rotate(v); + } else { + v.owner().getPlayer().sendMessage(ChatColor.RED + "Something went wrong."); } } @@ -182,16 +177,11 @@ public class Rot2DvertBrush extends Brush { this.bSize = v.getBrushSize(); - switch (this.mode) - { - case 0: - this.getMatrix(); - this.rotate(v); - break; - - default: - v.owner().getPlayer().sendMessage(ChatColor.RED + "Something went wrong."); - break; + if (this.mode == 0) { + this.getMatrix(); + this.rotate(v); + } else { + v.owner().getPlayer().sendMessage(ChatColor.RED + "Something went wrong."); } } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot3DBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot3DBrush.java index 1a9069cd1..79ddcbdf8 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot3DBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/Rot3DBrush.java @@ -248,16 +248,11 @@ public class Rot3DBrush extends Brush { this.bSize = v.getBrushSize(); - switch (this.mode) - { - case 0: - this.getMatrix(); - this.rotate(v); - break; - - default: - v.owner().getPlayer().sendMessage(ChatColor.RED + "Something went wrong."); - break; + if (this.mode == 0) { + this.getMatrix(); + this.rotate(v); + } else { + v.owner().getPlayer().sendMessage(ChatColor.RED + "Something went wrong."); } } @@ -266,16 +261,11 @@ public class Rot3DBrush extends Brush { this.bSize = v.getBrushSize(); - switch (this.mode) - { - case 0: - this.getMatrix(); - this.rotate(v); - break; - - default: - v.owner().getPlayer().sendMessage(ChatColor.RED + "Something went wrong."); - break; + if (this.mode == 0) { + this.getMatrix(); + this.rotate(v); + } else { + v.owner().getPlayer().sendMessage(ChatColor.RED + "Something went wrong."); } } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellBallBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellBallBrush.java index 7004b2d39..9c25020ba 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellBallBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellBallBrush.java @@ -50,10 +50,8 @@ public class ShellBallBrush extends Brush { for (int y = 0; y <= brushSizeDoubled; y++) { - for (int z = 0; z <= brushSizeDoubled; z++) - { - newMaterials[x][y][z] = oldMaterials[x + 1][y + 1][z + 1]; - } + System.arraycopy(oldMaterials[x + 1][y + 1], 1, newMaterials[x][y], 0, + brushSizeDoubled + 1); } } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellSetBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellSetBrush.java index 9e7fa81d8..b4037a11f 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellSetBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellSetBrush.java @@ -57,7 +57,8 @@ public class ShellSetBrush extends Brush } else { - final ArrayList blocks = new ArrayList(((Math.abs(highX - lowX) * Math.abs(highZ - lowZ) * Math.abs(highY - lowY)) / 2)); + final ArrayList blocks = new ArrayList<>( + ((Math.abs(highX - lowX) * Math.abs(highZ - lowZ) * Math.abs(highY - lowY)) / 2)); for (int y = lowY; y <= highY; y++) { for (int x = lowX; x <= highX; x++) diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellVoxelBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellVoxelBrush.java index ce394c276..2d528fb58 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellVoxelBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/ShellVoxelBrush.java @@ -49,10 +49,8 @@ public class ShellVoxelBrush extends Brush { for (int y = 0; y <= brushSizeSquared; y++) { - for (int z = 0; z <= brushSizeSquared; z++) - { - newMaterials[x][y][z] = oldMaterials[x + 1][y + 1][z + 1]; - } + System.arraycopy(oldMaterials[x + 1][y + 1], 1, newMaterials[x][y], 0, + brushSizeSquared + 1); } } int temp; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SnowConeBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SnowConeBrush.java index b68eccd8d..056184209 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SnowConeBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SnowConeBrush.java @@ -2,6 +2,7 @@ package com.thevoxelbox.voxelsniper.brush; import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.thevoxelbox.voxelsniper.Message; import com.thevoxelbox.voxelsniper.SnipeData; @@ -95,19 +96,15 @@ public class SnowConeBrush extends Brush if (snowData > snowconeData[x][z]) { - switch (BlockTypes.get(snowcone[x][z])) - { - case AIR: - case CAVE_AIR: - case VOID_AIR: - snowconeData[x][z] = snowData; - snowcone[x][z] = BlockTypes.SNOW.getInternalId(); - case SNOW_BLOCK: - snowconeData[x][z] = snowData; - break; - default: - break; + BlockType blockType = + BlockTypes.get(snowcone[x][z]); + if (blockType.getMaterial().isAir()) { + snowconeData[x][z] = snowData; + snowcone[x][z] = BlockTypes.SNOW.getInternalId(); + snowconeData[x][z] = snowData; + } else if (blockType == BlockTypes.SNOW_BLOCK) { + snowconeData[x][z] = snowData; } } else if (yOffset[x][z] > 0 && snowcone[x][z] == BlockTypes.SNOW.getInternalId()) @@ -152,22 +149,17 @@ public class SnowConeBrush extends Brush @Override protected final void powder(final SnipeData v) { - switch (getTargetBlock().getType()) - { - case SNOW: - this.addSnow(v, this.getTargetBlock()); - break; - default: - Block blockAbove = getTargetBlock().getRelative(BlockFace.UP); - if (blockAbove != null && BukkitAdapter.adapt(blockAbove.getType()).getMaterial().isAir()) - { - addSnow(v, blockAbove); - } - else - { - v.owner().getPlayer().sendMessage(ChatColor.RED + "Error: Center block neither snow nor air."); - } - break; + if (getTargetBlock().getType() == Material.SNOW) { + this.addSnow(v, this.getTargetBlock()); + } else { + Block blockAbove = getTargetBlock().getRelative(BlockFace.UP); + if (blockAbove != null && BukkitAdapter.adapt(blockAbove.getType()).getMaterial() + .isAir()) { + addSnow(v, blockAbove); + } else { + v.owner().getPlayer() + .sendMessage(ChatColor.RED + "Error: Center block neither snow nor air."); + } } } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SpiralStaircaseBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SpiralStaircaseBrush.java index b803ac117..c3b12d0b4 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SpiralStaircaseBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SpiralStaircaseBrush.java @@ -2,6 +2,7 @@ package com.thevoxelbox.voxelsniper.brush; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.extension.input.InputParseException; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.registry.LegacyMapper; import com.thevoxelbox.voxelsniper.Message; @@ -724,14 +725,12 @@ public class SpiralStaircaseBrush extends Brush // step/slab try { - BlockTypes type = BlockTypes.parse(par[i]); + BlockType type = BlockTypes.parse(par[i]); this.stairtype = par[i].toLowerCase().intern(); v.sendMessage(ChatColor.BLUE + "Staircase type: " + this.stairtype); return; } catch (InputParseException ignore) {} - switch (par[i].toLowerCase()) { - case "block": - + if ("block".equals(par[i].toLowerCase())) { } if (par[i].equalsIgnoreCase("block") || par[i].equalsIgnoreCase("step") || par[i].equalsIgnoreCase("woodstair") || par[i].equalsIgnoreCase("cobblestair")) { diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterBallBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterBallBrush.java index ec13e95c7..fb45a2b5f 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterBallBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterBallBrush.java @@ -130,10 +130,9 @@ public class SplatterBallBrush extends PerformBrush { for (int y = 2 * v.getBrushSize(); y >= 0; y--) { - for (int z = 2 * v.getBrushSize(); z >= 0; z--) - { - splat[x][y][z] = tempSplat[x][y][z]; - } + if (2 * v.getBrushSize() + 1 >= 0) + System.arraycopy(tempSplat[x][y], 0, splat[x][y], 0, + 2 * v.getBrushSize() + 1); } } } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterDiscBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterDiscBrush.java index c67d1e094..05d970753 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterDiscBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterDiscBrush.java @@ -115,10 +115,8 @@ public class SplatterDiscBrush extends PerformBrush // integrate tempsplat back into splat at end of iteration for (int x = 2 * v.getBrushSize(); x >= 0; x--) { - for (int y = 2 * v.getBrushSize(); y >= 0; y--) - { - splat[x][y] = tempSplat[x][y]; - } + if (2 * v.getBrushSize() + 1 >= 0) + System.arraycopy(tempSplat[x], 0, splat[x], 0, 2 * v.getBrushSize() + 1); } } this.growPercent = gref; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterOverlayBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterOverlayBrush.java index baea84b19..162f831d0 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterOverlayBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterOverlayBrush.java @@ -1,7 +1,8 @@ package com.thevoxelbox.voxelsniper.brush; -import com.sk89q.worldedit.blocks.BlockMaterial; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.world.registry.BlockMaterial; import com.thevoxelbox.voxelsniper.Message; import com.thevoxelbox.voxelsniper.SnipeData; import com.thevoxelbox.voxelsniper.brush.perform.PerformBrush; @@ -103,10 +104,8 @@ public class SplatterOverlayBrush extends PerformBrush // integrate tempsplat back into splat at end of iteration for (int x = 2 * v.getBrushSize(); x >= 0; x--) { - for (int y = 2 * v.getBrushSize(); y >= 0; y--) - { - splat[x][y] = tempSplat[x][y]; - } + if (2 * v.getBrushSize() + 1 >= 0) + System.arraycopy(tempSplat[x], 0, splat[x], 0, 2 * v.getBrushSize() + 1); } } this.growPercent = gref; @@ -135,7 +134,7 @@ public class SplatterOverlayBrush extends PerformBrush if (!this.allBlocks) { // if the override parameter has not been activated, go to the switch that filters out manmade stuff. - BlockTypes type = BlockTypes.get(this.getBlockIdAt(this.getTargetBlock().getX() + x, y, this.getTargetBlock().getZ() + z)); + BlockType type = BlockTypes.get(this.getBlockIdAt(this.getTargetBlock().getX() + x, y, this.getTargetBlock().getZ() + z)); BlockMaterial mat = type.getMaterial(); if (mat.isSolid() && mat.isFullCube() && !mat.hasContainer()) { final int depth = randomizeHeight ? generator.nextInt(this.depth) : this.depth; @@ -239,10 +238,8 @@ public class SplatterOverlayBrush extends PerformBrush // integrate tempsplat back into splat at end of iteration for (int x = 2 * v.getBrushSize(); x >= 0; x--) { - for (int y = 2 * v.getBrushSize(); y >= 0; y--) - { - splat[x][y] = tempsplat[x][y]; - } + if (2 * v.getBrushSize() + 1 >= 0) + System.arraycopy(tempsplat[x], 0, splat[x], 0, 2 * v.getBrushSize() + 1); } } this.growPercent = gref; @@ -268,7 +265,7 @@ public class SplatterOverlayBrush extends PerformBrush if (!this.allBlocks) { // if the override parameter has not been activated, go to the switch that filters out manmade stuff. - BlockTypes type = BlockTypes.get(this.getBlockIdAt(this.getTargetBlock().getX() + x, y, this.getTargetBlock().getZ() + z)); + BlockType type = BlockTypes.get(this.getBlockIdAt(this.getTargetBlock().getX() + x, y, this.getTargetBlock().getZ() + z)); BlockMaterial mat = type.getMaterial(); if (mat.isSolid() && mat.isFullCube() && !mat.hasContainer()) { diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterVoxelBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterVoxelBrush.java index cfa39e759..805ab96cd 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterVoxelBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterVoxelBrush.java @@ -130,10 +130,9 @@ public class SplatterVoxelBrush extends PerformBrush { for (int y = 2 * v.getBrushSize(); y >= 0; y--) { - for (int z = 2 * v.getBrushSize(); z >= 0; z--) - { - splat[x][y][z] = tempSplat[x][y][z]; - } + if (2 * v.getBrushSize() + 1 >= 0) + System.arraycopy(tempSplat[x][y], 0, splat[x][y], 0, + 2 * v.getBrushSize() + 1); } } } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterVoxelDiscBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterVoxelDiscBrush.java index aea30c080..920a8be7d 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterVoxelDiscBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplatterVoxelDiscBrush.java @@ -111,10 +111,8 @@ public class SplatterVoxelDiscBrush extends PerformBrush // integrate tempsplat back into splat at end of iteration for (int x = 2 * v.getBrushSize(); x >= 0; x--) { - for (int y = 2 * v.getBrushSize(); y >= 0; y--) - { - splat[x][y] = tempSplat[x][y]; - } + if (2 * v.getBrushSize() + 1 >= 0) + System.arraycopy(tempSplat[x], 0, splat[x], 0, 2 * v.getBrushSize() + 1); } } this.growPercent = gref; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplineBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplineBrush.java index 707a8c7ab..b2a0bdb47 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplineBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/SplineBrush.java @@ -16,9 +16,9 @@ import java.util.ArrayList; */ public class SplineBrush extends PerformBrush { - private final ArrayList endPts = new ArrayList(); - private final ArrayList ctrlPts = new ArrayList(); - protected ArrayList spline = new ArrayList(); + private final ArrayList endPts = new ArrayList<>(); + private final ArrayList ctrlPts = new ArrayList<>(); + protected ArrayList spline = new ArrayList<>(); protected boolean set; protected boolean ctrl; protected String[] sparams = {"ss", "sc", "clear"}; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/StampBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/StampBrush.java index 43b884c28..c19e0f4e1 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/StampBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/StampBrush.java @@ -52,10 +52,10 @@ public class StampBrush extends Brush NO_AIR, FILL, DEFAULT } - protected HashSet clone = new HashSet(); - protected HashSet fall = new HashSet(); - protected HashSet drop = new HashSet(); - protected HashSet solid = new HashSet(); + protected HashSet clone = new HashSet<>(); + protected HashSet fall = new HashSet<>(); + protected HashSet drop = new HashSet<>(); + protected HashSet solid = new HashSet<>(); protected Undo undo; protected boolean sorted = false; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/StencilListBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/StencilListBrush.java index a90f80569..b96a78a21 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/StencilListBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/StencilListBrush.java @@ -26,7 +26,7 @@ public class StencilListBrush extends Brush private short zRef; private short yRef; private byte pasteParam = 0; - private HashMap stencilList = new HashMap(); + private HashMap stencilList = new HashMap<>(); /** * diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/UnderlayBrush.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/UnderlayBrush.java index 38e8ea2c3..28a68b65c 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/UnderlayBrush.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/UnderlayBrush.java @@ -1,7 +1,7 @@ package com.thevoxelbox.voxelsniper.brush; -import com.sk89q.worldedit.blocks.BlockMaterial; import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.world.registry.BlockMaterial; import com.thevoxelbox.voxelsniper.Message; import com.thevoxelbox.voxelsniper.SnipeData; import com.thevoxelbox.voxelsniper.brush.perform.PerformBrush; diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/WallSider.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/WallSider.java new file mode 100644 index 000000000..f1b794f4b --- /dev/null +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/WallSider.java @@ -0,0 +1,139 @@ +package com.thevoxelbox.voxelsniper.brush; + +import org.bukkit.ChatColor; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.util.Vector; + +import com.boydti.fawe.bukkit.wrapper.AsyncBlock; +import com.thevoxelbox.voxelsniper.Message; +import com.thevoxelbox.voxelsniper.SnipeData; + +public class WallSider extends Brush{ + + private static String[] facings = new String[] { "north", "east", "south", "west", "relative to player" }; + private short c; + private short d; + private double e; + private boolean f; + private boolean g; + private boolean h; + + public WallSider() { + this.c = 4; + this.d = 1; + this.e = 0.0; + this.setName("WallSider"); + } + + private void a(final SnipeData snipeData, final Block block, final boolean b) { + final double n = (snipeData.getBrushSize() + this.e) * (snipeData.getBrushSize() + this.e); + final Vector vector; + final Vector clone = (vector = block.getLocation().toVector()).clone(); + int c; + if (this.c == 4) { + double n2; + if ((n2 = (snipeData.owner().getPlayer().getLocation().getYaw() - 90.0f) % 360.0f) < 0.0) { + n2 += 360.0; + } + c = ((0.0 >= n2 && n2 < 45.0) ? 2 : ((45.0 >= n2 && n2 < 135.0) ? 3 : ((135.0 >= n2 && n2 < 225.0) ? 0 : ((225.0 >= n2 && n2 < 315.0) ? 1 : ((315.0 >= n2 && n2 < 360.0) ? 2 : -1))))); + } + else { + c = this.c; + } + int n3 = c; + if (b) { + n3 = (short)((n3 + 2) % 4); + } + int n4 = 98; + if (n3 == 0 || n3 == 2) { + n4 = 97; + } + for (int i = -snipeData.getBrushSize(); i <= snipeData.getBrushSize(); ++i) { + if (n4 == 97) { + clone.setX(vector.getX() + i); + } + else { + clone.setZ(vector.getZ() + i); + } + for (int j = -snipeData.getBrushSize(); j <= snipeData.getBrushSize(); ++j) { + clone.setY(vector.getY() + j); + if (vector.distanceSquared(clone) <= n) { + for (short n5 = 0; n5 < this.d; ++n5) { + if (n4 == 97) { + clone.setZ(vector.getZ() + ((n3 == 2) ? n5 : (-n5))); + } + else { + clone.setX(vector.getX() + ((n3 == 1) ? n5 : (-n5))); + } + final AsyncBlock block2 = this.getWorld().getBlockAt(clone.getBlockX(), clone.getBlockY(), clone.getBlockZ()); + if ((this.f && block2.getTypeId() == snipeData.getReplaceId()) || (!this.f && (block2.getTypeId() != 0 || this.g))) { + block2.setTypeId(snipeData.getVoxelId()); + } + } + if (n4 == 97) { + clone.setZ(vector.getZ()); + } + else { + clone.setX(vector.getX()); + } + } + } + } + } + + @Override + protected final void arrow(final SnipeData snipeData) { + this.a(snipeData, this.getTargetBlock(), false); + } + + @Override + protected final void powder(final SnipeData snipeData) { + this.a(snipeData, this.getTargetBlock(), true); + } + + public final void parameters(final String[] array, final SnipeData snipeData) { + for (int i = 1; i < array.length; ++i) { + final String lowerCase; + if ((lowerCase = array[i].toLowerCase()).startsWith("d")) { + this.d = (short)Integer.parseInt(lowerCase.replace("d", "")); + snipeData.sendMessage(ChatColor.AQUA + "Depth set to " + this.d + " blocks"); + } + else if (lowerCase.startsWith("s")) { + this.c = (short)Integer.parseInt(lowerCase.replace("s", "")); + if (this.c > 4 || this.c < 0) { + this.c = 4; + } + snipeData.sendMessage(ChatColor.AQUA + "Orientation set to " + facings[this.c]); + } + else if (lowerCase.startsWith("true")) { + this.e = 0.5; + snipeData.sendMessage(ChatColor.AQUA + "True circle mode ON."); + } + else if (lowerCase.startsWith("false")) { + this.e = 0.0; + snipeData.sendMessage(ChatColor.AQUA + "True circle mode OFF."); + } + else if (lowerCase.startsWith("air")) { + this.g = true; + snipeData.sendMessage(ChatColor.AQUA + "Including air."); + } + else if (lowerCase.startsWith("mm")) { + this.f = true; + snipeData.sendMessage(ChatColor.AQUA + "Replacing block."); + } + } + } + + @Override + public String getPermissionNode() { + return "voxelsniper.brush.wallsider"; + } + + @Override + public void info(Message vm) { + // TODO Auto-generated method stub + + } + +} diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/PatternPerformer.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/PatternPerformer.java index aade828fa..dbbfd0782 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/PatternPerformer.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/PatternPerformer.java @@ -2,10 +2,10 @@ package com.thevoxelbox.voxelsniper.brush.perform; import com.boydti.fawe.bukkit.wrapper.AsyncBlock; import com.boydti.fawe.object.pattern.PatternTraverser; -import com.sk89q.worldedit.MutableBlockVector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.thevoxelbox.voxelsniper.Message; import com.thevoxelbox.voxelsniper.SnipeData; import org.bukkit.block.Block; @@ -14,7 +14,6 @@ public class PatternPerformer extends vPerformer { private String info; private Pattern pattern; private Extent extent; - private MutableBlockVector mutable = new MutableBlockVector(); @Override public void info(Message vm) { @@ -33,9 +32,9 @@ public class PatternPerformer extends vPerformer { @Override public void perform(AsyncBlock block) { - mutable.setComponents(block.getX(), block.getY(), block.getZ()); + BlockVector3 bv = BlockVector3.at(block.getX(), block.getY(), block.getZ()); try { - pattern.apply(extent, mutable, mutable); + pattern.apply(extent, bv, bv); } catch (WorldEditException e) { throw new RuntimeException(e); } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/Performer.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/Performer.java index 01a2a07c5..157d1b6ef 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/Performer.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/Performer.java @@ -12,7 +12,7 @@ import com.thevoxelbox.voxelsniper.Message; public interface Performer { - public void parse(String[] args, com.thevoxelbox.voxelsniper.SnipeData v); + void parse(String[] args, com.thevoxelbox.voxelsniper.SnipeData v); - public void showInfo(Message vm); + void showInfo(Message vm); } diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/PerformerE.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/PerformerE.java index ef0ff7e5a..c4f5b819e 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/PerformerE.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/brush/perform/PerformerE.java @@ -99,7 +99,7 @@ public enum PerformerE public static String performer_list_short = ""; public static String performer_list_long = ""; - private PerformerE(Class c, String s, String l) + PerformerE(Class c, String s, String l) { pclass = c; short_name = s; @@ -116,28 +116,12 @@ public enum PerformerE p = pclass.getConstructor().newInstance(); return p; } - catch (InstantiationException ex) - { - Logger.getLogger(PerformerE.class.getName()).log(Level.SEVERE, null, ex); - } - catch (IllegalAccessException ex) - { - Logger.getLogger(PerformerE.class.getName()).log(Level.SEVERE, null, ex); - } - catch (IllegalArgumentException ex) - { - Logger.getLogger(PerformerE.class.getName()).log(Level.SEVERE, null, ex); - } - catch (InvocationTargetException ex) + catch (InstantiationException | IllegalAccessException | InvocationTargetException | IllegalArgumentException ex) { Logger.getLogger(PerformerE.class.getName()).log(Level.SEVERE, null, ex); } } - catch (NoSuchMethodException ex) - { - Logger.getLogger(PerformerE.class.getName()).log(Level.SEVERE, null, ex); - } - catch (SecurityException ex) + catch (NoSuchMethodException | SecurityException ex) { Logger.getLogger(PerformerE.class.getName()).log(Level.SEVERE, null, ex); } @@ -163,8 +147,8 @@ public enum PerformerE static { - performers = new TreeMap(); - long_names = new TreeMap(); + performers = new TreeMap<>(); + long_names = new TreeMap<>(); for (PerformerE pe : values()) { diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/command/VoxelReplaceCommand.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/command/VoxelReplaceCommand.java index d3674f374..0e040ce4e 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/command/VoxelReplaceCommand.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/command/VoxelReplaceCommand.java @@ -2,6 +2,7 @@ package com.thevoxelbox.voxelsniper.command; import com.bekvon.bukkit.residence.commands.material; import com.boydti.fawe.bukkit.wrapper.AsyncBlock; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.thevoxelbox.voxelsniper.RangeBlockHelper; import com.thevoxelbox.voxelsniper.SnipeData; @@ -39,7 +40,7 @@ public class VoxelReplaceCommand extends VoxelCommand return true; } - BlockTypes weType = BlockTypes.parse(args[0]); + BlockType weType = BlockTypes.parse(args[0]); if (weType != null) { snipeData.setReplaceId(weType.getInternalId()); diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/command/VoxelVoxelCommand.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/command/VoxelVoxelCommand.java index cbd8b52fe..743b027c7 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/command/VoxelVoxelCommand.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/command/VoxelVoxelCommand.java @@ -29,6 +29,7 @@ import com.bekvon.bukkit.residence.commands.material; import com.boydti.fawe.bukkit.favs.PatternUtil; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.thevoxelbox.voxelsniper.RangeBlockHelper; import com.thevoxelbox.voxelsniper.SnipeData; @@ -53,8 +54,8 @@ public class VoxelVoxelCommand extends VoxelCommand { Block block = (new RangeBlockHelper(player, sniper.getWorld())).getTargetBlock(); Material blockType = block.getType(); - BlockTypes weType = BukkitAdapter.adapt(blockType); - if(!player.hasPermission("voxelsniper.ignorelimitations") && WorldEdit.getInstance().getConfiguration().disallowedBlocks.contains(weType)) { + BlockType weType = BukkitAdapter.adapt(blockType); + if(!player.hasPermission("voxelsniper.ignorelimitations") && WorldEdit.getInstance().getConfiguration().disallowedBlocks.contains(weType.getId())) { player.sendMessage("You are not allowed to use " + blockType.name() + ". (WorldEdit config.yml)"); return true; } @@ -65,9 +66,9 @@ public class VoxelVoxelCommand extends VoxelCommand { return true; } else { - BlockTypes weType = BlockTypes.parse(args[0]); + BlockType weType = BlockTypes.parse(args[0]); if(weType != null) { - if(!player.hasPermission("voxelsniper.ignorelimitations") && WorldEdit.getInstance().getConfiguration().disallowedBlocks.contains(weType)) { + if(!player.hasPermission("voxelsniper.ignorelimitations") && WorldEdit.getInstance().getConfiguration().disallowedBlocks.contains(weType.getId())) { player.sendMessage("You are not allowed to use " + weType + "."); return true; } else { diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/jsap/HelpJSAP.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/jsap/HelpJSAP.java index 17a01b81c..89870aa21 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/jsap/HelpJSAP.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/jsap/HelpJSAP.java @@ -165,7 +165,7 @@ public class HelpJSAP extends JSAP { if (!(jsapResult.success()) || jsapResult.getBoolean("help")) { - List returnValue = new LinkedList(); + List returnValue = new LinkedList<>(); // To avoid spurious missing argument errors we never print errors if help is required. if (!jsapResult.getBoolean("help")) { diff --git a/favs/src/main/java/com/thevoxelbox/voxelsniper/util/BlockWrapper.java b/favs/src/main/java/com/thevoxelbox/voxelsniper/util/BlockWrapper.java index 997ccc1e3..d8f31240c 100644 --- a/favs/src/main/java/com/thevoxelbox/voxelsniper/util/BlockWrapper.java +++ b/favs/src/main/java/com/thevoxelbox/voxelsniper/util/BlockWrapper.java @@ -1,6 +1,7 @@ package com.thevoxelbox.voxelsniper.util; import com.boydti.fawe.bukkit.wrapper.AsyncBlock; +import org.bukkit.Material; import org.bukkit.World; /** @@ -10,6 +11,7 @@ public class BlockWrapper { private int id; + private Material type; private int x; private int y; private int z; @@ -38,6 +40,10 @@ public class BlockWrapper return this.data; } + public Material getType() { + return type; + } + /** * @return the id */ @@ -131,4 +137,9 @@ public class BlockWrapper { this.z = z; } + + public void setType(Material type) { + this.type = type; + } + } diff --git a/favs/src/main/resources/plugin.yml b/favs/src/main/resources/plugin.yml index fa6b1e7b1..6c5f76cd9 100644 --- a/favs/src/main/resources/plugin.yml +++ b/favs/src/main/resources/plugin.yml @@ -7,7 +7,7 @@ load: STARTUP database: false depend: [WorldEdit] api-version: 1.13 -#softdepend: [WorldGuard, PlotSquared, MCore, Factions, GriefPrevention, Residence, Towny, PlotMe, PreciousStones] +#softdepend: [WorldGuard, PlotSquared, MCore, Factions, GriefPrevention, Residence, Towny, PreciousStones] commands: '/p': description: VoxelSniper perform command @@ -146,6 +146,7 @@ permissions: voxelsniper.brush.ellipsoid: true voxelsniper.brush.eraser: true voxelsniper.brush.erode: true + voxelsniper.brush.erodeblend: true voxelsniper.brush.extrude: true voxelsniper.brush.filldown: true voxelsniper.brush.flatocean: true @@ -190,6 +191,7 @@ permissions: voxelsniper.brush.voxeldisc: true voxelsniper.brush.voxeldiscface: true voxelsniper.brush.warp: true + voxelsniper.brush.wallsider: true voxelsniper.goto: true voxelsniper.sniper: true voxelsniper.sniper: @@ -228,6 +230,7 @@ permissions: voxelsniper.brush.entityremoval: true voxelsniper.brush.eraser: true voxelsniper.brush.erode: true + voxelsniper.brush.erodeblend: true voxelsniper.brush.extrude: true voxelsniper.brush.filldown: true voxelsniper.brush.flatocean: true @@ -279,6 +282,7 @@ permissions: voxelsniper.brush.voxeldisc: true voxelsniper.brush.voxeldiscface: true voxelsniper.brush.warp: true + voxelsniper.brush.wallsider: true voxelsniper.brush.ball: default: op voxelsniper.brush.biome: @@ -333,6 +337,8 @@ permissions: default: op voxelsniper.brush.erode: default: op + voxelsniper.brush.erodeblend: + default: op voxelsniper.brush.extrude: default: op voxelsniper.brush.filldown: @@ -433,5 +439,7 @@ permissions: default: op voxelsniper.brush.voxeldiscface: default: op + voxelsniper.brush.wallsider: + default: op voxelsniper.brush.warp: default: op \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index e0b3fb8d7..db93606ed 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,6 @@ +#Mon Mar 25 18:59:14 EDT 2019 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip diff --git a/splash.txt b/splash.txt index 70cf461ed..c63b561f2 100644 --- a/splash.txt +++ b/splash.txt @@ -10,7 +10,6 @@ ======= By Empire92 and WorldEdit team ======= If you encounter trouble: - - Read COMPILING.md if you haven't yet - Run `build` in a separate Gradle run - Use gradlew and not gradle - Ask us! diff --git a/worldedit-bukkit/build.gradle b/worldedit-bukkit/build.gradle index 5e5b3f48b..acefe8c9b 100644 --- a/worldedit-bukkit/build.gradle +++ b/worldedit-bukkit/build.gradle @@ -1,90 +1,88 @@ -apply plugin: 'eclipse' -apply plugin: 'idea' -apply plugin: 'maven' - -repositories { - maven { url "https://hub.spigotmc.org/nexus/content/groups/public" } - maven { url "https://ci.athion.net/job/FAWE-WorldGuard-1.13/lastSuccessfulBuild/artifact/mvn" } -} - -dependencies { - compile project(':worldedit-core') - compile 'com.sk89q:dummypermscompat:1.8' - compile 'com.destroystokyo.paper:paper-api:1.13-R0.1-SNAPSHOT' - compile 'org.spigotmc:spigot:1.13.2-R0.1-SNAPSHOT' - testCompile 'org.mockito:mockito-core:1.9.0-rc1' - compile 'net.milkbowl.vault:VaultAPI:1.5.6' - compile 'com.massivecraft:factions:2.8.0' - compile 'com.drtshock:factions:1.6.9.5' - compile 'com.factionsone:FactionsOne:1.2.2' - compile 'me.ryanhamshire:GriefPrevention:11.5.2' - compile 'com.massivecraft:mcore:7.0.1' - compile 'net.sacredlabyrinth.Phaed:PreciousStones:10.0.4-SNAPSHOT' - compile 'net.jzx7:regios:5.9.9' - compile 'com.bekvon.bukkit.residence:Residence:4.5._13.1' - compile 'com.palmergames.bukkit:towny:0.84.0.9' - compile 'com.worldcretornica:plotme_core:0.16.3' - compile 'com.thevoxelbox.voxelsniper:voxelsniper:5.171.0' - compile 'com.comphenix.protocol:ProtocolLib-API:4.4.0-SNAPSHOT' - compile 'com.wasteofplastic:askyblock:3.0.8.2' - compile 'com.sk89q:worldguard-core:latest' - compile 'com.sk89q:worldguard-legacy:latest' -} - -processResources { - from (sourceSets.main.resources.srcDirs) { - expand 'internalVersion': project.internalVersion - include 'plugin.yml' - } - - from (sourceSets.main.resources.srcDirs) { - exclude 'plugin.yml' - } -} - -jar.archiveName="fawe-bukkit-${project.parent.version}.jar" -jar.destinationDir = file '../mvn/com/boydti/fawe-bukkit/' + project.parent.version -task createPom << { - pom { - project { - groupId 'com.boydti' - artifactId 'fawe-bukkit' - version project.parent.version - } - } - .getEffectivePom() - .setDependencies(new ArrayList<>()) - .writeTo("../mvn/com/boydti/fawe-bukkit/${project.parent.version}/fawe-bukkit-${project.parent.version}.pom") - pom { - project { - groupId 'com.boydti' - artifactId 'fawe-bukkit' - version 'latest' - } - } - .getEffectivePom() - .setDependencies(new ArrayList<>()) - .writeTo("../mvn/com/boydti/fawe-bukkit/latest/fawe-bukkit-latest.pom") -} -task copyFiles { - doLast { - copy { - from "../mvn/com/boydti/fawe-bukkit/${project.parent.version}/" - into '../mvn/com/boydti/fawe-bukkit/latest/' - include('*.jar') - rename ("fawe-bukkit-${project.parent.version}.jar", 'fawe-bukkit-latest.jar') - } - } -} - -shadowJar { - dependencies { - include(dependency(':worldedit-core')) - } - archiveName = "${parent.name}-${project.name.replaceAll("worldedit-", "")}-${parent.version}.jar" - destinationDir = file '../target' -} - -build.dependsOn(shadowJar) -build.finalizedBy(copyFiles) -copyFiles.dependsOn(createPom) +apply plugin: 'eclipse' +apply plugin: 'idea' +apply plugin: 'maven' + +repositories { + maven { url "https://hub.spigotmc.org/nexus/content/groups/public" } +} + +dependencies { + compile project(':worldedit-core') + compile 'net.milkbowl.vault:VaultAPI:1.7' + compile 'com.sk89q:dummypermscompat:1.10' + compile 'com.destroystokyo.paper:paper-api:1.13.2-R0.1-SNAPSHOT' + compile 'org.spigotmc:spigot:1.13.2-R0.1-SNAPSHOT' + testCompile 'org.mockito:mockito-core:1.9.0-rc1' + compile 'com.massivecraft:factions:2.8.0' + compile 'com.drtshock:factions:1.6.9.5' + compile 'com.factionsone:FactionsOne:1.2.2' + compile 'me.ryanhamshire:GriefPrevention:11.5.2' + compile 'com.massivecraft:mcore:7.0.1' + compile 'net.sacredlabyrinth.Phaed:PreciousStones:10.0.4-SNAPSHOT' + compile 'net.jzx7:regios:5.9.9' + compile 'com.bekvon.bukkit.residence:Residence:4.5._13.1' + compile 'com.palmergames.bukkit:towny:0.84.0.9' + compile 'com.thevoxelbox.voxelsniper:voxelsniper:5.171.0' + compile 'com.comphenix.protocol:ProtocolLib-API:4.4.0-SNAPSHOT' + compile 'com.wasteofplastic:askyblock:3.0.8.2' + compileOnly 'com.sk89q.worldguard:worldguard-core:7.0.0-20190215.210421-39' + compileOnly 'com.sk89q.worldguard:worldguard-legacy:7.0.0-20190215.210421-39' +} + +processResources { + from (sourceSets.main.resources.srcDirs) { + expand 'internalVersion': project.internalVersion + include 'plugin.yml' + } + + from (sourceSets.main.resources.srcDirs) { + exclude 'plugin.yml' + } +} + +jar.archiveName="fawe-bukkit-${project.parent.version}.jar" +jar.destinationDir = file '../mvn/com/boydti/fawe-bukkit/' + project.parent.version +task createPom << { + pom { + project { + groupId 'com.boydti' + artifactId 'fawe-bukkit' + version project.parent.version + } + } + .getEffectivePom() + .setDependencies(new ArrayList<>()) + .writeTo("../mvn/com/boydti/fawe-bukkit/${project.parent.version}/fawe-bukkit-${project.parent.version}.pom") + pom { + project { + groupId 'com.boydti' + artifactId 'fawe-bukkit' + version 'latest' + } + } + .getEffectivePom() + .setDependencies(new ArrayList<>()) + .writeTo("../mvn/com/boydti/fawe-bukkit/latest/fawe-bukkit-latest.pom") +} +task copyFiles { + doLast { + copy { + from "../mvn/com/boydti/fawe-bukkit/${project.parent.version}/" + into '../mvn/com/boydti/fawe-bukkit/latest/' + include('*.jar') + rename ("fawe-bukkit-${project.parent.version}.jar", 'fawe-bukkit-latest.jar') + } + } +} + +shadowJar { + dependencies { + include(dependency(':worldedit-core')) + } + archiveName = "${parent.name}-${project.name.replaceAll("worldedit-", "")}-${parent.version}.jar" + destinationDir = file '../target' +} + +build.dependsOn(shadowJar) +build.finalizedBy(copyFiles) +copyFiles.dependsOn(createPom) diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/BStats.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/BStats.java new file mode 100644 index 000000000..1bcc86214 --- /dev/null +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/BStats.java @@ -0,0 +1,704 @@ +package org.bstats.bukkit; + +import com.boydti.fawe.Fawe; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"WeakerAccess", "unused"}) public class BStats { + + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System + .getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', + 'k', 'i', 't'}); + final String examplePackage = + new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class + .getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException( + "bStats Metrics class has not been relocated correctly!"); + } + } + } + + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Is bStats enabled on this server? + private boolean enabled; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // The uuid of the server + private static String serverUUID; + + // The plugin + private final Plugin plugin; + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + */ + public BStats(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)").copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + + // Load the data + enabled = config.getBoolean("enabled", true); + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { + } + } + // Register our service + Bukkit.getServicesManager() + .register(BStats.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = + new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JSONObject getPluginData() { + JSONObject data = new JSONObject(); + + String pluginName = "FastAsyncWorldEdit"; + String pluginVersion = Fawe.get().getVersion() + ""; + + data.put("pluginName", pluginName); // Append the name of the plugin + data.put("pluginVersion", pluginVersion); // Append the version of the plugin + JSONArray customCharts = new JSONArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JSONObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.put("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JSONObject getServerData() { + // Minecraft specific data + int playerAmount = getPlayerCount(); + int onlineMode = Fawe.imp().isOnlineMode() ? 1 : 0; + String serverVersion = Fawe.imp().getPlatformVersion(); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JSONObject data = new JSONObject(); + + data.put("serverUUID", serverUUID); + + data.put("playerAmount", playerAmount); + data.put("onlineMode", onlineMode); + data.put("bukkitVersion", serverVersion); + + data.put("javaVersion", javaVersion); + data.put("osName", osName); + data.put("osArch", osArch); + data.put("osVersion", osVersion); + data.put("coreCount", coreCount); + + return data; + } + + public int getPlayerCount() { + return Fawe.imp() == null ? 1 : Fawe.imp().getPlayerCount(); + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JSONObject data = getServerData(); + + JSONArray pluginData = new JSONArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + + for (RegisteredServiceProvider provider : Bukkit.getServicesManager() + .getRegistrations(service)) { + try { + pluginData.add(provider.getService().getMethod("getPluginData") + .invoke(provider.getProvider())); + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } + } + } catch (NoSuchFieldException ignored) { + } + } + + data.put("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(() -> { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger() + .log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), + e); + } + } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JSONObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException( + "This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data.toString()); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", + "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + outputStream.flush(); + } + + StringBuilder builder; + try (InputStream inputStream = connection.getInputStream(); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(inputStream))) { + + builder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + if (logResponseStatusText) { + plugin.getLogger() + .info("Sent data to bStats and received response: " + builder.toString()); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(outputStream); + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + gzip.close(); + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + private JSONObject getRequestJsonObject() { + JSONObject chart = new JSONObject(); + chart.put("chartId", chartId); + try { + JSONObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.put("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, + "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JSONObject getChartData() throws Exception; + + } + + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + } + + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override public JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JSONObject value = new JSONObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()) + .entrySet()) { + value.put(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.put(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + + } + + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + + } + + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JSONArray categoryValues = new JSONArray(); + categoryValues.add(entry.getValue()); + values.put(entry.getKey(), categoryValues); + } + data.put("values", values); + return data; + } + + } + + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JSONArray categoryValues = new JSONArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(categoryValue); + } + values.put(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + +} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/BukkitPlayer.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/BukkitPlayer.java index 3881f1ffd..25eea21b9 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/BukkitPlayer.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/BukkitPlayer.java @@ -8,7 +8,6 @@ import com.boydti.fawe.wrappers.PlayerWrapper; import java.lang.reflect.Method; import java.util.UUID; -import com.intellectualcrafters.plot.config.C; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import org.bukkit.Bukkit; 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 909f51ed9..550a1fe8e 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/FaweBukkit.java @@ -24,13 +24,11 @@ import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.regions.FaweMaskManager; import com.boydti.fawe.util.Jars; import com.boydti.fawe.util.MainUtil; -import com.boydti.fawe.util.ReflectionUtils; import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.cui.CUI; import com.boydti.fawe.util.image.ImageViewer; -import com.boydti.fawe.util.metrics.BStats; -import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.world.World; +import org.bstats.bukkit.BStats; import org.bukkit.Bukkit; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.PluginCommand; @@ -41,7 +39,6 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.Vector; @@ -74,8 +71,6 @@ public class FaweBukkit implements IFawe, Listener { return this.vault; } - private List locations = Arrays.asList(new Vector(0, 5, 0)); - public FaweBukkit(Plugin plugin) { this.plugin = plugin; try { @@ -110,28 +105,25 @@ public class FaweBukkit implements IFawe, Listener { } // Registered delayed Event Listeners - TaskManager.IMP.task(new Runnable() { - @Override - public void run() { - // This class - Bukkit.getPluginManager().registerEvents(FaweBukkit.this, FaweBukkit.this.plugin); + TaskManager.IMP.task(() -> { + // This class + Bukkit.getPluginManager().registerEvents(FaweBukkit.this, FaweBukkit.this.plugin); - // The tick limiter - try { - Class.forName("sun.misc.SharedSecrets"); - new ChunkListener_8(); - } catch (ClassNotFoundException e) { - new ChunkListener_9(); - } - - /*try { - Class.forName("com.destroystokyo.paper.event.server.AsyncTabCompleteEvent"); - new AsyncTabCompleteListener(WorldEditPlugin.getInstance()); - } catch (Throwable ignore) - { - Bukkit.getPluginManager().registerEvents(new SyncTabCompleteListener(WorldEditPlugin.getInstance()), plugin); - }*/ + // The tick limiter + try { + Class.forName("sun.misc.SharedSecrets"); + new ChunkListener_8(); + } catch (ClassNotFoundException e) { + new ChunkListener_9(); } + + /*try { + Class.forName("com.destroystokyo.paper.event.server.AsyncTabCompleteEvent"); + new AsyncTabCompleteListener(WorldEditPlugin.getInstance()); + } catch (Throwable ignore) + { + Bukkit.getPluginManager().registerEvents(new SyncTabCompleteListener(WorldEditPlugin.getInstance()), plugin); + }*/ }); } @@ -265,42 +257,8 @@ public class FaweBukkit implements IFawe, Listener { } } - @Override - public void startMetrics() { - Metrics metrics = new Metrics(plugin); - metrics.start(); - TaskManager.IMP.task(new Runnable() { - @Override - public void run() { - ArrayList> services = new ArrayList(Bukkit.getServicesManager().getKnownServices()); - services.forEach(service -> { - try { - service.getField("B_STATS_VERSION"); - ArrayList> providers = new ArrayList(Bukkit.getServicesManager().getRegistrations(service)); - for (RegisteredServiceProvider provider : providers) { - Object instance = provider.getProvider(); - - // Link it to FAWE's metrics instead - BStats.linkMetrics(instance); - - // Disable the other metrics - Bukkit.getServicesManager().unregister(service, instance); - try { - Class clazz = instance.getClass(); - Field logFailedRequests = ReflectionUtils.findField(clazz, boolean.class); - logFailedRequests.set(null, false); - Field url = null; - try { url = clazz.getDeclaredField("URL"); } catch (NoSuchFieldException ignore) { - for (Field field : clazz.getDeclaredFields()) if (ReflectionUtils.setAccessible(field).get(null).toString().startsWith("http")) { url = field; break; } - } - if (url != null) ReflectionUtils.setFailsafeFieldValue(url, null, null); - } catch (NoSuchFieldError | IllegalAccessException ignore) {} - catch (Throwable e) {} - } - } catch (NoSuchFieldException ignored) { } - }); - } - }); + @Override public void startMetrics() { + BStats bStats = new BStats(plugin); } public ItemUtil getItemUtil() { @@ -335,11 +293,11 @@ public class FaweBukkit implements IFawe, Listener { public String getDebugInfo() { StringBuilder msg = new StringBuilder(); List pl = new ArrayList<>(); - msg.append("server.plugins: \n"); + msg.append("server.version: " + Bukkit.getVersion() + " / " + Bukkit.getBukkitVersion() + "\n"); + msg.append("Plugins: \n"); for (Plugin p : Bukkit.getPluginManager().getPlugins()) { msg.append(" - " + p.getName() + ": " + p.getDescription().getVersion() + "\n"); } - msg.append("server.version: " + Bukkit.getVersion() + " / " + Bukkit.getBukkitVersion() + "\n"); return msg.toString(); } @@ -387,12 +345,8 @@ public class FaweBukkit implements IFawe, Listener { debug("======================================="); ignore.printStackTrace(); debug("======================================="); - TaskManager.IMP.laterAsync(new Runnable() { - @Override - public void run() { - MainUtil.sendAdmin("&cNo NMS placer found, see console!"); - } - }, 1); + TaskManager.IMP.laterAsync( + () -> MainUtil.sendAdmin("&cNo NMS placer found, see console!"), 1); hasNMS = false; } return new BukkitQueue_All(world); @@ -443,12 +397,8 @@ public class FaweBukkit implements IFawe, Listener { debug("======================================="); error.printStackTrace(); debug("======================================="); - TaskManager.IMP.laterAsync(new Runnable() { - @Override - public void run() { - MainUtil.sendAdmin("&cNo NMS placer found, see console!"); - } - }, 1); + TaskManager.IMP.laterAsync( + () -> MainUtil.sendAdmin("&cNo NMS placer found, see console!"), 1); hasNMS = false; } } @@ -480,15 +430,6 @@ public class FaweBukkit implements IFawe, Listener { MainUtil.handleError(e); } } - final Plugin plotmePlugin = Bukkit.getServer().getPluginManager().getPlugin("PlotMe"); - if ((plotmePlugin != null) && plotmePlugin.isEnabled()) { - try { - managers.add(new PlotMeFeature(plotmePlugin, this)); - Fawe.debug("Plugin 'PlotMe' found. Using it now."); - } catch (final Throwable e) { - MainUtil.handleError(e); - } - } final Plugin townyPlugin = Bukkit.getServer().getPluginManager().getPlugin("Towny"); if ((townyPlugin != null) && townyPlugin.isEnabled()) { try { diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/Metrics.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/Metrics.java deleted file mode 100644 index ff1deca39..000000000 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/Metrics.java +++ /dev/null @@ -1,584 +0,0 @@ -package com.boydti.fawe.bukkit; - -import com.boydti.fawe.Fawe; -import com.boydti.fawe.object.io.FastByteArrayOutputStream; -import com.boydti.fawe.object.io.PGZIPOutputStream; -import com.boydti.fawe.util.MainUtil; -import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.net.Proxy; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.*; -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.scheduler.BukkitTask; - -public class Metrics { - - /** - * The current revision number. - */ - private static final int REVISION = 7; - /** - * The base url of the metrics domain. - */ - private static final String BASE_URL = "http://report.mcstats.org"; - /** - * The url used to report a server's status. - */ - private static final String REPORT_URL = "/plugin/%s"; - /** - * Interval of time to ping (in minutes). - */ - private static final int PING_INTERVAL = 15; - /** - * The plugin this metrics submits for. - */ - private final Plugin plugin; - /** - * All of the custom graphs to submit to metrics. - */ - private final Set graphs = Collections.synchronizedSet(new HashSet()); - /** - * Unique server id. - */ - private final String guid; - /** - * Debug mode. - */ - private final boolean debug; - /** - * The scheduled task. - */ - private volatile BukkitTask task = null; - - public Metrics(Plugin plugin) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - this.plugin = plugin; - this.guid = UUID.randomUUID().toString(); - this.debug = false; - } - - /** - * GZip compress a string of bytes. - * - * @param input - * - * @return byte[] the file as a byte array - */ - public static byte[] gzip(String input) { - FastByteArrayOutputStream baos = new FastByteArrayOutputStream(); - PGZIPOutputStream gzos = null; - try { - gzos = new PGZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); - } catch (IOException e) { - MainUtil.handleError(e); - } finally { - if (gzos != null) { - try { - gzos.close(); - } catch (IOException ignore) { - } - } - } - return baos.toByteArray(); - } - - /** - * Appends a json encoded key/value pair to the given string builder. - * - * @param json - * @param key - * @param value - * - */ - private static void appendJSONPair(StringBuilder json, String key, String value) { - boolean isValueNumeric = false; - try { - if (value.equals("0") || !value.endsWith("0")) { - Double.parseDouble(value); - isValueNumeric = true; - } - } catch (NumberFormatException e) { - isValueNumeric = false; - } - if (json.charAt(json.length() - 1) != '{') { - json.append(','); - } - json.append(escapeJSON(key)); - json.append(':'); - if (isValueNumeric) { - json.append(value); - } else { - json.append(escapeJSON(value)); - } - } - - /** - * Escape a string to create a valid JSON string - * - * @param text - * - * @return String - */ - private static String escapeJSON(String text) { - StringBuilder builder = new StringBuilder(); - builder.append('"'); - for (int index = 0; index < text.length(); index++) { - char chr = text.charAt(index); - switch (chr) { - case '"': - case '\\': - builder.append('\\'); - builder.append(chr); - break; - case '\b': - builder.append("\\b"); - break; - case '\t': - builder.append("\\t"); - break; - case '\n': - builder.append("\\n"); - break; - case '\r': - builder.append("\\r"); - break; - default: - if (chr < ' ') { - String t = "000" + Integer.toHexString(chr); - builder.append("\\u" + t.substring(t.length() - 4)); - } else { - builder.append(chr); - } - break; - } - } - builder.append('"'); - return builder.toString(); - } - - /** - * Encode text as UTF-8 - * - * @param text the text to encode - * - * @return the encoded text, as UTF-8 - */ - private static String urlEncode(String text) throws UnsupportedEncodingException { - return URLEncoder.encode(text, "UTF-8"); - } - - /** - * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics - * website. Plotters can be added to the graph object returned. - * - * @param name The name of the graph - * - * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given - */ - public Graph createGraph(String name) { - if (name == null) { - throw new IllegalArgumentException("Graph name cannot be null"); - } - // Construct the graph object - Graph graph = new Graph(name); - // Now we can add our graph - this.graphs.add(graph); - // and return back - return graph; - } - - /** - * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend - * - * @param graph The name of the graph - */ - public void addGraph(Graph graph) { - if (graph == null) { - throw new IllegalArgumentException("Graph cannot be null"); - } - this.graphs.add(graph); - } - - /** - * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the - * initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 - * ticks. - * - * @return True if statistics measuring is running, otherwise false. - */ - public boolean start() { - // Is metrics already running? - if (this.task != null) { - return true; - } - // Begin hitting the server with glorious data - this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() { - private boolean firstPost = true; - - @Override - public void run() { - try { - postPlugin(!this.firstPost); - // After the first post we set firstPost to - // false - // Each post thereafter will be a ping - this.firstPost = false; - } catch (IOException e) { - MainUtil.handleError(e); - if (Metrics.this.debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - } - }, 0, PING_INTERVAL * 1200); - return true; - } - - /** - * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. - * - * @throws IOException - */ - public void enable() { - // Enable Task, if it is not running - if (this.task == null) { - start(); - } - } - - /** - * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. - * - */ - public void disable() { - // Disable Task, if it is running - if (this.task != null) { - this.task.cancel(); - this.task = null; - } - } - - /** - * Gets the File object of the config file that should be used to store - * data such as the GUID and opt-out status. - * - * @return the File object for the config file - */ - public File getConfigFile() { - // I believe the easiest way to get the base folder (e.g craftbukkit set - // via -P) for plugins to use - // is to abuse the plugin object we already have - // plugin.getDataFolder() => base/plugins/PluginA/ - // pluginsFolder => base/plugins/ - // The base is not necessarily relative to the startup directory. - File pluginsFolder = this.plugin.getDataFolder().getParentFile(); - // return => base/plugins/PluginMetrics/config.yml - return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); - } - - /** - * Generic method that posts a plugin to the metrics website. - */ - private void postPlugin(boolean isPing) throws IOException { - // Server software specific section - PluginDescriptionFile description = this.plugin.getDescription(); - String pluginName = description.getName(); - boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled - String pluginVersion = description.getVersion(); - String serverVersion = Bukkit.getVersion(); - int playersOnline = 0; - try { - if (Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).getReturnType() == Collection.class) { - playersOnline = ((Collection) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).invoke(null)).size(); - } else { - playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).invoke(null)).length; - } - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { - ex.printStackTrace(); - } - // END server software specific section -- all code below does not use - // any code outside of this class / Java - // Construct the post data - StringBuilder json = new StringBuilder(1024); - json.append('{'); - // The plugin's description file containing all of the plugin data such as name, version, author, etc - appendJSONPair(json, "guid", this.guid); - appendJSONPair(json, "plugin_version", pluginVersion); - appendJSONPair(json, "server_version", serverVersion); - appendJSONPair(json, "players_online", Integer.toString(playersOnline)); - // New data as of R6 - String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - String osversion = System.getProperty("os.version"); - String java_version = System.getProperty("java.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - // normalize os arch .. amd64 -> x86_64 - if (osarch.equals("amd64")) { - osarch = "x86_64"; - } - appendJSONPair(json, "osname", osname); - appendJSONPair(json, "osarch", osarch); - appendJSONPair(json, "osversion", osversion); - appendJSONPair(json, "cores", Integer.toString(coreCount)); - appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); - appendJSONPair(json, "java_version", java_version); - // If we're pinging, append it - if (isPing) { - appendJSONPair(json, "ping", "1"); - } - if (!this.graphs.isEmpty()) { - synchronized (this.graphs) { - json.append(','); - json.append('"'); - json.append("graphs"); - json.append('"'); - json.append(':'); - json.append('{'); - boolean firstGraph = true; - for (Graph graph : this.graphs) { - StringBuilder graphJson = new StringBuilder(); - graphJson.append('{'); - for (Plotter plotter : graph.getPlotters()) { - appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); - } - graphJson.append('}'); - if (!firstGraph) { - json.append(','); - } - json.append(escapeJSON(graph.getName())); - json.append(':'); - json.append(graphJson); - firstGraph = false; - } - json.append('}'); - } - } - // close json - json.append('}'); - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); - // Connect to the website - URLConnection connection; - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) { - connection = url.openConnection(Proxy.NO_PROXY); - } else { - connection = url.openConnection(); - } - byte[] uncompressed = json.toString().getBytes(); - byte[] compressed = gzip(json.toString()); - // Headers - connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); - connection.addRequestProperty("Content-Type", "application/json"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.setDoOutput(true); - if (this.debug) { - Fawe.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); - } - try { - try (OutputStream os = connection.getOutputStream()) { - os.write(compressed); - os.flush(); - } - String response; - try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - response = reader.readLine(); - if (this.debug) { - Fawe.debug("[Metrics] Response for " + pluginName + ": " + response); - } - } - if (response == null || response.startsWith("ERR") || response.startsWith("7")) { - if (response == null) { - response = "null"; - } else if (response.startsWith("7")) { - response = response.substring(response.startsWith("7,") ? 2 : 1); - } - throw new IOException(response); - } else { - // Is this the first update this hour? - if ("1".equals(response) || response.contains("This is your first update this hour")) { - synchronized (this.graphs) { - for (Graph graph : this.graphs) { - for (Plotter plotter : graph.getPlotters()) { - plotter.reset(); - } - } - } - } - } - } catch (Exception e) { - if (this.debug) { - MainUtil.handleError(e); - } - } - } - - /** - * Check if mineshafter is present. If it is, we need to bypass it to send POST requests - * - * @return true if mineshafter is installed on the server - */ - private boolean isMineshafterPresent() { - try { - Class.forName("mineshafter.MineServer"); - return true; - } catch (ClassNotFoundException e) { - return false; - } - } - - /** - * Represents a custom graph on the website - */ - public static class Graph { - - /** - * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is - * rejected - */ - private final String name; - /** - * The set of plotters that are contained within this graph - */ - private final Set plotters = new LinkedHashSet<>(); - - private Graph(String name) { - this.name = name; - } - - /** - * Gets the graph's name - * - * @return the Graph's name - */ - public String getName() { - return this.name; - } - - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter the plotter to add to the graph - */ - public void addPlotter(Plotter plotter) { - this.plotters.add(plotter); - } - - /** - * Remove a plotter from the graph - * - * @param plotter the plotter to remove from the graph - */ - public void removePlotter(Plotter plotter) { - this.plotters.remove(plotter); - } - - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return an unmodifiable {@link Set} of the plotter objects - */ - public Set getPlotters() { - return Collections.unmodifiableSet(this.plotters); - } - - @Override - public int hashCode() { - return this.name.hashCode(); - } - - @Override - public boolean equals(Object object) { - if (!(object instanceof Graph)) { - return false; - } - Graph graph = (Graph) object; - return graph.name.equals(this.name); - } - - /** - * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. - */ - protected void onOptOut() { - } - } - - /** - * Interface used to collect custom data for a plugin - */ - public abstract static class Plotter { - - /** - * The plot's name - */ - private final String name; - - /** - * Construct a plotter with the default plot name - */ - public Plotter() { - this("Default"); - } - - /** - * Construct a plotter with a specific plot name - * - * @param name the name of the plotter to use, which will show up on the website - */ - public Plotter(String name) { - this.name = name; - } - - /** - * Get the current value for the plotted point. Since this function defers to an external function it may or may - * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called - * from any thread so care should be taken when accessing resources that need to be synchronized. - * - * @return the current value for the point to be plotted. - */ - public abstract int getValue(); - - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() { - return this.name; - } - - /** - * Called after the website graphs have been updated - */ - public void reset() { - } - - @Override - public int hashCode() { - return getColumnName().hashCode(); - } - - @Override - public boolean equals(Object object) { - if (!(object instanceof Plotter)) { - return false; - } - Plotter plotter = (Plotter) object; - return plotter.name.equals(this.name) && plotter.getValue() == getValue(); - } - } -} \ No newline at end of file diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/BlockMaterial_1_13.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/BlockMaterial_1_13.java index 30bffb79b..53a59d24d 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/BlockMaterial_1_13.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/BlockMaterial_1_13.java @@ -1,7 +1,8 @@ package com.boydti.fawe.bukkit.adapter.v1_13_1; import com.sk89q.util.ReflectionUtil; -import com.sk89q.worldedit.blocks.BlockMaterial; +import com.sk89q.worldedit.world.registry.BlockMaterial; + import net.minecraft.server.v1_13_R2.*; import org.bukkit.craftbukkit.v1_13_R2.block.data.CraftBlockData; diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java index 9726b20fd..628956cdf 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/adapter/v1_13_1/Spigot_v1_13_R2.java @@ -22,22 +22,20 @@ package com.boydti.fawe.bukkit.adapter.v1_13_1; import com.boydti.fawe.Fawe; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; -import com.sk89q.jnbt.*; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.blocks.BlockMaterial; +import com.sk89q.jnbt.*; import com.sk89q.worldedit.blocks.TileEntityBlock; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.bukkit.adapter.CachedBukkitAdapter; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.internal.Constants; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.registry.state.*; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.world.block.BlockState; -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.*; +import com.sk89q.worldedit.world.registry.BlockMaterial; import net.minecraft.server.v1_13_R2.*; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -49,14 +47,13 @@ import org.bukkit.craftbukkit.v1_13_R2.CraftWorld; import org.bukkit.craftbukkit.v1_13_R2.block.CraftBlock; import org.bukkit.craftbukkit.v1_13_R2.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_13_R2.entity.CraftEntity; +import org.bukkit.entity.Player; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import javax.annotation.Nullable; import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; -import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; @@ -69,7 +66,6 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit private final Field nbtListTagListField; private final Method nbtCreateTagMethod; - private Method chunkSetTypeMethod; static { // A simple test @@ -88,13 +84,6 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit // The method to create an NBTBase tag given its type ID nbtCreateTagMethod = NBTBase.class.getDeclaredMethod("createTag", byte.class); nbtCreateTagMethod.setAccessible(true); - - // 1.13.2 Adaptation to find the a/setType method - try { - chunkSetTypeMethod = Chunk.class.getMethod("setType", BlockPosition.class, IBlockData.class, boolean.class); - }catch(NoSuchMethodException e) { - chunkSetTypeMethod = Chunk.class.getMethod("a", BlockPosition.class, IBlockData.class, boolean.class); - } } private int[] idbToStateOrdinal; @@ -186,7 +175,7 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit @Override public BlockMaterial getMaterial(BlockState state) { - BlockTypes type = state.getBlockType(); + BlockType type = state.getBlockType(); IBlockData bs = ((CraftBlockData) Bukkit.createBlockData(state.getAsString())).getState(); return new BlockMaterial_1_13(bs.getBlock(), bs); } @@ -213,7 +202,7 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit @SuppressWarnings("deprecation") @Override - public BlockState getBlock(Location location) { + public BaseBlock getBlock(Location location) { checkNotNull(location); CraftWorld craftWorld = ((CraftWorld) location.getWorld()); @@ -229,11 +218,11 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit if (te != null) { NBTTagCompound tag = new NBTTagCompound(); readTileEntityIntoTag(te, tag); // Load data - return new BaseBlock(state, (CompoundTag) toNative(tag)); + return state.toBaseBlock((CompoundTag) toNative(tag)); } } - return state; + return state.toBaseBlock(); } @Override @@ -260,10 +249,13 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit } else { existing = section.getType(x & 15, y & 15, z & 15); } - BlockPosition pos = null; - CompoundTag nativeTag = state.getNbtData(); + + BlockPosition pos = new BlockPosition(x, y, z); + + nmsChunk.d(pos); // Force delete the old tile entity + + CompoundTag nativeTag = state instanceof BaseBlock ? ((BaseBlock)state).getNbtData() : null; if (nativeTag != null || existing instanceof TileEntityBlock) { - pos = new BlockPosition(x, y, z); nmsWorld.setTypeAndData(pos, blockData, 0); // remove tile if (nativeTag != null) { @@ -285,18 +277,12 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit sections[y4] = section = new ChunkSection(y4 << 4, nmsWorld.worldProvider.g()); } if (existing.e() != blockData.e() || existing.getMaterial().f() != blockData.getMaterial().f()) { - try { - chunkSetTypeMethod.invoke(nmsChunk, pos = new BlockPosition(x, y, z), blockData, false); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - logger.warning("Error when setting block!"); - e.printStackTrace(); - } + nmsChunk.setType(pos = new BlockPosition(x, y, z), blockData, false); } else { section.setType(x & 15, y & 15, z & 15, blockData); } } if (update) { - if (pos == null) pos = new BlockPosition(x, y, z); nmsWorld.getMinecraftWorld().notify(pos, existing, blockData, 0); } return true; @@ -325,7 +311,7 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit public org.bukkit.entity.Entity createEntity(Location location, BaseEntity state) { checkNotNull(location); checkNotNull(state); - + if (state.getType() == com.sk89q.worldedit.world.entity.EntityTypes.PLAYER) return null; CraftWorld craftWorld = ((CraftWorld) location.getWorld()); WorldServer worldServer = craftWorld.getHandle(); @@ -353,7 +339,7 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit @SuppressWarnings("unchecked") @Override - public Map getProperties(BlockType blockType) { + public Map> getProperties(BlockType blockType) { Block block; try { block = IRegistry.BLOCK.getOrDefault(new MinecraftKey(blockType.getNamespace(), blockType.getResource())); @@ -365,7 +351,7 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit logger.warning("Failed to find properties for " + blockType.getId()); return Collections.emptyMap(); } - Map properties = Maps.newLinkedHashMap(); + Map> properties = Maps.newLinkedHashMap(); BlockStateList blockStateList = block.getStates(); for (IBlockState state : blockStateList.d()) { Property property; @@ -411,17 +397,19 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit } return new CompoundTag(values); } else if (foreign instanceof NBTTagByte) { - return new ByteTag(((NBTTagByte) foreign).asByte()); // getByte + return new ByteTag(((NBTTagByte) foreign).asByte()); } else if (foreign instanceof NBTTagByteArray) { return new ByteArrayTag(((NBTTagByteArray) foreign).c()); // data } else if (foreign instanceof NBTTagDouble) { return new DoubleTag(((NBTTagDouble) foreign).asDouble()); // getDouble } else if (foreign instanceof NBTTagFloat) { - return new FloatTag(((NBTTagFloat) foreign).asFloat()); // getFloat + return new FloatTag(((NBTTagFloat) foreign).asFloat()); } else if (foreign instanceof NBTTagInt) { - return new IntTag(((NBTTagInt) foreign).asInt()); // getInt + return new IntTag(((NBTTagInt) foreign).asInt()); } else if (foreign instanceof NBTTagIntArray) { return new IntArrayTag(((NBTTagIntArray) foreign).d()); // data + } else if (foreign instanceof NBTTagLongArray) { + return new LongArrayTag(((NBTTagLongArray) foreign).d()); // data } else if (foreign instanceof NBTTagList) { try { return toNativeList((NBTTagList) foreign); @@ -430,13 +418,13 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit return new ListTag(ByteTag.class, new ArrayList()); } } else if (foreign instanceof NBTTagLong) { - return new LongTag(((NBTTagLong) foreign).asLong()); // getLong + return new LongTag(((NBTTagLong) foreign).asLong()); } else if (foreign instanceof NBTTagShort) { - return new ShortTag(((NBTTagShort) foreign).asShort()); // getShort + return new ShortTag(((NBTTagShort) foreign).asShort()); } else if (foreign instanceof NBTTagString) { - return new StringTag(foreign.asString()); // data + return new StringTag(foreign.asString()); } else if (foreign instanceof NBTTagEnd) { - return EndTag.INSTANCE; + return new EndTag(); } else { throw new IllegalArgumentException("Don't know how to make native " + foreign.getClass().getCanonicalName()); } @@ -454,7 +442,7 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit */ public ListTag toNativeList(NBTTagList foreign) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { List values = new ArrayList<>(); - int type = foreign.getTypeId(); + int type = foreign.d(); List foreignList; foreignList = (List) nbtListTagListField.get(foreign); @@ -497,9 +485,11 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit return new NBTTagInt(((IntTag) foreign).getValue()); } else if (foreign instanceof IntArrayTag) { return new NBTTagIntArray(((IntArrayTag) foreign).getValue()); + } else if (foreign instanceof LongArrayTag) { + return new NBTTagLongArray(((LongArrayTag) foreign).getValue()); } else if (foreign instanceof ListTag) { NBTTagList tag = new NBTTagList(); - ListTag foreignList = (ListTag) foreign; + ListTag foreignList = (ListTag) foreign; for (Tag t : foreignList.getValue()) { tag.add(fromNative(t)); } @@ -539,4 +529,26 @@ public final class Spigot_v1_13_R2 extends CachedBukkitAdapter implements Bukkit BlockMaterial_1_13 material = (BlockMaterial_1_13) state.getMaterial(); return material.getCraftBlockData(); } -} \ No newline at end of file + + @Override + public void sendFakeNBT(Player player, BlockVector3 pos, CompoundTag nbtData) { + // TODO Auto-generated method stub + + } + + @Override + public void notifyAndLightBlock(Location position, BlockState previousType) { + this.setBlock(position.getChunk(), position.getBlockX(), position.getBlockY(), position.getBlockZ(), previousType, true); + } + + @Override + public boolean setBlock(Location location, BlockStateHolder state, boolean notifyAndLight) { + return this.setBlock(location.getChunk(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), state, notifyAndLight); + } + + @Override + public void sendFakeOP(Player player) { + // TODO Auto-generated method stub + + } +} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/JsonString.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/JsonString.java index e59fb2e70..115bdf66e 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/JsonString.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/JsonString.java @@ -29,7 +29,7 @@ final class JsonString implements JsonRepresentedObject, ConfigurationSerializab } public Map serialize() { - HashMap theSingleValue = new HashMap(); + HashMap theSingleValue = new HashMap<>(); theSingleValue.put("stringValue", _value); return theSingleValue; } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/Reflection.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/Reflection.java index d0e7b60c7..17e5e4280 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/Reflection.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/chat/Reflection.java @@ -177,12 +177,12 @@ public final class Reflection { */ public synchronized static Method getMethod(Class clazz, String name, Class... args) { if (!_loadedMethods.containsKey(clazz)) { - _loadedMethods.put(clazz, new HashMap>, Method>>()); + _loadedMethods.put(clazz, new HashMap<>()); } Map>, Method>> loadedMethodNames = _loadedMethods.get(clazz); if (!loadedMethodNames.containsKey(name)) { - loadedMethodNames.put(name, new HashMap>, Method>()); + loadedMethodNames.put(name, new HashMap<>()); } Map>, Method> loadedSignatures = loadedMethodNames.get(name); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/filter/GriefPreventionFilter.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/filter/GriefPreventionFilter.java index a67438547..1f49830de 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/filter/GriefPreventionFilter.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/filter/GriefPreventionFilter.java @@ -1,9 +1,10 @@ package com.boydti.fawe.bukkit.filter; +import com.boydti.fawe.object.RunnableVal; import com.boydti.fawe.regions.general.CuboidRegionFilter; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.TaskManager; -import com.sk89q.worldedit.BlockVector2D; +import com.boydti.fawe.util.TaskManager; +import com.sk89q.worldedit.math.BlockVector2; + import java.util.ArrayDeque; import java.util.Collection; import me.ryanhamshire.GriefPrevention.Claim; @@ -34,8 +35,8 @@ public class GriefPreventionFilter extends CuboidRegionFilter { org.bukkit.Location bot = claim.getGreaterBoundaryCorner(); if (world.equals(bot.getWorld())) { org.bukkit.Location top = claim.getGreaterBoundaryCorner(); - BlockVector2D pos1 = new BlockVector2D(bot.getBlockX(), bot.getBlockZ()); - BlockVector2D pos2 = new BlockVector2D(top.getBlockX(), top.getBlockZ()); + BlockVector2 pos1 = BlockVector2.at(bot.getBlockX(), bot.getBlockZ()); + BlockVector2 pos2 = BlockVector2.at(top.getBlockX(), top.getBlockZ()); add(pos1, pos2); } } 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 e9b8a6bf3..b195a9368 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 @@ -5,7 +5,7 @@ import com.boydti.fawe.FaweAPI; import com.boydti.fawe.object.RunnableVal; import com.boydti.fawe.regions.general.CuboidRegionFilter; import com.boydti.fawe.util.TaskManager; -import com.sk89q.worldedit.BlockVector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.ApplicableRegionSet; @@ -33,14 +33,14 @@ public class WorldGuardFilter extends CuboidRegionFilter { public void run(Object value) { WorldGuardFilter.this.manager = WorldGuard.getInstance().getPlatform().getRegionContainer().get(FaweAPI.getWorld(world.getName())); for (ProtectedRegion region : manager.getRegions().values()) { - BlockVector min = region.getMinimumPoint(); - BlockVector max = region.getMaximumPoint(); + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); if (max.getBlockX() - min.getBlockX() > 1024 || max.getBlockZ() - min.getBlockZ() > 1024) { Fawe.debug("Large or complex region shapes cannot be optimized. Filtering will be slower"); large = true; break; } - add(min.toVector2D(), max.toVector2D()); + add(min.toBlockVector2(), max.toBlockVector2()); } } }); @@ -49,8 +49,8 @@ public class WorldGuardFilter extends CuboidRegionFilter { @Override public boolean containsChunk(int chunkX, int chunkZ) { if (!large) return super.containsChunk(chunkX, chunkZ); - BlockVector pos1 = new BlockVector(chunkX << 4, 0, chunkZ << 4); - BlockVector pos2 = new BlockVector(pos1.getBlockX() + 15, 255, pos1.getBlockZ() + 15); + 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); ApplicableRegionSet set = manager.getApplicableRegions(chunkRegion); return set.size() > 0 && !set.getRegions().iterator().next().getId().equals("__global__"); @@ -59,8 +59,8 @@ public class WorldGuardFilter extends CuboidRegionFilter { @Override public boolean containsRegion(int mcaX, int mcaZ) { if (!large) return super.containsRegion(mcaX, mcaZ); - BlockVector pos1 = new BlockVector(mcaX << 9, 0, mcaZ << 9); - BlockVector pos2 = new BlockVector(pos1.getBlockX() + 511, 255, pos1.getBlockZ() + 511); + 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); ApplicableRegionSet set = manager.getApplicableRegions(regionRegion); return set.size() > 0 && !set.getRegions().iterator().next().getId().equals("__global__"); 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 68bb97377..e175ff1d5 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 @@ -14,6 +14,9 @@ import com.sk89q.worldedit.*; 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.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; + import java.util.ArrayDeque; import java.util.Collection; import java.util.Iterator; @@ -69,7 +72,7 @@ public class BukkitImageListener implements Listener { String name = player.getName().toLowerCase(); if (!event.getMessage().toLowerCase().contains(name)) { ArrayDeque buffered = fp.getMeta("CFIBufferedMessages"); - if (buffered == null) fp.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque()); + if (buffered == null) fp.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque<>()); String full = String.format(event.getFormat(), event.getPlayer().getDisplayName(), event.getMessage()); buffered.add(full); iter.remove(); @@ -100,7 +103,7 @@ public class BukkitImageListener implements Listener { if (event.getHand() == EquipmentSlot.OFF_HAND) return; } catch (NoSuchFieldError | NoSuchMethodError ignored) {} - List target = player.getLastTwoTargetBlocks((Set) null, 100); + List target = player.getLastTwoTargetBlocks(null, 100); if (target.isEmpty()) return; Block targetBlock = target.get(0); @@ -148,7 +151,7 @@ public class BukkitImageListener implements Listener { if (generator == null) return null; ImageViewer viewer = generator.getImageViewer(); - if (viewer == null || !(viewer instanceof BukkitImageViewer)) return null; + if (!(viewer instanceof BukkitImageViewer)) return null; BukkitImageViewer biv = (BukkitImageViewer) viewer; return biv; @@ -182,12 +185,7 @@ public class BukkitImageListener implements Listener { if (frames == null || tool == null) { viewer.selectFrame(itemFrame); player.updateInventory(); - TaskManager.IMP.laterAsync(new Runnable() { - @Override - public void run() { - viewer.view(generator); - } - }, 1); + TaskManager.IMP.laterAsync(() -> viewer.view(generator), 1); return; } @@ -246,27 +244,24 @@ public class BukkitImageListener implements Listener { if (worldX < 0 || worldX > width || worldZ < 0 || worldZ > length) return; - Vector wPos = new Vector(worldX, 0, worldZ); - fp.runAction(new Runnable() { - @Override - public void run() { - viewer.refresh(); - int topY = generator.getNearestSurfaceTerrainBlock(wPos.getBlockX(), wPos.getBlockZ(), 255, 0, 255); - wPos.mutY(topY); + fp.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(fp.getWorld()).player(fp).combineStages(false).autoQueue(false).blockBag(null).limitUnlimited().build(); - ExtentTraverser last = new ExtentTraverser(es.getExtent()).last(); - if (last.get() instanceof FastWorldEditExtent) 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); + EditSession es = new EditSessionBuilder(fp.getWorld()).player(fp).combineStages(false).autoQueue(false).blockBag(null).limitUnlimited().build(); + ExtentTraverser last = new ExtentTraverser(es.getExtent()).last(); + if (last.get() instanceof FastWorldEditExtent) 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); @@ -277,4 +272,4 @@ public class BukkitImageListener implements Listener { } } } -} \ No newline at end of file +} 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 f5e2fe05c..2053d8f9c 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,15 +22,16 @@ import com.comphenix.protocol.wrappers.ChunkCoordIntPair; import com.comphenix.protocol.wrappers.EnumWrappers; import com.comphenix.protocol.wrappers.WrappedBlockData; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.bukkit.BukkitAdapter; 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 java.lang.reflect.InvocationTargetException; import java.util.List; @@ -62,12 +63,12 @@ public class CFIPacketListener implements Listener { this.protocolmanager = ProtocolLibrary.getProtocolManager(); // Direct digging to the virtual world - registerBlockEvent(PacketType.Play.Client.BLOCK_DIG, false, new RunnableVal3() { + registerBlockEvent(PacketType.Play.Client.BLOCK_DIG, false, new RunnableVal3() { @Override - public void run(PacketEvent event, VirtualWorld gen, Vector pt) { + public void run(PacketEvent event, VirtualWorld gen, BlockVector3 pt) { try { Player plr = event.getPlayer(); - Vector realPos = pt.add(gen.getOrigin()); + BlockVector3 realPos = pt.add(gen.getOrigin().toBlockPoint()); if (!sendBlockChange(plr, gen, pt, Interaction.HIT)) { gen.setBlock(pt, EditSession.nullBlock); } @@ -78,9 +79,9 @@ public class CFIPacketListener implements Listener { }); // Direct placing to the virtual world - RunnableVal3 placeTask = new RunnableVal3() { + RunnableVal3 placeTask = new RunnableVal3() { @Override - public void run(PacketEvent event, VirtualWorld gen, Vector pt) { + public void run(PacketEvent event, VirtualWorld gen, BlockVector3 pt) { try { Player plr = event.getPlayer(); List hands = event.getPacket().getHands().getValues(); @@ -89,17 +90,13 @@ public class CFIPacketListener implements Listener { PlayerInventory inv = plr.getInventory(); ItemStack hand = enumHand == EnumWrappers.Hand.MAIN_HAND ? inv.getItemInMainHand() : inv.getItemInOffHand(); if (hand != null && hand.getType().isBlock()) { - switch (hand.getType()) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - break; - default: - BlockStateHolder block = BukkitAdapter.asBlockState(hand); - if (block != null) { - gen.setBlock(pt, block); - return; - } + Material type = hand.getType(); + if (!type.isEmpty()) { + BlockStateHolder block = BukkitAdapter.asBlockState(hand); + if (block != null) { + gen.setBlock(pt, block); + return; + } } } pt = getRelPos(event, gen); @@ -113,9 +110,9 @@ public class CFIPacketListener implements Listener { registerBlockEvent(PacketType.Play.Client.USE_ITEM, true, placeTask); // Cancel block change packets where the real world overlaps with the virtual one - registerBlockEvent(PacketType.Play.Server.BLOCK_CHANGE, false, new RunnableVal3() { + registerBlockEvent(PacketType.Play.Server.BLOCK_CHANGE, false, new RunnableVal3() { @Override - public void run(PacketEvent event, VirtualWorld gen, Vector pt) { + public void run(PacketEvent event, VirtualWorld gen, BlockVector3 pt) { // Do nothing } }); @@ -128,7 +125,7 @@ public class CFIPacketListener implements Listener { VirtualWorld gen = getGenerator(event); if (gen != null) { - Vector origin = gen.getOrigin(); + BlockVector3 origin = gen.getOrigin().toBlockPoint(); PacketContainer packet = event.getPacket(); StructureModifier ints = packet.getIntegers(); int cx = ints.read(0); @@ -137,7 +134,7 @@ public class CFIPacketListener implements Listener { int ocx = origin.getBlockX() >> 4; int ocz = origin.getBlockZ() >> 4; - if (gen.contains(new Vector((cx - ocx) << 4, 0, (cz - ocz) << 4))) { + if (gen.contains(BlockVector3.at((cx - ocx) << 4, 0, (cz - ocz) << 4))) { event.setCancelled(true); Player plr = event.getPlayer(); @@ -163,8 +160,8 @@ public class CFIPacketListener implements Listener { Location pos = player.getLocation(); VirtualWorld gen = getGenerator(event); if (gen != null) { - Vector origin = gen.getOrigin(); - Vector pt = new Vector(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); + BlockVector3 origin = gen.getOrigin().toBlockPoint(); + BlockVector3 pt = BlockVector3.at(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); StructureModifier ints = event.getPacket().getIntegers(); int id = ints.read(0); @@ -188,21 +185,19 @@ public class CFIPacketListener implements Listener { Location pos = player.getLocation(); VirtualWorld gen = getGenerator(event); if (gen != null) { - Vector origin = gen.getOrigin(); - Vector from = new Vector(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); + BlockVector3 origin = gen.getOrigin().toBlockPoint(); + BlockVector3 from = BlockVector3.at(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); PacketContainer packet = event.getPacket(); StructureModifier doubles = packet.getDoubles(); - Vector to = new Vector(doubles.read(0), doubles.read(1), doubles.read(2)); + BlockVector3 to = BlockVector3.at(doubles.read(0), doubles.read(1), doubles.read(2)); if (gen.contains(to.subtract(origin)) && from.distanceSq(to) < 8) { int id = packet.getIntegers().read(0); PacketContainer reply = new PacketContainer(PacketType.Play.Client.TELEPORT_ACCEPT); reply.getIntegers().write(0, id); try { protocolmanager.recieveClientPacket(player, reply); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { + } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } event.setCancelled(true); @@ -220,10 +215,10 @@ public class CFIPacketListener implements Listener { if (gen != null) { PacketContainer packet = event.getPacket(); ChunkCoordIntPair chunk = packet.getChunkCoordIntPairs().read(0); - Vector origin = gen.getOrigin(); + BlockVector3 origin = gen.getOrigin().toBlockPoint(); int cx = chunk.getChunkX() - (origin.getBlockX() >> 4); int cz = chunk.getChunkZ() - (origin.getBlockX() >> 4); - if (gen.contains(new Vector(cx << 4, 0, cz << 4))) { + if (gen.contains(BlockVector3.at(cx << 4, 0, cz << 4))) { event.setCancelled(true); } } @@ -246,14 +241,14 @@ public class CFIPacketListener implements Listener { } } - private boolean sendBlockChange(Player plr, VirtualWorld gen, Vector pt, Interaction action) { + private boolean sendBlockChange(Player plr, VirtualWorld gen, BlockVector3 pt, Interaction action) { PlatformManager platform = WorldEdit.getInstance().getPlatformManager(); com.sk89q.worldedit.entity.Player actor = FawePlayer.wrap(plr).getPlayer(); - com.sk89q.worldedit.util.Location location = new com.sk89q.worldedit.util.Location(actor.getWorld(), pt); + com.sk89q.worldedit.util.Location location = new com.sk89q.worldedit.util.Location(actor.getWorld(), pt.toVector3()); BlockInteractEvent toCall = new BlockInteractEvent(actor, location, action); platform.handleBlockInteract(toCall); if (toCall.isCancelled() || action == Interaction.OPEN) { - Vector realPos = pt.add(gen.getOrigin()); + BlockVector3 realPos = pt.add(gen.getOrigin().toBlockPoint()); BlockStateHolder block = gen.getBlock(pt); sendBlockChange(plr, realPos, block); return true; @@ -261,7 +256,7 @@ public class CFIPacketListener implements Listener { return false; } - private void sendBlockChange(Player plr, Vector pt, BlockStateHolder block) { + private void sendBlockChange(Player plr, BlockVector3 pt, BlockStateHolder block) { plr.sendBlockChange(new Location(plr.getWorld(), pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()), BukkitAdapter.adapt(block)); } @@ -280,20 +275,20 @@ public class CFIPacketListener implements Listener { return null; } - private Vector getRelPos(PacketEvent event, VirtualWorld generator) { + private BlockVector3 getRelPos(PacketEvent event, VirtualWorld generator) { PacketContainer packet = event.getPacket(); StructureModifier position = packet.getBlockPositionModifier(); BlockPosition loc = position.readSafely(0); if (loc == null) return null; - Vector origin = generator.getOrigin(); - Vector pt = new Vector(loc.getX() - origin.getBlockX(), loc.getY() - origin.getBlockY(), loc.getZ() - origin.getBlockZ()); + BlockVector3 origin = generator.getOrigin().toBlockPoint(); + BlockVector3 pt = BlockVector3.at(loc.getX() - origin.getBlockX(), loc.getY() - origin.getBlockY(), loc.getZ() - origin.getBlockZ()); return pt; } - private void handleBlockEvent(PacketEvent event, boolean relative, RunnableVal3 task) { + private void handleBlockEvent(PacketEvent event, boolean relative, RunnableVal3 task) { VirtualWorld gen = getGenerator(event); if (gen != null) { - Vector pt = getRelPos(event, gen); + BlockVector3 pt = getRelPos(event, gen); if (pt != null) { if (relative) pt = getRelative(event, pt); if (gen.contains(pt)) { @@ -304,7 +299,7 @@ public class CFIPacketListener implements Listener { } } - private void registerBlockEvent(PacketType type, boolean relative, RunnableVal3 task) { + private void registerBlockEvent(PacketType type, boolean relative, RunnableVal3 task) { protocolmanager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.NORMAL, type) { @Override public void onPacketReceiving(final PacketEvent event) { @@ -318,7 +313,7 @@ public class CFIPacketListener implements Listener { }); } - private Vector getRelative(PacketEvent container, Vector pt) { + private BlockVector3 getRelative(PacketEvent container, BlockVector3 pt) { PacketContainer packet = container.getPacket(); StructureModifier dirs = packet.getDirections(); EnumWrappers.Direction dir = dirs.readSafely(0); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/BukkitMask.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/BukkitMask.java index 701cd3e30..54e9f0bc9 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/BukkitMask.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/BukkitMask.java @@ -1,7 +1,8 @@ package com.boydti.fawe.bukkit.regions; import com.boydti.fawe.regions.FaweMask; -import com.sk89q.worldedit.BlockVector; +import com.sk89q.worldedit.math.BlockVector3; + import org.bukkit.Location; public class BukkitMask extends FaweMask { @@ -11,6 +12,6 @@ public class BukkitMask extends FaweMask { } public BukkitMask(Location pos1, Location pos2, String name) { - super(new BlockVector(pos1.getBlockX(), pos1.getBlockY(), pos1.getBlockZ()), new BlockVector(pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ()), name); + super(BlockVector3.at(pos1.getBlockX(), pos1.getBlockY(), pos1.getBlockZ()), BlockVector3.at(pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ()), name); } } \ No newline at end of file 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 1ef42cdcb..e1aa7bbc9 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 @@ -5,8 +5,8 @@ import com.boydti.fawe.bukkit.wrapper.AsyncWorld; import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.queue.NullFaweQueue; import com.boydti.fawe.regions.FaweMask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.block.BlockTypes; @@ -55,8 +55,8 @@ public class FreeBuildRegion extends BukkitMaskManager { World bukkitWorld = player.parent.getWorld(); AsyncWorld asyncWorld = AsyncWorld.wrap(bukkitWorld); - Vector vec1 = new Vector(0, 0, 0); - Vector vec2 = vec1; + BlockVector3 vec1 = BlockVector3.at(0, 0, 0); + BlockVector3 vec2 = vec1; Location pos1 = BukkitAdapter.adapt(bukkitWorld, vec1); Location pos2 = BukkitAdapter.adapt(bukkitWorld, vec2); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/PlotMeFeature.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/PlotMeFeature.java deleted file mode 100644 index ee57961a9..000000000 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/PlotMeFeature.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.boydti.fawe.bukkit.regions; - -import com.boydti.fawe.bukkit.FaweBukkit; -import com.boydti.fawe.object.FawePlayer; -import com.worldcretornica.plotme_core.Plot; -import com.worldcretornica.plotme_core.PlotMe_Core; -import com.worldcretornica.plotme_core.bukkit.PlotMe_CorePlugin; -import com.worldcretornica.plotme_core.bukkit.api.BukkitPlayer; -import com.worldcretornica.plotme_core.bukkit.api.BukkitWorld; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; -import org.bukkit.plugin.Plugin; - -public class PlotMeFeature extends BukkitMaskManager implements Listener { - FaweBukkit plugin; - PlotMe_Core plotme; - - public PlotMeFeature(final Plugin plotmePlugin, final FaweBukkit p3) { - super(plotmePlugin.getName()); - this.plotme = ((PlotMe_CorePlugin) plotmePlugin).getAPI(); - this.plugin = p3; - - } - public boolean isAllowed(Player player, Plot plot, MaskType type) { - return plot != null && type == MaskType.MEMBER ? plot.isAllowed(player.getUniqueId()) : player.getUniqueId().equals(plot.getOwnerId()); - } - - @Override - public BukkitMask getMask(final FawePlayer fp, MaskType type) { - final Player player = fp.parent; - final Location location = player.getLocation(); - final Plot plot = this.plotme.getPlotMeCoreManager().getPlotById(new BukkitPlayer(player)); - if (plot == null) { - return null; - } - if (isAllowed(player, plot, type)) { - final Location pos1 = new Location(location.getWorld(), this.plotme.getGenManager(player.getWorld().getName()).bottomX(plot.getId(), new BukkitWorld(player.getWorld())), 0, this.plotme - .getGenManager(player.getWorld().getName()).bottomZ(plot.getId(), new BukkitWorld(player.getWorld()))); - final Location pos2 = new Location(location.getWorld(), this.plotme.getGenManager(player.getWorld().getName()).topX(plot.getId(), new BukkitWorld(player.getWorld())), 256, this.plotme - .getGenManager(player.getWorld().getName()).topZ(plot.getId(), new BukkitWorld(player.getWorld()))); - return new BukkitMask(pos1, pos2) { - @Override - public String getName() { - return plot.getId(); - } - - @Override - public boolean isValid(FawePlayer player, MaskType type) { - return isAllowed((Player) player.parent, plot, type); - } - }; - } - return null; - } -} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/PreciousStonesFeature.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/PreciousStonesFeature.java index dccb3952a..7b0af05b5 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/PreciousStonesFeature.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/PreciousStonesFeature.java @@ -3,7 +3,8 @@ package com.boydti.fawe.bukkit.regions; import com.boydti.fawe.bukkit.FaweBukkit; import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.regions.FaweMask; -import com.sk89q.worldedit.BlockVector; +import com.sk89q.worldedit.math.BlockVector3; + import java.util.List; import net.sacredlabyrinth.Phaed.PreciousStones.PreciousStones; import net.sacredlabyrinth.Phaed.PreciousStones.field.Field; @@ -40,8 +41,8 @@ public class PreciousStonesFeature extends BukkitMaskManager implements Listener boolean member = fp.hasPermission("fawe.preciousstones.member"); for (final Field myField : fields) { if (isAllowed(player, myField, type, member)) { - BlockVector pos1 = new BlockVector(myField.getMinx(), myField.getMiny(), myField.getMinz()); - BlockVector pos2 = new BlockVector(myField.getMaxx(), myField.getMaxy(), myField.getMaxz()); + BlockVector3 pos1 = BlockVector3.at(myField.getMinx(), myField.getMiny(), myField.getMinz()); + BlockVector3 pos2 = BlockVector3.at(myField.getMaxx(), myField.getMaxy(), myField.getMaxz()); return new FaweMask(pos1, pos2, "FIELD: " + myField) { @Override public boolean isValid(FawePlayer player, MaskType type) { 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 156753f4a..cb7a91675 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 @@ -7,8 +7,8 @@ import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.RegionWrapper; import com.boydti.fawe.regions.FaweMask; import com.boydti.fawe.regions.general.RegionFilter; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.AbstractRegion; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Polygonal2DRegion; @@ -61,7 +61,7 @@ public class Worldguard extends BukkitMaskManager implements Listener { if (global != null && isAllowed(player, global)) { return global; } - final ApplicableRegionSet regions = manager.getApplicableRegions(new Vector(loc.getX(), loc.getY(), loc.getZ())); + final ApplicableRegionSet regions = manager.getApplicableRegions(BlockVector3.at(loc.getX(), loc.getY(), loc.getZ())); for (final ProtectedRegion region : regions) { if (isAllowed(player, region)) { return region; @@ -145,27 +145,27 @@ public class Worldguard extends BukkitMaskManager implements Listener { } @Override - public Vector getMinimumPoint() { + public BlockVector3 getMinimumPoint() { return region.getMinimumPoint(); } @Override - public Vector getMaximumPoint() { + public BlockVector3 getMaximumPoint() { return region.getMaximumPoint(); } @Override - public void expand(Vector... changes) { + public void expand(BlockVector3... changes) { throw new UnsupportedOperationException("Region is immutable"); } @Override - public void contract(Vector... changes) { + public void contract(BlockVector3... changes) { throw new UnsupportedOperationException("Region is immutable"); } @Override - public boolean contains(Vector position) { + public boolean contains(BlockVector3 position) { return region.contains(position); } } @@ -179,8 +179,8 @@ public class Worldguard extends BukkitMaskManager implements Listener { } if (region instanceof ProtectedPolygonalRegion) { ProtectedPolygonalRegion casted = (ProtectedPolygonalRegion) region; - BlockVector max = region.getMaximumPoint(); - BlockVector min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); + BlockVector3 min = region.getMinimumPoint(); return new Polygonal2DRegion(null, casted.getPoints(), min.getBlockY(), max.getBlockY()); } return new AdaptedRegion(region); diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/WorldguardFlag.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/WorldguardFlag.java index 21e673f41..3f3f1a842 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/WorldguardFlag.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/regions/WorldguardFlag.java @@ -5,7 +5,7 @@ import com.boydti.fawe.bukkit.filter.WorldGuardFilter; import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.regions.FaweMask; import com.boydti.fawe.regions.general.RegionFilter; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.AbstractRegion; import com.sk89q.worldguard.LocalPlayer; import com.sk89q.worldguard.WorldGuard; @@ -65,45 +65,45 @@ public class WorldguardFlag extends BukkitMaskManager implements Listener { } @Override - public Vector getMinimumPoint() { - Vector point = null; + public BlockVector3 getMinimumPoint() { + BlockVector3 point = null; for (Map.Entry entry : manager.getRegions().entrySet()) { - Vector p = entry.getValue().getMinimumPoint(); + BlockVector3 p = entry.getValue().getMinimumPoint(); if (point == null) { point = p; continue; } - point = Vector.getMinimum(point, p); + point = point.getMinimum(p); } return point; } @Override - public Vector getMaximumPoint() { - Vector point = null; + public BlockVector3 getMaximumPoint() { + BlockVector3 point = null; for (Map.Entry entry : manager.getRegions().entrySet()) { - Vector p = entry.getValue().getMaximumPoint(); + BlockVector3 p = entry.getValue().getMaximumPoint(); if (point == null) { point = p; continue; } - point = Vector.getMaximum(point, p); + point = point.getMaximum(p); } return point; } @Override - public void expand(Vector... changes) { + public void expand(BlockVector3... changes) { throw new UnsupportedOperationException("Region is immutable"); } @Override - public void contract(Vector... changes) { + public void contract(BlockVector3... changes) { throw new UnsupportedOperationException("Region is immutable"); } @Override - public boolean contains(Vector position) { + public boolean contains(BlockVector3 position) { // Make sure that all these flags are not denied. Denies override allows. WorldGuardExtraFlags can add Flags.WORLDEDIT return manager.getApplicableRegions(position).testState(localplayer, Flags.BUILD, Flags.BLOCK_PLACE, Flags.BLOCK_BREAK); } 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 df5f92f87..28015ebb0 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 @@ -69,7 +69,7 @@ public class ItemUtil { if (nativeTag != null) return (CompoundTag) nativeTag; } Tag nativeTag = BukkitQueue_0.toNative(nmsTag); - map.put(nmsTag.hashCode(), new WeakReference(nativeTag)); + map.put(nmsTag.hashCode(), new WeakReference<>(nativeTag)); return null; } } catch (Throwable e) { diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/VaultUtil.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/VaultUtil.java index dfc2cde83..4d0751c94 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/VaultUtil.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/VaultUtil.java @@ -8,7 +8,8 @@ public class VaultUtil { public final Permission permission; public VaultUtil() { - final RegisteredServiceProvider permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); + final RegisteredServiceProvider permissionProvider = + Bukkit.getServer().getServicesManager().getRegistration(Permission.class); if (permissionProvider != null) { this.permission = permissionProvider.getProvider(); } else { diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/StructureCUI.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/StructureCUI.java index 15a397bf8..b1e389cc6 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/StructureCUI.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/util/cui/StructureCUI.java @@ -13,11 +13,12 @@ import com.comphenix.protocol.wrappers.BlockPosition; import com.comphenix.protocol.wrappers.nbt.NbtBase; import com.comphenix.protocol.wrappers.nbt.NbtCompound; import com.comphenix.protocol.wrappers.nbt.NbtFactory; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.internal.cui.CUIEvent; import com.sk89q.worldedit.internal.cui.SelectionPointEvent; import com.sk89q.worldedit.internal.cui.SelectionShapeEvent; +import com.sk89q.worldedit.math.BlockVector3; + import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; @@ -33,10 +34,10 @@ import org.bukkit.entity.Player; public class StructureCUI extends CUI { private boolean cuboid = true; - private Vector pos1; - private Vector pos2; + private BlockVector3 pos1; + private BlockVector3 pos2; - private Vector remove; + private BlockVector3 remove; private NbtCompound removeTag; private BlockState state; @@ -56,7 +57,7 @@ public class StructureCUI extends CUI { int x = Integer.parseInt(param[1]); int y = Integer.parseInt(param[2]); int z = Integer.parseInt(param[3]); - Vector pos = new Vector(x, y, z); + BlockVector3 pos = BlockVector3.at(x, y, z); if (id == 0) { pos1 = pos; } else { @@ -123,7 +124,7 @@ public class StructureCUI extends CUI { } } - private void sendNbt(Vector pos, NbtCompound compound) { + private void sendNbt(BlockVector3 pos, NbtCompound compound) { Player player = this.getPlayer().parent; ProtocolManager manager = ProtocolLibrary.getProtocolManager(); @@ -158,8 +159,8 @@ public class StructureCUI extends CUI { remove = null; } if (pos1 == null || pos2 == null) return; - Vector min = Vector.getMinimum(pos1, pos2); - Vector max = Vector.getMaximum(pos1, pos2); + BlockVector3 min = pos1.getMinimum(pos2); + BlockVector3 max = pos1.getMaximum(pos2); // Position double rotX = playerLoc.getYaw(); @@ -187,7 +188,7 @@ public class StructureCUI extends CUI { NbtCompound compound = constructStructureNbt(x, y, z, posX, posY, posZ, sizeX, sizeY, sizeZ); Block block = player.getWorld().getBlockAt(x, y, z); - remove = new Vector(x, y, z); + remove = BlockVector3.at(x, y, z); state = BukkitAdapter.adapt(block.getBlockData()); removeTag = compound; diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitChunk_All.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitChunk_All.java index 79a039f96..96483b7c5 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitChunk_All.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitChunk_All.java @@ -13,7 +13,6 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.ListTag; import com.sk89q.jnbt.LongTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.entity.BaseEntity; @@ -23,6 +22,8 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; @@ -103,7 +104,7 @@ public class BukkitChunk_All extends IntFaweChunk { int[][] sections = getCombinedIdArrays(); final int bx = getX() << 4; final int bz = getZ() << 4; - boolean update = adapter != null ? adapter.isChunkInUse(chunk) : true; + boolean update = adapter == null || adapter.isChunkInUse(chunk); if (layer == -1) { if (adapter != null) { @@ -157,7 +158,7 @@ public class BukkitChunk_All extends IntFaweChunk { HashSet entsToRemove = this.getEntityRemoves(); if (!entsToRemove.isEmpty()) { for (Entity entity : chunk.getEntities()) { - if (entsToRemove.contains(entity.getUniqueId())) { + if (entsToRemove.contains(entity.getUniqueId()) && !(entity instanceof Player)) { entity.remove(); } } @@ -232,43 +233,40 @@ public class BukkitChunk_All extends IntFaweChunk { if (combined == 0) continue; int xx = bx + x; - BlockTypes type = BlockTypes.getFromStateId(combined); + BlockType type = BlockTypes.getFromStateId(combined); if (type == BlockTypes.__RESERVED__) continue; - switch (type) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - if (!place) { - mutableLoc.setX(xx); - mutableLoc.setY(yy); - mutableLoc.setZ(zz); + String s = type.getResource().toUpperCase(); + if (type.getMaterial().isAir()) { + if (!place) { + mutableLoc.setX(xx); + mutableLoc.setY(yy); + mutableLoc.setZ(zz); + setBlock(adapter, chunk, mutableLoc, combined, update); + } + continue; + } + if (place) { + if (type.getMaterial().hasContainer() && adapter != null) { + CompoundTag nbt = getTile(x, yy, z); + if (nbt != null) { + synchronized (BukkitChunk_All.this) { + BaseBlock state = + BaseBlock.getFromInternalId(combined, nbt); + adapter.setBlock(chunk, xx, yy, zz, state, update); + } + continue; + } + } + if (type.getMaterial().isTicksRandomly()) { + synchronized (BukkitChunk_All.this) { setBlock(adapter, chunk, mutableLoc, combined, update); } - continue; - default: - if (place) { - if (type.getMaterial().hasContainer() && adapter != null) { - CompoundTag nbt = getTile(x, yy, z); - if (nbt != null) { - synchronized (BukkitChunk_All.this) { - BaseBlock state = BaseBlock.getFromInternalId(combined, nbt); - adapter.setBlock(chunk, xx, yy, zz, state, update); - } - continue; - } - } - if (type.getMaterial().isTicksRandomly()) { - synchronized (BukkitChunk_All.this) { - setBlock(adapter, chunk, mutableLoc, combined, update); - } - } else { - mutableLoc.setX(xx); - mutableLoc.setY(yy); - mutableLoc.setZ(zz); - setBlock(adapter, chunk, mutableLoc, combined, update); - } - } - continue; + } else { + mutableLoc.setX(xx); + mutableLoc.setY(yy); + mutableLoc.setZ(zz); + setBlock(adapter, chunk, mutableLoc, combined, update); + } } } } @@ -277,65 +275,61 @@ public class BukkitChunk_All extends IntFaweChunk { for (;index < 4096; index++) { int j = place ? index : 4095 - index; int combined = newArray[j]; - BlockTypes type = BlockTypes.getFromStateId(combined); + BlockType type = BlockTypes.getFromStateId(combined); if (type == BlockTypes.__RESERVED__) continue; - switch (type) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - if (!place) { - int x = cacheX[j]; - int z = cacheZ[j]; - int y = cacheY[j]; - mutableLoc.setX(bx + x); - mutableLoc.setY(y); - mutableLoc.setZ(bz + z); - setBlock(adapter, chunk, mutableLoc, combined, update); - } - break; - default: - boolean light = type.getMaterial().getLightValue() > 0; - if (light) { - if (place) { - continue; - } - light = light && getParent().getSettings().LIGHTING.MODE != 0; - if (light) { - parent.enableLighting(disableResult); - } - } else if (!place) { - continue; - } + if (type.getMaterial().isAir()) { + if (!place) { int x = cacheX[j]; int z = cacheZ[j]; int y = cacheY[j]; - if (type.getMaterial().hasContainer() && adapter != null) { - CompoundTag tile = getTile(x, y, z); - if (tile != null) { - synchronized (BukkitChunk_All.this) { - BaseBlock state = BaseBlock.getFromInternalId(combined, tile); - adapter.setBlock(chunk, bx + x, y, bz + z, state, update); - } - break; - } + mutableLoc.setX(bx + x); + mutableLoc.setY(y); + mutableLoc.setZ(bz + z); + setBlock(adapter, chunk, mutableLoc, combined, update); + } + continue; + } else { + boolean light = type.getMaterial().getLightValue() > 0; + if (light) { + if (place) { + continue; } - if (type.getMaterial().isTicksRandomly()) { + light = light && getParent().getSettings().LIGHTING.MODE != 0; + if (light) { + parent.enableLighting(disableResult); + } + } else if (!place) { + continue; + } + int x = cacheX[j]; + int z = cacheZ[j]; + int y = cacheY[j]; + if (type.getMaterial().hasContainer() && adapter != null) { + CompoundTag tile = getTile(x, y, z); + if (tile != null) { synchronized (BukkitChunk_All.this) { - mutableLoc.setX(bx + x); - mutableLoc.setY(y); - mutableLoc.setZ(bz + z); - setBlock(adapter, chunk, mutableLoc, combined, update); + BaseBlock state = BaseBlock.getFromInternalId(combined, tile); + adapter.setBlock(chunk, bx + x, y, bz + z, state, update); } - } else { + break; + } + } + if (type.getMaterial().isTicksRandomly()) { + synchronized (BukkitChunk_All.this) { mutableLoc.setX(bx + x); mutableLoc.setY(y); mutableLoc.setZ(bz + z); setBlock(adapter, chunk, mutableLoc, combined, update); } - if (light) { - parent.disableLighting(disableResult); - } - break; + } else { + mutableLoc.setX(bx + x); + mutableLoc.setY(y); + mutableLoc.setZ(bz + z); + setBlock(adapter, chunk, mutableLoc, combined, update); + } + if (light) { + parent.disableLighting(disableResult); + } } if (System.currentTimeMillis() - start > recommended) { index++; @@ -356,12 +350,12 @@ public class BukkitChunk_All extends IntFaweChunk { } public void setBlock(BukkitImplAdapter adapter, Chunk chunk, Location location, int combinedId, boolean update) { - com.sk89q.worldedit.world.block.BlockState state = com.sk89q.worldedit.world.block.BlockState.getFromInternalId(combinedId); + com.sk89q.worldedit.world.block.BaseBlock base = com.sk89q.worldedit.world.block.BlockState.getFromInternalId(combinedId).toBaseBlock(); if (adapter != null) { - adapter.setBlock(chunk, (int) location.getX(), (int) location.getY(), (int) location.getZ(), state, update); + adapter.setBlock(chunk, (int) location.getX(), (int) location.getY(), (int) location.getZ(), base, update); } else { Block block = location.getWorld().getBlockAt(location); - block.setBlockData(BukkitAdapter.adapt(state), false); + block.setBlockData(BukkitAdapter.adapt(base), false); } } } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitQueue_0.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitQueue_0.java index ac294817f..65ae8e00d 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitQueue_0.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitQueue_0.java @@ -113,14 +113,15 @@ public abstract class BukkitQueue_0 extends NMSMa WirePacket packet = null; int viewDistance = Bukkit.getViewDistance(); try { - for (int i = 0; i < players.length; i++) { + for (FawePlayer fawePlayer : players) { int cx = chunk.getX(); int cz = chunk.getZ(); - Player player = ((BukkitPlayer) players[i]).parent; + Player player = ((BukkitPlayer) fawePlayer).parent; Location loc = player.getLocation(); - if (Math.abs((loc.getBlockX() >> 4) - cx) <= viewDistance && Math.abs((loc.getBlockZ() >> 4) - cz) <= viewDistance) { + if (Math.abs((loc.getBlockX() >> 4) - cx) <= viewDistance + && Math.abs((loc.getBlockZ() >> 4) - cz) <= viewDistance) { if (packet == null) { byte[] data; byte[] buffer = new byte[8192]; @@ -128,12 +129,12 @@ public abstract class BukkitQueue_0 extends NMSMa chunk = (FaweChunk) chunk.getChunk(); } // TODO FIXME -// if (chunk instanceof MCAChunk) { -// data = new MCAChunkPacket((MCAChunk) chunk, true, true, hasSky()).apply(buffer); -// } else { -// data = new FaweChunkPacket(chunk, true, true, hasSky()).apply(buffer); -// } -// packet = new WirePacket(PacketType.Play.Server.MAP_CHUNK, data); + // if (chunk instanceof MCAChunk) { + // data = new MCAChunkPacket((MCAChunk) chunk, true, true, hasSky()).apply(buffer); + // } else { + // data = new FaweChunkPacket(chunk, true, true, hasSky()).apply(buffer); + // } + // packet = new WirePacket(PacketType.Play.Server.MAP_CHUNK, data); } manager.sendWirePacket(player, packet); } diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitQueue_All.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitQueue_All.java index bdb0dff98..8960efd76 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitQueue_All.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/BukkitQueue_All.java @@ -22,6 +22,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentMap; import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; import org.bukkit.Chunk; @@ -153,7 +154,7 @@ public class BukkitQueue_All extends BukkitQueue_0(); + if (unloaded == null) unloaded = new ArrayDeque<>(); unloaded.add(chunk); } } @@ -180,19 +181,16 @@ public class BukkitQueue_All extends BukkitQueue_0 finalUnloaded = unloaded; - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - for (Chunk chunk : finalUnloaded) { - int cx = chunk.getX(); - int cz = chunk.getZ(); - if (world.isChunkLoaded(cx, cz)) continue; - SetQueue.IMP.addTask(() -> { - world.loadChunk(chunk.getX(), chunk.getZ(), false); - world.refreshChunk(chunk.getX(), chunk.getZ()); - }); + TaskManager.IMP.async(() -> { + for (Chunk chunk : finalUnloaded) { + int cx = chunk.getX(); + int cz = chunk.getZ(); + if (world.isChunkLoaded(cx, cz)) continue; + SetQueue.IMP.addTask(() -> { + world.loadChunk(chunk.getX(), chunk.getZ(), false); + world.refreshChunk(chunk.getX(), chunk.getZ()); + }); - } } }); // load chunks @@ -333,7 +331,7 @@ public class BukkitQueue_All extends BukkitQueue_0imp().getPlugin(); plm.registerEvents(this, plugin); try { plm.registerEvents(new ChunkListener_8Plus(this), plugin); } catch (Throwable ignore) {} - TaskManager.IMP.repeat(new Runnable() { - @Override - public void run() { - rateLimit--; - physicsFreeze = false; - itemFreeze = false; - lastZ = Integer.MIN_VALUE; - physSkip = 0; - physCancelPair = Long.MIN_VALUE; - physCancel = false; + TaskManager.IMP.repeat(() -> { + rateLimit--; + physicsFreeze = false; + itemFreeze = false; + lastZ = Integer.MIN_VALUE; + physSkip = 0; + physCancelPair = Long.MIN_VALUE; + physCancel = false; - counter.clear(); - for (Long2ObjectMap.Entry entry : badChunks.long2ObjectEntrySet()) { - long key = entry.getLongKey(); - int x = MathMan.unpairIntX(key); - int z = MathMan.unpairIntY(key); - counter.put(key, badLimit); - } - badChunks.clear(); + counter.clear(); + for (Long2ObjectMap.Entry entry : badChunks.long2ObjectEntrySet()) { + long key = entry.getLongKey(); + int x = MathMan.unpairIntX(key); + int z = MathMan.unpairIntY(key); + counter.put(key, badLimit); } + badChunks.clear(); }, Settings.IMP.TICK_LIMITER.INTERVAL); } } @@ -381,4 +378,4 @@ public abstract class ChunkListener implements Listener { return; } } -} \ No newline at end of file +} diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/FaweAdapter_All.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/FaweAdapter_All.java index 781cfe9b8..6c8dbb19b 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/FaweAdapter_All.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/FaweAdapter_All.java @@ -18,7 +18,7 @@ //import com.sk89q.jnbt.StringTag; //import com.sk89q.jnbt.Tag; //import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; +//import com.sk89q.worldedit.world.block.BlockState; //import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; //import com.sk89q.worldedit.entity.BaseEntity; //import com.sk89q.worldedit.internal.Constants; diff --git a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/PaperChunkCallback.java b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/PaperChunkCallback.java index 369f9a71a..20592715a 100644 --- a/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/PaperChunkCallback.java +++ b/worldedit-bukkit/src/main/java/com/boydti/fawe/bukkit/v0/PaperChunkCallback.java @@ -5,8 +5,8 @@ import org.bukkit.World; public abstract class PaperChunkCallback { public PaperChunkCallback(World world, int x, int z) { - world.getChunkAtAsync(x, z, chunk -> PaperChunkCallback.this.onLoad(chunk)); + world.getChunkAtAsync(x, z, PaperChunkCallback.this::onLoad); } public abstract void onLoad(Chunk chunk); -} \ No newline at end of file +} 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 e13815f15..a41583620 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 @@ -9,7 +9,10 @@ import java.util.Collection; import java.util.List; import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; + +import org.bukkit.FluidCollisionMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Biome; @@ -20,6 +23,9 @@ import org.bukkit.block.data.BlockData; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.RayTraceResult; +import org.bukkit.util.Vector; public class AsyncBlock implements Block { @@ -198,9 +204,10 @@ public class AsyncBlock implements Block { @Override public BlockFace getFace(Block block) { BlockFace[] directions = BlockFace.values(); - for(int i = 0; i < directions.length; ++i) { - BlockFace face = directions[i]; - if(this.getX() + face.getModX() == block.getX() && this.getY() + face.getModY() == block.getY() && this.getZ() + face.getModZ() == block.getZ()) { + for (BlockFace face : directions) { + if (this.getX() + face.getModX() == block.getX() + && this.getY() + face.getModY() == block.getY() + && this.getZ() + face.getModZ() == block.getZ()) { return face; } } @@ -210,11 +217,10 @@ public class AsyncBlock implements Block { @Override public AsyncBlockState getState() { int combined = queue.getCombinedId4Data(x, y, z, 0); - BlockTypes type = BlockTypes.getFromStateId(combined); - switch (type) { - case SIGN: - case WALL_SIGN: - return new AsyncSign(this, combined); + BlockType type = BlockTypes.getFromStateId(combined); + String s = type.getResource().toUpperCase(); + if (type == BlockTypes.SIGN || type == BlockTypes.WALL_SIGN) { + return new AsyncSign(this, combined); } return new AsyncBlockState(this, combined); } @@ -267,20 +273,13 @@ public class AsyncBlock implements Block { @Override public boolean isEmpty() { - switch (getType()) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - return true; - default: - return false; - } + return getType().isEmpty(); } @Override public boolean isLiquid() { int combined = queue.getCombinedId4Data(x, y, z, 0); - BlockTypes type = BlockTypes.getFromStateId(combined); + BlockType type = BlockTypes.getFromStateId(combined); return type.getMaterial().isLiquid(); } @@ -343,4 +342,19 @@ public class AsyncBlock implements Block { public void removeMetadata(String metadataKey, Plugin owningPlugin) { this.getUnsafeBlock().removeMetadata(metadataKey, owningPlugin); } + + @Override + public boolean isPassable() { + return this.getUnsafeBlock().isPassable(); + } + + @Override + public RayTraceResult rayTrace(Location arg0, Vector arg1, double arg2, FluidCollisionMode arg3) { + return this.getUnsafeBlock().rayTrace(arg0, arg1, arg2, arg3); + } + + @Override + public BoundingBox getBoundingBox() { + return this.getUnsafeBlock().getBoundingBox(); + } } 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 84d9d33cc..c536f9f8a 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 @@ -29,7 +29,7 @@ public class AsyncChunk implements Chunk { @Override public boolean equals(Object obj) { - if (obj == null || !(obj instanceof Chunk)) { + if (!(obj instanceof Chunk)) { return false; } Chunk other = (Chunk) obj; @@ -88,14 +88,14 @@ public class AsyncChunk implements Chunk { BukkitQueue_0 bq = (BukkitQueue_0) queue; if (world.isChunkLoaded(x, z)) { long pair = MathMan.pairInt(x, z); - Long originalKeep = bq.keepLoaded.get(pair); - bq.keepLoaded.put(pair, Long.MAX_VALUE); + Long originalKeep = BukkitQueue_0.keepLoaded.get(pair); + BukkitQueue_0.keepLoaded.put(pair, Long.MAX_VALUE); if (world.isChunkLoaded(x, z)) { task.run(); if (originalKeep != null) { - bq.keepLoaded.put(pair, originalKeep); + BukkitQueue_0.keepLoaded.put(pair, originalKeep); } else { - bq.keepLoaded.remove(pair); + BukkitQueue_0.keepLoaded.remove(pair); } return task.value; } @@ -182,4 +182,14 @@ public class AsyncChunk implements Chunk { public boolean isSlimeChunk() { return false; } + + @Override + public boolean isForceLoaded() { + return world.isChunkForceLoaded(x, z); + } + + @Override + public void setForceLoaded(boolean arg0) { + world.getChunkAt(x, z).setForceLoaded(arg0); + } } 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 4b04493be..2c2bda098 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 @@ -18,8 +18,11 @@ import java.util.Collection; import java.util.List; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.function.Predicate; import java.util.function.Supplier; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import org.bukkit.*; import org.bukkit.block.Biome; @@ -39,7 +42,9 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; +import org.bukkit.util.BoundingBox; import org.bukkit.util.Consumer; +import org.bukkit.util.RayTraceResult; import org.bukkit.util.Vector; /** @@ -109,7 +114,7 @@ public class AsyncWorld extends DelegateFaweQueue implements World, HasFaweQueue this.parent = parent; this.queue = queue; if (queue instanceof BukkitQueue_0) { - this.adapter = (BukkitImplAdapter) ((BukkitQueue_0) queue).getAdapter(); + this.adapter = BukkitQueue_0.getAdapter(); } else { try { this.adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); @@ -136,12 +141,7 @@ public class AsyncWorld extends DelegateFaweQueue implements World, HasFaweQueue if (queue != this.queue) { if (this.queue != null) { final FaweQueue oldQueue = this.queue; - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - oldQueue.flush(); - } - }); + TaskManager.IMP.async(oldQueue::flush); } this.queue = queue; } @@ -268,7 +268,7 @@ public class AsyncWorld extends DelegateFaweQueue implements World, HasFaweQueue public int getHighestBlockYAt(int x, int z) { for (int y = getMaxHeight() - 1; y >= 0; y--) { int stateId = queue.getCachedCombinedId4Data(x, y, z, BlockTypes.AIR.getInternalId()); - BlockTypes type = BlockTypes.getFromStateId(stateId); + BlockType type = BlockTypes.getFromStateId(stateId); if (!type.getMaterial().isAir()) return y; } return 0; @@ -349,7 +349,7 @@ public class AsyncWorld extends DelegateFaweQueue implements World, HasFaweQueue @Override public boolean equals(Object obj) { - if (obj == null || !(obj instanceof World)) { + if (!(obj instanceof World)) { return false; } World other = (World) obj; @@ -566,7 +566,7 @@ public class AsyncWorld extends DelegateFaweQueue implements World, HasFaweQueue return TaskManager.IMP.sync(new RunnableVal>() { @Override public void run(Collection value) { - this.value = (Collection) parent.getEntitiesByClass(classes); + this.value = parent.getEntitiesByClass(classes); } }); } @@ -576,7 +576,7 @@ public class AsyncWorld extends DelegateFaweQueue implements World, HasFaweQueue return TaskManager.IMP.sync(new RunnableVal>() { @Override public void run(Collection value) { - this.value = (Collection) parent.getEntitiesByClass(cls); + this.value = parent.getEntitiesByClass(cls); } }); } @@ -794,22 +794,12 @@ public class AsyncWorld extends DelegateFaweQueue implements World, HasFaweQueue @Override @Deprecated public FallingBlock spawnFallingBlock(Location location, Material material, byte data) throws IllegalArgumentException { - return TaskManager.IMP.sync(new Supplier() { - @Override - public FallingBlock get() { - return parent.spawnFallingBlock(location, material, data); - } - }); + return TaskManager.IMP.sync(() -> parent.spawnFallingBlock(location, material, data)); } @Override public FallingBlock spawnFallingBlock(Location location, BlockData blockData) throws IllegalArgumentException { - return TaskManager.IMP.sync(new Supplier() { - @Override - public FallingBlock get() { - return parent.spawnFallingBlock(location, blockData); - } - }); + return TaskManager.IMP.sync(() -> parent.spawnFallingBlock(location, blockData)); } @Override @@ -1181,4 +1171,106 @@ public class AsyncWorld extends DelegateFaweQueue implements World, HasFaweQueue } }); } + + @Override + public CompletableFuture getChunkAtAsync(int arg0, int arg1, boolean arg2) { + return parent.getChunkAtAsync(arg0, arg1, arg2); + } + + @Override + public Collection getNearbyEntities(BoundingBox arg0) { + return parent.getNearbyEntities(arg0); + } + + @Override + public Collection getNearbyEntities(BoundingBox arg0, Predicate arg1) { + return parent.getNearbyEntities(arg0, arg1); + } + + @Override + public Collection getNearbyEntities(Location arg0, double arg1, double arg2, double arg3, + Predicate arg4) { + return parent.getNearbyEntities(arg0, arg1, arg2, arg3, arg4); + } + + @Override + public boolean isChunkForceLoaded(int arg0, int arg1) { + return parent.isChunkForceLoaded(arg0, arg1); + } + + @Override + public boolean isDayTime() { + return parent.isDayTime(); + } + + @Override + public Location locateNearestStructure(Location arg0, StructureType arg1, int arg2, boolean arg3) { + return parent.locateNearestStructure(arg0, arg1, arg2, arg3); + } + + @Override + public RayTraceResult rayTrace(Location arg0, Vector arg1, double arg2, FluidCollisionMode arg3, boolean arg4, + double arg5, Predicate arg6) { + return parent.rayTrace(arg0, arg1, arg2, arg3, arg4, arg5, arg6); + } + + @Override + public RayTraceResult rayTraceBlocks(Location arg0, Vector arg1, double arg2) { + return parent.rayTraceBlocks(arg0, arg1, arg2); + } + + @Override + public RayTraceResult rayTraceBlocks(Location arg0, Vector arg1, double arg2, FluidCollisionMode arg3) { + return parent.rayTraceBlocks(arg0, arg1, arg2, arg3); + } + + @Override + public RayTraceResult rayTraceBlocks(Location arg0, Vector arg1, double arg2, FluidCollisionMode arg3, + boolean arg4) { + return parent.rayTraceBlocks(arg0, arg1, arg2, arg3, arg4); + } + + @Override + public RayTraceResult rayTraceEntities(Location arg0, Vector arg1, double arg2) { + return parent.rayTraceEntities(arg0, arg1, arg2); + } + + @Override + public RayTraceResult rayTraceEntities(Location arg0, Vector arg1, double arg2, double arg3) { + return parent.rayTraceEntities(arg0, arg1, arg2, arg3); + } + + @Override + public RayTraceResult rayTraceEntities(Location arg0, Vector arg1, double arg2, Predicate arg3) { + return parent.rayTraceEntities(arg0, arg1, arg2, arg3); + } + + @Override + public RayTraceResult rayTraceEntities(Location arg0, Vector arg1, double arg2, double arg3, + Predicate arg4) { + return parent.rayTraceEntities(arg0, arg1, arg2, arg3, arg4); + } + + @Override + public void spawnParticle(Particle arg0, Location arg1, int arg2, double arg3, double arg4, double arg5, + double arg6, T arg7, boolean arg8) { + parent.spawnParticle(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); + } + + @Override + public void spawnParticle(Particle arg0, double arg1, double arg2, double arg3, int arg4, double arg5, + double arg6, double arg7, double arg8, T arg9, boolean arg10) { + parent.spawnParticle(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); + + } + + @Override + public void setChunkForceLoaded(int x, int z, boolean forced) { + parent.setChunkForceLoaded(x, z, forced); + } + + @Override + public Collection getForceLoadedChunks() { + return parent.getForceLoadedChunks(); + } } 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 54018dc14..1dfb8ab9d 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 @@ -14,6 +14,8 @@ public class AsyncSign extends AsyncBlockState implements Sign { public AsyncSign(AsyncBlock block, int combined) { super(block, combined); } + + private boolean isEditable = false; @Override public String[] getLines() { @@ -51,4 +53,14 @@ public class AsyncSign extends AsyncBlockState implements Sign { map.put("Text" + (index + 1), new StringTag(toJson(line))); } } + + @Override + public boolean isEditable() { + return this.isEditable; + } + + @Override + public void setEditable(boolean arg0) { + this.isEditable = arg0; + } } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/wepif/PermissionsResolverManager.java b/worldedit-bukkit/src/main/java/com/sk89q/wepif/PermissionsResolverManager.java index 01f04546b..4775d86c4 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/wepif/PermissionsResolverManager.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/wepif/PermissionsResolverManager.java @@ -95,6 +95,7 @@ public class PermissionsResolverManager implements PermissionsResolver { bPermissionsResolver.class, GroupManagerResolver.class, NijiPermissionsResolver.class, + VaultResolver.class, DinnerPermsResolver.class, FlatFilePermissionsResolver.class }; @@ -283,7 +284,8 @@ public class PermissionsResolverManager implements PermissionsResolver { if (plugin instanceof PermissionsProvider) { setPluginPermissionsResolver(plugin); } else if ("permissions".equalsIgnoreCase(name) || "permissionsex".equalsIgnoreCase(name) - || "bpermissions".equalsIgnoreCase(name) || "groupmanager".equalsIgnoreCase(name)) { + || "bpermissions".equalsIgnoreCase(name) || "groupmanager".equalsIgnoreCase(name) + || "vault".equalsIgnoreCase(name)) { load(); } } @@ -294,7 +296,8 @@ public class PermissionsResolverManager implements PermissionsResolver { if (event.getPlugin() instanceof PermissionsProvider || "permissions".equalsIgnoreCase(name) || "permissionsex".equalsIgnoreCase(name) - || "bpermissions".equalsIgnoreCase(name) || "groupmanager".equalsIgnoreCase(name)) { + || "bpermissions".equalsIgnoreCase(name) || "groupmanager".equalsIgnoreCase(name) + || "vault".equalsIgnoreCase(name)) { load(); } } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/wepif/VaultResolver.java b/worldedit-bukkit/src/main/java/com/sk89q/wepif/VaultResolver.java new file mode 100644 index 000000000..a97017ceb --- /dev/null +++ b/worldedit-bukkit/src/main/java/com/sk89q/wepif/VaultResolver.java @@ -0,0 +1,116 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.wepif; + +import com.sk89q.util.yaml.YAMLProcessor; +import net.milkbowl.vault.permission.Permission; +import org.bukkit.OfflinePlayer; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.plugin.RegisteredServiceProvider; + +public class VaultResolver implements PermissionsResolver { + + private static Permission perms = null; + + public static PermissionsResolver factory(Server server, YAMLProcessor config) { + if (server.getPluginManager().getPlugin("Vault") == null) { + return null; + } + RegisteredServiceProvider rsp = server.getServicesManager().getRegistration(Permission.class); + perms = rsp.getProvider(); + if (perms == null) { + return null; + } + + return new VaultResolver(server); + } + + private final Server server; + + public VaultResolver(Server server) { + this.server = server; + } + + @Override + public void load() { + } + + @Override + public String getDetectionMessage() { + return "Vault detected! Using Vault for permissions"; + } + + @Override + public boolean hasPermission(String name, String permission) { + return hasPermission(server.getOfflinePlayer(name), permission); + } + + @Override + public boolean hasPermission(String worldName, String name, String permission) { + return hasPermission(worldName, server.getOfflinePlayer(name), permission); + } + + @Override + public boolean inGroup(String player, String group) { + return inGroup(server.getOfflinePlayer(player), group); + } + + @Override + public String[] getGroups(String player) { + return getGroups(server.getOfflinePlayer(player)); + } + + @Override + public boolean hasPermission(OfflinePlayer player, String permission) { + Player onlinePlayer = player.getPlayer(); + if (onlinePlayer == null) { + return perms.playerHas(null, player, permission); + } else { + return perms.playerHas(onlinePlayer.getWorld().getName(), player, permission); + } + } + + @Override + public boolean hasPermission(String worldName, OfflinePlayer player, String permission) { + return perms.playerHas(worldName, player, permission); + } + + @Override + public boolean inGroup(OfflinePlayer player, String group) { + Player onlinePlayer = player.getPlayer(); + if (onlinePlayer == null) { + return perms.playerInGroup(null, player, group); + } else { + return perms.playerInGroup(onlinePlayer, group); + } + } + + @Override + public String[] getGroups(OfflinePlayer player) { + Player onlinePlayer = player.getPlayer(); + if (onlinePlayer == null) { + return perms.getPlayerGroups(null, player); + } else { + return perms.getPlayerGroups(onlinePlayer); + } + } + +} 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 885a961b3..e68587283 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,12 +19,13 @@ package com.sk89q.worldedit.bukkit; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.bukkit.adapter.IBukkitAdapter; import com.sk89q.worldedit.bukkit.adapter.SimpleBukkitAdapter; import com.sk89q.worldedit.entity.Entity; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.block.BlockState; @@ -34,6 +35,7 @@ import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.item.ItemType; + import org.bukkit.Material; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Player; @@ -84,7 +86,11 @@ public enum BukkitAdapter { return getAdapter().adapt(location); } - public static org.bukkit.Location adapt(org.bukkit.World world, Vector position) { + public static org.bukkit.Location adapt(org.bukkit.World world, Vector3 position) { + return getAdapter().adapt(world, position); + } + + public static org.bukkit.Location adapt(org.bukkit.World world, BlockVector3 position) { return getAdapter().adapt(world, position); } @@ -92,10 +98,14 @@ public enum BukkitAdapter { return getAdapter().adapt(world, location); } - public static Vector asVector(org.bukkit.Location location) { + public static Vector3 asVector(org.bukkit.Location location) { return getAdapter().asVector(location); } + public static BlockVector3 asBlockVector(org.bukkit.Location location) { + return getAdapter().asBlockVector(location); + } + public static Entity adapt(org.bukkit.entity.Entity entity) { return getAdapter().adapt(entity); } @@ -132,12 +142,12 @@ public enum BukkitAdapter { return getAdapter().adapt(blockData); } - public static BlockTypes adapt(Material material) { + public static BlockType adapt(Material material) { return getAdapter().adapt(material); } - public static BlockData adapt(BlockStateHolder block) { - return getAdapter().adapt(block); + public static > BlockData adapt(B block) { + return getAdapter().adapt(block); } public static BlockData getBlockData(int combinedId) { diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockCategoryRegistry.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockCategoryRegistry.java new file mode 100644 index 000000000..24cbe0f6b --- /dev/null +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitBlockCategoryRegistry.java @@ -0,0 +1,52 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.bukkit; + +import com.sk89q.worldedit.registry.Category; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.registry.BlockCategoryRegistry; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Tag; + +import java.util.Set; +import java.util.stream.Collectors; + +public class BukkitBlockCategoryRegistry implements BlockCategoryRegistry { + + private Set getFromBukkitTag(Tag tag) { + return tag.getValues().stream().map(BukkitAdapter::asBlockType).collect(Collectors.toSet()); + } + + @Override + public Set getCategorisedByName(String category) { + String[] split = category.split(":"); + String namespace = split.length > 1 ? split[0] : "minecraft"; + String key = split.length > 1 ? split[1] : category; + Tag tag = Bukkit.getTag(Tag.REGISTRY_BLOCKS, new NamespacedKey(namespace, key), Material.class); + return getFromBukkitTag(tag); + } + + @Override + public Set getAll(Category category) { + return getCategorisedByName(category.getId()); + } +} \ No newline at end of file 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 7795a0022..0264ba49e 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 @@ -20,9 +20,9 @@ package com.sk89q.worldedit.bukkit; import com.bekvon.bukkit.residence.commands.material; -import com.sk89q.worldedit.blocks.BlockMaterial; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.command.tool.BlockDataCyler; +import com.sk89q.worldedit.world.registry.BlockMaterial; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -83,7 +83,7 @@ public class BukkitBlockRegistry extends BundledBlockRegistry { @Nullable @Override - public Map getProperties(BlockType blockType) { + public Map> getProperties(BlockType blockType) { BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); if (adapter != null) { return adapter.getProperties(blockType); 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 3d289df5d..55929af02 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,24 +19,22 @@ package com.sk89q.worldedit.bukkit; -import com.sk89q.worldedit.entity.metadata.Metadatable; -import com.sk89q.worldedit.session.SessionKey; -import com.sk89q.worldedit.util.auth.AuthorizationException; -import com.sk89q.worldedit.extension.platform.Actor; -import com.sk89q.worldedit.internal.cui.CUIEvent; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import javax.annotation.Nullable; -import java.io.File; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -public class BukkitCommandSender implements Actor, Metadatable { +import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.internal.cui.CUIEvent; +import com.sk89q.worldedit.session.SessionKey; +import com.sk89q.worldedit.util.auth.AuthorizationException; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.io.File; +import java.util.UUID; + +import javax.annotation.Nullable; + +public class BukkitCommandSender implements Actor { /** * One time generated ID. @@ -45,7 +43,6 @@ public class BukkitCommandSender implements Actor, Metadatable { private CommandSender sender; private WorldEditPlugin plugin; - private ConcurrentHashMap meta; public BukkitCommandSender(WorldEditPlugin plugin, CommandSender sender) { checkNotNull(plugin); @@ -56,12 +53,6 @@ public class BukkitCommandSender implements Actor, Metadatable { this.sender = sender; } - @Override - public synchronized Map getMetaMap() { - if (meta == null) meta = new ConcurrentHashMap<>(); - return meta; - } - @Override public UUID getUniqueId() { return DEFAULT_ID; diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitConfiguration.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitConfiguration.java index 5a20cdfbc..494a464ea 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitConfiguration.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitConfiguration.java @@ -21,6 +21,7 @@ package com.sk89q.worldedit.bukkit; import com.sk89q.util.yaml.YAMLProcessor; import com.sk89q.worldedit.util.YAMLConfiguration; +import com.sk89q.worldedit.util.report.Unreported; import java.io.File; @@ -30,7 +31,7 @@ import java.io.File; public class BukkitConfiguration extends YAMLConfiguration { public boolean noOpPermissions = false; - private final WorldEditPlugin plugin; + @Unreported private final WorldEditPlugin plugin; public BukkitConfiguration(YAMLProcessor config, WorldEditPlugin plugin) { super(config, plugin.getLogger()); diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntity.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntity.java index 595a7fc9c..a5c7b0a60 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntity.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitEntity.java @@ -71,6 +71,16 @@ public class BukkitEntity implements Entity { } } + @Override + public boolean setLocation(Location location) { + org.bukkit.entity.Entity entity = entityRef.get(); + if (entity != null) { + return entity.teleport(BukkitAdapter.adapt(location)); + } else { + return false; + } + } + @Override public BaseEntity getState() { org.bukkit.entity.Entity entity = entityRef.get(); diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitItemCategoryRegistry.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitItemCategoryRegistry.java new file mode 100644 index 000000000..b5291b4e1 --- /dev/null +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitItemCategoryRegistry.java @@ -0,0 +1,52 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.bukkit; + +import com.sk89q.worldedit.registry.Category; +import com.sk89q.worldedit.world.item.ItemType; +import com.sk89q.worldedit.world.registry.ItemCategoryRegistry; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Tag; + +import java.util.Set; +import java.util.stream.Collectors; + +public class BukkitItemCategoryRegistry implements ItemCategoryRegistry { + + private Set getFromBukkitTag(Tag tag) { + return tag.getValues().stream().map(BukkitAdapter::asItemType).collect(Collectors.toSet()); + } + + @Override + public Set getCategorisedByName(String category) { + String[] split = category.split(":"); + String namespace = split.length > 1 ? split[0] : "minecraft"; + String key = split.length > 1 ? split[1] : category; + Tag tag = Bukkit.getTag(Tag.REGISTRY_ITEMS, new NamespacedKey(namespace, key), Material.class); + return getFromBukkitTag(tag); + } + + @Override + public Set getAll(Category category) { + return getCategorisedByName(category.getId()); + } +} \ 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 be3f6ff1f..b3674e986 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 @@ -22,20 +22,25 @@ package com.sk89q.worldedit.bukkit; import com.boydti.fawe.object.RunnableVal; import com.boydti.fawe.util.TaskManager; import com.sk89q.util.StringUtil; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.blocks.BaseItemStack; +import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.extension.platform.AbstractPlayerActor; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.internal.cui.CUIEvent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.session.SessionKey; import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.world.World; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.gamemode.GameModes; + import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -45,11 +50,12 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.UUID; +import javax.annotation.Nullable; + public class BukkitPlayer extends AbstractPlayerActor { private Player player; @@ -74,11 +80,11 @@ public class BukkitPlayer extends AbstractPlayerActor { } @Override - public BlockState getBlockInHand(HandSide handSide) throws WorldEditException { + public BaseBlock getBlockInHand(HandSide handSide) throws WorldEditException { ItemStack itemStack = handSide == HandSide.MAIN_HAND ? player.getInventory().getItemInMainHand() : player.getInventory().getItemInOffHand(); - return BukkitAdapter.asBlockState(itemStack); + return BukkitAdapter.asBlockState(itemStack).toBaseBlock(); } @Override @@ -86,34 +92,38 @@ public class BukkitPlayer extends AbstractPlayerActor { return player.getName(); } + @Override + public String getDisplayName() { + return player.getDisplayName(); + } + @Override public void giveItem(BaseItemStack itemStack) { final PlayerInventory inv = player.getInventory(); ItemStack newItem = BukkitAdapter.adapt(itemStack); - if (itemStack.getType() == WorldEdit.getInstance().getConfiguration().wandItem) { + if (itemStack.getType().getId().equalsIgnoreCase(WorldEdit.getInstance().getConfiguration().wandItem)) { inv.remove(newItem); } final ItemStack item = player.getItemInHand(); player.setItemInHand(newItem); - if (item != null) { - HashMap overflow = inv.addItem(item); - if (overflow != null && !overflow.isEmpty()) { - TaskManager.IMP.sync(new RunnableVal() { - @Override - public void run(Object value) { - for (Map.Entry entry : overflow.entrySet()) { - ItemStack stack = entry.getValue(); - if (stack.getType() != Material.AIR && stack.getAmount() > 0) { - Item dropped = player.getWorld().dropItem(player.getLocation(), stack); - PlayerDropItemEvent event = new PlayerDropItemEvent(player, dropped); - if (event.isCancelled()) { - dropped.remove(); - } + HashMap overflow = inv.addItem(item); + if (!overflow.isEmpty()) { + TaskManager.IMP.sync(new RunnableVal() { + @Override + public void run(Object value) { + for (Map.Entry entry : overflow.entrySet()) { + ItemStack stack = entry.getValue(); + if (stack.getType() != Material.AIR && stack.getAmount() > 0) { + Item + dropped = player.getWorld().dropItem(player.getLocation(), stack); + PlayerDropItemEvent event = new PlayerDropItemEvent(player, dropped); + if (event.isCancelled()) { + dropped.remove(); } } } - }); - } + } + }); } player.updateInventory(); } @@ -147,7 +157,7 @@ public class BukkitPlayer extends AbstractPlayerActor { } @Override - public void setPosition(Vector pos, float pitch, float yaw) { + public void setPosition(Vector3 pos, float pitch, float yaw) { player.teleport(new Location(player.getWorld(), pos.getX(), pos.getY(), pos.getZ(), yaw, pitch)); } @@ -205,7 +215,7 @@ public class BukkitPlayer extends AbstractPlayerActor { return; } - setPosition(new Vector(x + 0.5, y, z + 0.5)); + setPosition(Vector3.at(x + 0.5, y, z + 0.5)); player.setFlying(true); } @@ -217,7 +227,7 @@ public class BukkitPlayer extends AbstractPlayerActor { @Override public com.sk89q.worldedit.util.Location getLocation() { Location nativeLocation = player.getLocation(); - Vector position = BukkitAdapter.asVector(nativeLocation); + Vector3 position = BukkitAdapter.asVector(nativeLocation); return new com.sk89q.worldedit.util.Location( getWorld(), position, @@ -225,6 +235,11 @@ public class BukkitPlayer extends AbstractPlayerActor { nativeLocation.getPitch()); } + @Override + public boolean setLocation(com.sk89q.worldedit.util.Location location) { + return player.teleport(BukkitAdapter.adapt(location)); + } + @Nullable @Override public T getFacet(Class cls) { @@ -274,4 +289,22 @@ public class BukkitPlayer extends AbstractPlayerActor { } + @Override + public > void sendFakeBlock(BlockVector3 pos, B block) { + Location loc = new Location(player.getWorld(), pos.getX(), pos.getY(), pos.getZ()); + if (block == null) { + player.sendBlockChange(loc, player.getWorld().getBlockAt(loc).getBlockData()); + } else { + player.sendBlockChange(loc, BukkitAdapter.adapt(block)); + if (block instanceof BaseBlock && ((BaseBlock) block).hasNbtData()) { + BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); + if (adapter != null) { + adapter.sendFakeNBT(player, pos, ((BaseBlock) block).getNbtData()); + if (block.getBlockType() == BlockTypes.STRUCTURE_BLOCK) { + adapter.sendFakeOP(player); + } + } + } + } + } } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitRegistries.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitRegistries.java index 6a50bf507..962d10d01 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitRegistries.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitRegistries.java @@ -31,6 +31,8 @@ class BukkitRegistries extends BundledRegistries { private final ItemRegistry itemRegistry = new BukkitItemRegistry(); private final BiomeRegistry biomeRegistry = new BukkitBiomeRegistry(); private final EntityRegistry entityRegistry = new BukkitEntityRegistry(); + private final BlockCategoryRegistry blockCategoryRegistry = new BukkitBlockCategoryRegistry(); + private final ItemCategoryRegistry itemCategoryRegistry = new BukkitItemCategoryRegistry(); /** * Create a new instance. @@ -42,6 +44,11 @@ class BukkitRegistries extends BundledRegistries { public BlockRegistry getBlockRegistry() { return blockRegistry; } + + @Override + public BlockCategoryRegistry getBlockCategoryRegistry() { + return blockCategoryRegistry; + } @Override public BiomeRegistry getBiomeRegistry() { @@ -52,6 +59,11 @@ class BukkitRegistries extends BundledRegistries { public ItemRegistry getItemRegistry() { return itemRegistry; } + + @Override + public ItemCategoryRegistry getItemCategoryRegistry() { + return itemCategoryRegistry; + } @Override public EntityRegistry getEntityRegistry() { diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitWorld.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitWorld.java index b328523c7..a199b6069 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitWorld.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/BukkitWorld.java @@ -1,5 +1,4 @@ /* - * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q * Copyright (C) WorldEdit team and contributors * @@ -19,15 +18,18 @@ package com.sk89q.worldedit.bukkit; -import com.boydti.fawe.Fawe; -import com.sk89q.worldedit.*; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; + +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.blocks.BaseItemStack; -import com.sk89q.worldedit.blocks.LazyBlock; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.history.change.BlockChange; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.world.AbstractWorld; @@ -35,6 +37,7 @@ import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.weather.WeatherType; import com.sk89q.worldedit.world.weather.WeatherTypes; + import org.bukkit.Effect; import org.bukkit.TreeType; import org.bukkit.World; @@ -43,16 +46,18 @@ import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Chest; import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; import org.bukkit.inventory.DoubleChestInventory; import org.bukkit.inventory.Inventory; import javax.annotation.Nullable; import java.lang.ref.WeakReference; -import java.util.*; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; - import static com.google.common.base.Preconditions.checkNotNull; public class BukkitWorld extends AbstractWorld { @@ -84,8 +89,8 @@ public class BukkitWorld extends AbstractWorld { List ents = world.getEntities(); List entities = new ArrayList<>(); for (Entity ent : ents) { - if (region.contains(BukkitAdapter.asVector(ent.getLocation()))) { - addEntities(ent, entities); + if (region.contains(BukkitAdapter.asBlockVector(ent.getLocation()))) { + entities.add(BukkitAdapter.adapt(ent)); } } return entities; @@ -95,43 +100,11 @@ public class BukkitWorld extends AbstractWorld { public List getEntities() { List list = new ArrayList<>(); for (Entity entity : getWorld().getEntities()) { - addEntities(entity, list); + list.add(BukkitAdapter.adapt(entity)); } return list; } - private static com.sk89q.worldedit.entity.Entity adapt(Entity ent) { - if (ent == null) return null; - return BukkitAdapter.adapt(ent); - } - - private void addEntities(Entity ent, Collection ents) { - ents.add(BukkitAdapter.adapt(ent)); - if (ent instanceof Player) { - final Player plr = (Player) ent; - com.sk89q.worldedit.entity.Entity left = adapt(((Player) ent).getShoulderEntityLeft()); - com.sk89q.worldedit.entity.Entity right = adapt(((Player) ent).getShoulderEntityRight()); - if (left != null) { - ents.add(new DelegateEntity(left) { - @Override - public boolean remove() { - plr.setShoulderEntityLeft(null); - return true; - } - }); - } - if (right != null) { - ents.add(new DelegateEntity(right) { - @Override - public boolean remove() { - plr.setShoulderEntityRight(null); - return true; - } - }); - } - } - } - @Nullable @Override public com.sk89q.worldedit.entity.Entity createEntity(com.sk89q.worldedit.util.Location location, BaseEntity entity) { @@ -185,22 +158,22 @@ public class BukkitWorld extends AbstractWorld { } @Override - public int getBlockLightLevel(Vector pt) { + public int getBlockLightLevel(BlockVector3 pt) { return getWorld().getBlockAt(pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()).getLightLevel(); } @Override public boolean regenerate(Region region, EditSession editSession) { - com.sk89q.worldedit.world.block.BlockStateHolder[] history = new com.sk89q.worldedit.world.block.BlockState[16 * 16 * (getMaxY() + 1)]; + BaseBlock[] history = new BaseBlock[16 * 16 * (getMaxY() + 1)]; - for (Vector2D chunk : region.getChunks()) { - Vector min = new Vector(chunk.getBlockX() * 16, 0, chunk.getBlockZ() * 16); + for (BlockVector2 chunk : region.getChunks()) { + BlockVector3 min = BlockVector3.at(chunk.getBlockX() * 16, 0, chunk.getBlockZ() * 16); // First save all the blocks inside for (int x = 0; x < 16; ++x) { for (int y = 0; y < (getMaxY() + 1); ++y) { for (int z = 0; z < 16; ++z) { - Vector pt = min.add(x, y, z); + BlockVector3 pt = min.add(x, y, z); int index = y * 16 * 16 + z * 16 + x; history[index] = editSession.getFullBlock(pt); } @@ -217,14 +190,14 @@ public class BukkitWorld extends AbstractWorld { for (int x = 0; x < 16; ++x) { for (int y = 0; y < (getMaxY() + 1); ++y) { for (int z = 0; z < 16; ++z) { - Vector pt = min.add(x, y, z); + BlockVector3 pt = min.add(x, y, z); int index = y * 16 * 16 + z * 16 + x; // We have to restore the block if it was outside if (!region.contains(pt)) { editSession.smartSetBlock(pt, history[index]); } else { // Otherwise fool with history - editSession.getChangeSet().add(new BlockChange(pt.toBlockVector(), history[index], editSession.getFullBlock(pt))); + editSession.getChangeSet().add(new BlockChange(pt, history[index], editSession.getFullBlock(pt))); } } } @@ -263,7 +236,7 @@ public class BukkitWorld extends AbstractWorld { } @Override - public boolean clearContainerBlockContents(Vector pt) { + public boolean clearContainerBlockContents(BlockVector3 pt) { Block block = getWorld().getBlockAt(pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()); if (block == null) { return false; @@ -317,7 +290,7 @@ public class BukkitWorld extends AbstractWorld { } @Override - public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, Vector pt) { + public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 pt) { World world = getWorld(); TreeType bukkitType = toBukkitTreeType(type); return type != null && world.generateTree(BukkitAdapter.adapt(world, pt), bukkitType, @@ -325,13 +298,13 @@ public class BukkitWorld extends AbstractWorld { } @Override - public void dropItem(Vector pt, BaseItemStack item) { + public void dropItem(Vector3 pt, BaseItemStack item) { World world = getWorld(); world.dropItemNaturally(BukkitAdapter.adapt(world, pt), BukkitAdapter.adapt(item)); } @Override - public void checkLoadedChunk(Vector pt) { + public void checkLoadedChunk(BlockVector3 pt) { World world = getWorld(); if (!world.isChunkLoaded(pt.getBlockX() >> 4, pt.getBlockZ() >> 4)) { @@ -363,15 +336,15 @@ public class BukkitWorld extends AbstractWorld { } @Override - public void fixAfterFastMode(Iterable chunks) { + public void fixAfterFastMode(Iterable chunks) { World world = getWorld(); - for (BlockVector2D chunkPos : chunks) { + for (BlockVector2 chunkPos : chunks) { world.refreshChunk(chunkPos.getBlockX(), chunkPos.getBlockZ()); } } @Override - public boolean playEffect(Vector position, int type, int data) { + public boolean playEffect(Vector3 position, int type, int data) { World world = getWorld(); final Effect effect = effects.get(type); @@ -430,29 +403,31 @@ public class BukkitWorld extends AbstractWorld { } @Override - public void simulateBlockMine(Vector pt) { + public BlockVector3 getSpawnPosition() { + return BukkitAdapter.asBlockVector(getWorld().getSpawnLocation()); + } + + @Override + public void simulateBlockMine(BlockVector3 pt) { getWorld().getBlockAt(pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()).breakNaturally(); } @Override - public com.sk89q.worldedit.world.block.BlockState getBlock(Vector position) { + public com.sk89q.worldedit.world.block.BlockState getBlock(BlockVector3 position) { Block bukkitBlock = getWorld().getBlockAt(position.getBlockX(), position.getBlockY(), position.getBlockZ()); return BukkitAdapter.adapt(bukkitBlock.getBlockData()); } @Override - public boolean setBlock(Vector position, BlockStateHolder block, boolean notifyAndLight) { + public > boolean setBlock(BlockVector3 position, B block, boolean notifyAndLight) throws WorldEditException { BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); if (adapter != null) { try { - int x = position.getBlockX(); - int y = position.getBlockY(); - int z = position.getBlockZ(); - return adapter.setBlock(getWorld().getChunkAt(x >> 4, z >> 4), x, y, z, block, true); + return adapter.setBlock(BukkitAdapter.adapt(getWorld(), position), block, notifyAndLight); } catch (Exception e) { - if (block.getNbtData() != null) { + if (block instanceof BaseBlock && ((BaseBlock)block).getNbtData() != null) { logger.warning("Tried to set a corrupt tile entity at " + position.toString()); - logger.warning(block.getNbtData().toString()); + logger.warning(((BaseBlock)block).getNbtData().toString()); } e.printStackTrace(); Block bukkitBlock = getWorld().getBlockAt(position.getBlockX(), position.getBlockY(), position.getBlockZ()); @@ -467,22 +442,33 @@ public class BukkitWorld extends AbstractWorld { } @Override - public com.sk89q.worldedit.world.block.BlockState getLazyBlock(Vector position) { + public com.sk89q.worldedit.world.block.BlockState getLazyBlock(BlockVector3 position) { return getBlock(position); } @Override - public com.sk89q.worldedit.world.block.BlockState getFullBlock(Vector position) { + public BaseBlock getFullBlock(BlockVector3 position) { BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); if (adapter != null) { return adapter.getBlock(BukkitAdapter.adapt(getWorld(), position)); } else { - return getBlock(position); + return getBlock(position).toBaseBlock(); } } @Override - public BaseBiome getBiome(Vector2D position) { + public boolean notifyAndLightBlock(BlockVector3 position, com.sk89q.worldedit.world.block.BlockState previousType) throws WorldEditException { + BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); + if (adapter != null) { + adapter.notifyAndLightBlock(BukkitAdapter.adapt(getWorld(), position), previousType); + return true; + } + + return false; + } + + @Override + public BaseBiome getBiome(BlockVector2 position) { BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); if (adapter != null) { int id = adapter.getBiomeId(getWorld().getBiome(position.getBlockX(), position.getBlockZ())); @@ -493,7 +479,7 @@ public class BukkitWorld extends AbstractWorld { } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); if (adapter != null) { Biome bukkitBiome = adapter.getBiome(biome.getId()); diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/DelegateEntity.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/DelegateEntity.java index 26cb9847e..86a978f92 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/DelegateEntity.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/DelegateEntity.java @@ -44,4 +44,9 @@ public class DelegateEntity implements Entity { public T getFacet(Class cls) { return parent.getFacet(cls); } + + @Override + public boolean setLocation(Location location) { + return parent.setLocation(location); + } } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/EditSessionBlockChangeDelegate.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/EditSessionBlockChangeDelegate.java index 97fa2b170..e0613cd97 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/EditSessionBlockChangeDelegate.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/EditSessionBlockChangeDelegate.java @@ -21,8 +21,8 @@ package com.sk89q.worldedit.bukkit; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.math.BlockVector3; + import org.bukkit.BlockChangeDelegate; import org.bukkit.block.data.BlockData; @@ -40,7 +40,7 @@ public class EditSessionBlockChangeDelegate implements BlockChangeDelegate { @Override public boolean setBlockData(int x, int y, int z, BlockData blockData) { try { - editSession.setBlock(new Vector(x, y, z), BukkitAdapter.adapt(blockData)); + editSession.setBlock(BlockVector3.at(x, y, z), BukkitAdapter.adapt(blockData)); } catch (MaxChangedBlocksException e) { return false; } @@ -49,7 +49,7 @@ public class EditSessionBlockChangeDelegate implements BlockChangeDelegate { @Override public BlockData getBlockData(int x, int y, int z) { - return BukkitAdapter.adapt(editSession.getBlock(new Vector(x, y, z))); + return BukkitAdapter.adapt(editSession.getBlock(BlockVector3.at(x, y, z))); } @Override @@ -59,7 +59,7 @@ public class EditSessionBlockChangeDelegate implements BlockChangeDelegate { @Override public boolean isEmpty(int x, int y, int z) { - return editSession.getBlock(new Vector(x, y, z)).getBlockType().getMaterial().isAir(); + return editSession.getBlock(BlockVector3.at(x, y, z)).getBlockType().getMaterial().isAir(); } } 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 44dd56b44..05774b84c 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 @@ -21,10 +21,13 @@ package com.sk89q.worldedit.bukkit; +import com.sk89q.minecraft.util.commands.CommandLocals; import com.sk89q.util.StringUtil; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.util.Location; +import com.sk89q.worldedit.util.command.CommandMapping; import com.sk89q.worldedit.world.World; import org.bukkit.block.Block; import org.bukkit.event.Event.Result; @@ -33,10 +36,14 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerCommandSendEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; +import java.util.Set; +import java.util.stream.Collectors; + /** * Handles all events thrown in relation to a Player */ @@ -99,6 +106,17 @@ public class WorldEditListener implements Listener { } } + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerCommand(PlayerCommandSendEvent event) { + CommandLocals locals = new CommandLocals(); + locals.put(Actor.class, plugin.wrapCommandSender(event.getPlayer())); + Set toRemove = plugin.getWorldEdit().getPlatformManager().getCommandManager().getDispatcher().getCommands().stream() + .filter(commandMapping -> !commandMapping.getCallable().testPermission(locals)) + .map(CommandMapping::getPrimaryAlias) + .collect(Collectors.toSet()); + event.getCommands().removeIf(toRemove::contains); + } + /** * Called when a player interacts * diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditPlugin.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditPlugin.java index 129f85859..78f8c8091 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditPlugin.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/WorldEditPlugin.java @@ -79,42 +79,42 @@ public class WorldEditPlugin extends JavaPlugin //implements TabCompleter private BukkitConfiguration config; private static Map lookupNames; - static { - { // Disable AWE as otherwise both fail to load - PluginManager manager = Bukkit.getPluginManager(); - try { - Field pluginsField = manager.getClass().getDeclaredField("plugins"); - Field lookupNamesField = manager.getClass().getDeclaredField("lookupNames"); - pluginsField.setAccessible(true); - lookupNamesField.setAccessible(true); - List plugins = (List) pluginsField.get(manager); - lookupNames = (Map) lookupNamesField.get(manager); - pluginsField.set(manager, plugins = new ArrayList(plugins) { - @Override - public boolean add(Plugin plugin) { - if (plugin.getName().startsWith("AsyncWorldEdit")) { - Fawe.debug("Disabling `" + plugin.getName() + "` as it is incompatible"); - } else if (plugin.getName().startsWith("BetterShutdown")) { - Fawe.debug("Disabling `" + plugin.getName() + "` as it is incompatible (Improperly shaded classes from com.sk89q.minecraft.util.commands)"); - } else { - return super.add(plugin); - } - return false; - } - }); - lookupNamesField.set(manager, lookupNames = new ConcurrentHashMap(lookupNames) { - @Override - public Plugin put(String key, Plugin plugin) { - if (plugin.getName().startsWith("AsyncWorldEdit") || plugin.getName().startsWith("BetterShutdown")) { - return null; - } - return super.put(key, plugin); - } - }); - } catch (Throwable ignore) {} - } - } - +// static { +// { // Disable AWE as otherwise both fail to load +// PluginManager manager = Bukkit.getPluginManager(); +// try { +// Field pluginsField = manager.getClass().getDeclaredField("plugins"); +// Field lookupNamesField = manager.getClass().getDeclaredField("lookupNames"); +// pluginsField.setAccessible(true); +// lookupNamesField.setAccessible(true); +// List plugins = (List) pluginsField.get(manager); +// lookupNames = (Map) lookupNamesField.get(manager); +// pluginsField.set(manager, plugins = new ArrayList(plugins) { +// @Override +// public boolean add(Plugin plugin) { +// if (plugin.getName().startsWith("AsyncWorldEdit")) { +// Fawe.debug("Disabling `" + plugin.getName() + "` as it is incompatible"); +// } else if (plugin.getName().startsWith("BetterShutdown")) { +// Fawe.debug("Disabling `" + plugin.getName() + "` as it is incompatible (Improperly shaded classes from com.sk89q.minecraft.util.commands)"); +// } else { +// return super.add(plugin); +// } +// return false; +// } +// }); +// lookupNamesField.set(manager, lookupNames = new ConcurrentHashMap(lookupNames) { +// @Override +// public Plugin put(String key, Plugin plugin) { +// if (plugin.getName().startsWith("AsyncWorldEdit") || plugin.getName().startsWith("BetterShutdown")) { +// return null; +// } +// return super.put(key, plugin); +// } +// }); +// } catch (Throwable ignore) {} +// } +// } +// public WorldEditPlugin() { init(); } @@ -145,6 +145,7 @@ public class WorldEditPlugin extends JavaPlugin //implements TabCompleter @SuppressWarnings("AccessStaticViaInstance") @Override public void onEnable() { + rename(); this.INSTANCE = this; FaweBukkit imp = new FaweBukkit(this); @@ -348,41 +349,27 @@ public class WorldEditPlugin extends JavaPlugin //implements TabCompleter protected void createDefaultConfiguration(String name) { File actual = new File(getDataFolder(), name); if (!actual.exists()) { - InputStream input = null; - try { - JarFile file = new JarFile(getFile()); + try (JarFile file = new JarFile(getFile())) { ZipEntry copy = file.getEntry("defaults/" + name); if (copy == null) throw new FileNotFoundException(); - input = file.getInputStream(copy); + copyDefaultConfig(file.getInputStream(copy), actual, name); } catch (IOException e) { getLogger().severe("Unable to read default configuration: " + name); } - if (input != null) { - FileOutputStream output = null; + } + } - try { - output = new FileOutputStream(actual); - byte[] buf = new byte[8192]; - int length; - while ((length = input.read(buf)) > 0) { - output.write(buf, 0, length); - } - - getLogger().info("Default configuration file written: " + name); - } catch (IOException e) { - getLogger().log(Level.WARNING, "Failed to write default config file", e); - } finally { - try { - input.close(); - } catch (IOException ignored) {} - - try { - if (output != null) { - output.close(); - } - } catch (IOException ignored) {} - } + private void copyDefaultConfig(InputStream input, File actual, String name) { + try (FileOutputStream output = new FileOutputStream(actual)) { + byte[] buf = new byte[8192]; + int length; + while ((length = input.read(buf)) > 0) { + output.write(buf, 0, length); } + + getLogger().info("Default configuration file written: " + name); + } catch (IOException e) { + getLogger().log(Level.WARNING, "Failed to write default config file", e); } } 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 83c63867a..33c2e51e0 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 @@ -20,18 +20,21 @@ package com.sk89q.worldedit.bukkit.adapter; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.blocks.BlockMaterial; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.worldedit.entity.BaseEntity; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.registry.BlockMaterial; + import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.block.Biome; import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; import java.util.Map; @@ -68,11 +71,29 @@ public interface BukkitImplAdapter extends IBukkitAdapter { * @param location the location * @return the block */ - BlockState getBlock(Location location); + BaseBlock getBlock(Location location); - boolean setBlock(Chunk chunk, int x, int y, int z, BlockStateHolder state, boolean update); + boolean setBlock(Chunk chunk, int x, int y, int z, BlockStateHolder state, boolean update); boolean isChunkInUse(Chunk chunk); + /** + * Set the block at the given location. + * + * @param location the location + * @param state the block + * @param notifyAndLight notify and light if set + * @return true if a block was likely changed + */ + boolean setBlock(Location location, BlockStateHolder state, boolean notifyAndLight); + + /** + * Notifies the simulation that the block at the given location has + * been changed and it must be re-lighted (and issue other events). + * + * @param position position of the block + * @param previousType the type of the previous block that was there + */ + void notifyAndLightBlock(Location position, BlockState previousType); /** * Get the state for the given entity. @@ -99,12 +120,12 @@ public interface BukkitImplAdapter extends IBukkitAdapter { * @param blockType The block type * @return The properties map */ - Map getProperties(BlockType blockType); + Map> getProperties(BlockType blockType); default BlockMaterial getMaterial(BlockType blockType) { return null; } - + default BlockMaterial getMaterial(BlockState blockState) { return null; } @@ -116,4 +137,21 @@ public interface BukkitImplAdapter extends IBukkitAdapter { default T fromNative(Tag foreign) { return null; } + + /** + * Send the given NBT data to the player. + * + * @param player The player + * @param pos The position + * @param nbtData The NBT Data + */ + void sendFakeNBT(Player player, BlockVector3 pos, CompoundTag nbtData); + + /** + * Make the client think it has operator status. + * This does not give them any operator capabilities. + * + * @param player The player + */ + void sendFakeOP(Player player); } diff --git a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplLoader.java b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplLoader.java index bd874167c..9d65cf46b 100644 --- a/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplLoader.java +++ b/worldedit-bukkit/src/main/java/com/sk89q/worldedit/bukkit/adapter/BukkitImplLoader.java @@ -91,7 +91,7 @@ public class BukkitImplLoader { Closer closer = Closer.create(); JarFile jar = closer.register(new JarFile(file)); try { - Enumeration entries = jar.entries(); + Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = (JarEntry) entries.nextElement(); 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 fe3009b9f..c62dbc75b 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 @@ -5,6 +5,7 @@ import com.sk89q.worldedit.bukkit.adapter.IBukkitAdapter; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.world.block.BlockState; 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.item.ItemType; import com.sk89q.worldedit.world.item.ItemTypes; @@ -52,17 +53,17 @@ public abstract class CachedBukkitAdapter implements IBukkitAdapter { @Override public ItemType asItemType(Material material) { try { - return ItemTypes.values[itemTypes[material.ordinal()]]; + return ItemTypes.get(itemTypes[material.ordinal()]); } catch (NullPointerException e) { if (init()) return asItemType(material); - return ItemTypes.values[itemTypes[material.ordinal()]]; + return ItemTypes.get(itemTypes[material.ordinal()]); } } @Override - public BlockTypes adapt(Material material) { + public BlockType adapt(Material material) { try { - return BlockTypes.values[blockTypes[material.ordinal()]]; + return BlockTypes.values[blockTypes[material.ordinal()]]; } catch (NullPointerException e) { if (init()) return adapt(material); throw e; @@ -80,7 +81,7 @@ public abstract class CachedBukkitAdapter implements IBukkitAdapter { try { checkNotNull(blockData); Material material = blockData.getMaterial(); - BlockTypes type = BlockTypes.getFromStateId(blockTypes[material.ordinal()]); + BlockType type = BlockTypes.getFromStateId(blockTypes[material.ordinal()]); List propList = type.getProperties(); if (propList.size() == 0) return type.getDefaultState(); String properties = blockData.getAsString(); 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 1e7e9e014..1f6f5f3ec 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 @@ -1,10 +1,11 @@ package com.sk89q.worldedit.bukkit.adapter; import com.sk89q.worldedit.NotABlockException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.bukkit.*; import com.sk89q.worldedit.entity.Entity; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.block.BlockState; @@ -96,7 +97,7 @@ public interface IBukkitAdapter { */ default Location adapt(org.bukkit.Location location) { checkNotNull(location); - Vector position = asVector(location); + Vector3 position = asVector(location); return new com.sk89q.worldedit.util.Location( adapt(location.getWorld()), position, @@ -112,7 +113,7 @@ public interface IBukkitAdapter { */ default org.bukkit.Location adapt(Location location) { checkNotNull(location); - Vector position = location.toVector(); + Vector3 position = location; return new org.bukkit.Location( adapt((World) location.getExtent()), position.getX(), position.getY(), position.getZ(), @@ -127,13 +128,17 @@ public interface IBukkitAdapter { * @param position the WorldEdit position * @return a Bukkit location */ - default org.bukkit.Location adapt(org.bukkit.World world, Vector position) { + default org.bukkit.Location adapt(org.bukkit.World world, Vector3 position) { checkNotNull(world); checkNotNull(position); return new org.bukkit.Location( world, position.getX(), position.getY(), position.getZ()); } + + default org.bukkit.Location adapt(org.bukkit.World world, BlockVector3 position){ + return adapt(world, position.toVector3()); + } /** * Create a Bukkit location from a WorldEdit location with a Bukkit world. @@ -158,9 +163,20 @@ public interface IBukkitAdapter { * @param location The Bukkit location * @return a WorldEdit vector */ - default Vector asVector(org.bukkit.Location location) { + default Vector3 asVector(org.bukkit.Location location) { checkNotNull(location); - return new Vector(location.getX(), location.getY(), location.getZ()); + return Vector3.at(location.getX(), location.getY(), location.getZ()); + } + + /** + * Create a WorldEdit BlockVector from a Bukkit location. + * + * @param location The Bukkit location + * @return a WorldEdit vector + */ + default BlockVector3 asBlockVector(org.bukkit.Location location) { + checkNotNull(location); + return BlockVector3.at(location.getX(), location.getY(), location.getZ()); } /** @@ -268,7 +284,7 @@ public interface IBukkitAdapter { */ BlockState adapt(BlockData blockData); - BlockTypes adapt(Material material); + BlockType adapt(Material material); /** * Create a Bukkit BlockData from a WorldEdit BlockStateHolder 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 19891fa7d..79a9b947e 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 @@ -1,6 +1,7 @@ package com.sk89q.worldedit.bukkit.adapter; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -31,7 +32,7 @@ public class SimpleBukkitAdapter extends CachedBukkitAdapter { int typeId = block.getInternalBlockTypeId(); BlockData[] dataCache = blockDataCache[typeId]; if (dataCache == null) { - BlockTypes type = BlockTypes.get(typeId); + BlockType type = BlockTypes.get(typeId); blockDataCache[typeId] = dataCache = new BlockData[type.getMaxStateId() + 1]; } int propId = block.getInternalPropertiesId(); diff --git a/worldedit-bukkit/src/main/resources/com/sk89q/worldedit/bukkit/adapter/impl/Spigot_v1_13_R1.class b/worldedit-bukkit/src/main/resources/com/sk89q/worldedit/bukkit/adapter/impl/Spigot_v1_13_R1.class new file mode 100644 index 000000000..9655a35a6 Binary files /dev/null and b/worldedit-bukkit/src/main/resources/com/sk89q/worldedit/bukkit/adapter/impl/Spigot_v1_13_R1.class differ diff --git a/worldedit-bukkit/src/main/resources/plugin.yml b/worldedit-bukkit/src/main/resources/plugin.yml index 7d6dbb247..f6d74bd1e 100644 --- a/worldedit-bukkit/src/main/resources/plugin.yml +++ b/worldedit-bukkit/src/main/resources/plugin.yml @@ -4,17 +4,15 @@ version: "${internalVersion}" api-version: 1.13 description: Fast Async WorldEdit plugin authors: [Empire92] -loadbefore: [WorldEdit,AsyncWorldEdit,AsyncWorldEditInjector,WorldGuard] load: STARTUP +loadbefore: [BannerBoard, WorldGuard, PlotSquared, AsyncWorldEdit, AsyncWorldEditInjector] database: false -#softdepend: [WorldGuard, PlotSquared, MCore, Factions, GriefPrevention, Residence, Towny, PlotMe, PreciousStones] +softdepend: [MCore, Factions, GriefPrevention, Residence, Towny, PreciousStones] permissions: fawe.plotsquared: default: true children: fawe.plotsquared.trusted: true - fawe.plotme: - default: true fawe.bypass.regions: default: false fawe.bypass: @@ -60,7 +58,6 @@ permissions: worldedit.generation.pumpkins: true worldedit.generation.pyramid: true worldedit.generation.shape: true - worldedit.biome.set: true worldedit.history.undo: true worldedit.history.redo: true worldedit.history.rollback: true diff --git a/worldedit-bukkit/src/test/java/com/sk89q/wepif/TestOfflinePermissible.java b/worldedit-bukkit/src/test/java/com/sk89q/wepif/TestOfflinePermissible.java index 21c83228f..685baafc6 100644 --- a/worldedit-bukkit/src/test/java/com/sk89q/wepif/TestOfflinePermissible.java +++ b/worldedit-bukkit/src/test/java/com/sk89q/wepif/TestOfflinePermissible.java @@ -184,4 +184,14 @@ public class TestOfflinePermissible implements OfflinePlayer, Permissible { public Map serialize() { throw new UnsupportedOperationException("Not supported yet."); } + + @Override + public long getLastLogin() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getLastSeen() { + throw new UnsupportedOperationException("Not supported yet."); + } } diff --git a/worldedit-core/build.gradle b/worldedit-core/build.gradle index 44a697af4..89a595b92 100644 --- a/worldedit-core/build.gradle +++ b/worldedit-core/build.gradle @@ -1,7 +1,7 @@ apply plugin: 'eclipse' apply plugin: 'idea' repositories { - maven {url "http://ci.athion.net/job/PlotSquared-Legacy/ws/mvn/"} + maven {url "http://ci.athion.net/job/PlotSquared-Breaking/ws/mvn/"} } dependencies { compile 'de.schlichtherle:truezip:6.8.3' @@ -12,15 +12,15 @@ dependencies { compile 'com.thoughtworks.paranamer:paranamer:2.6' compile 'com.google.code.gson:gson:2.8.0' compile 'com.sk89q.lib:jlibnoise:1.0.0' + compile 'com.googlecode.json-simple:json-simple:1.1.1' testCompile 'org.mockito:mockito-core:1.9.0-rc1' // Fawe depends compile 'org.yaml:snakeyaml:1.19' compile 'net.fabiozumbi12:redprotect:1.9.6' - compile ("com.plotsquared:plotsquared-api:latest") { + compile ("com.github.intellectualsites.plotsquared:PlotSquared-API:latest") { transitive = false } -// compile 'org.primesoft:BlocksHub:2.0' compile 'com.github.luben:zstd-jni:1.1.1' compile 'co.aikar:fastutil-lite:1.0' } diff --git a/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/LazyBlock.java b/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/LazyBlock.java index 3bf29bdd9..d87e7c571 100644 --- a/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/LazyBlock.java +++ b/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/LazyBlock.java @@ -22,11 +22,12 @@ package com.sk89q.worldedit.blocks; import static com.google.common.base.Preconditions.checkNotNull; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; /** * A implementation of a lazy block for {@link Extent#getLazyBlock(Vector)} @@ -42,7 +43,7 @@ import com.sk89q.worldedit.extent.Extent; public class LazyBlock extends BaseBlock { private final Extent extent; - private final Vector position; + private final BlockVector3 position; private boolean loaded = false; /** @@ -52,7 +53,7 @@ public class LazyBlock extends BaseBlock { * @param extent the extent to later load the full block data from * @param position the position to later load the full block data from */ - public LazyBlock(BlockType type, Extent extent, Vector position) { + public LazyBlock(BlockType type, Extent extent, BlockVector3 position) { super(type); checkNotNull(extent); checkNotNull(position); @@ -67,7 +68,7 @@ public class LazyBlock extends BaseBlock { * @param extent the extent to later load the full block data from * @param position the position to later load the full block data from */ - public LazyBlock(BlockState state, Extent extent, Vector position) { + public LazyBlock(BlockState state, Extent extent, BlockVector3 position) { super(state); checkNotNull(extent); checkNotNull(position); @@ -78,7 +79,7 @@ public class LazyBlock extends BaseBlock { @Override public CompoundTag getNbtData() { if (!loaded) { - BlockState loadedBlock = extent.getFullBlock(position); + BaseBlock loadedBlock = extent.getFullBlock(position); this.nbtData = loadedBlock.getNbtData(); loaded = true; } diff --git a/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/MobSpawnerBlock.java b/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/MobSpawnerBlock.java index 11d157824..c74c8f382 100644 --- a/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/MobSpawnerBlock.java +++ b/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/MobSpawnerBlock.java @@ -25,6 +25,7 @@ import com.sk89q.jnbt.NBTUtils; import com.sk89q.jnbt.ShortTag; import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.storage.InvalidFormatException; @@ -117,7 +118,7 @@ public class MobSpawnerBlock extends BaseBlock { @Override public CompoundTag getNbtData() { - Map values = new HashMap(); + Map values = new HashMap<>(); values.put("EntityId", new StringTag(mobType)); values.put("Delay", new ShortTag(delay)); values.put("SpawnCount", new ShortTag(spawnCount)); diff --git a/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SignBlock.java b/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SignBlock.java index 028c17014..60dabd6c7 100644 --- a/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SignBlock.java +++ b/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SignBlock.java @@ -23,8 +23,8 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.util.gson.GsonUtil; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; - import java.util.HashMap; import java.util.Map; @@ -92,7 +92,7 @@ public class SignBlock extends BaseBlock { @Override public CompoundTag getNbtData() { - Map values = new HashMap(); + Map values = new HashMap<>(); values.put("Text1", new StringTag(text[0])); values.put("Text2", new StringTag(text[1])); values.put("Text3", new StringTag(text[2])); diff --git a/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SkullBlock.java b/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SkullBlock.java index af33bc8de..e65ab3ec1 100644 --- a/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SkullBlock.java +++ b/worldedit-core/src/legacy/java/com/sk89q/worldedit/blocks/SkullBlock.java @@ -22,6 +22,7 @@ package com.sk89q.worldedit.blocks; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import java.util.HashMap; 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 4829dd13c..5bba05f4a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java @@ -10,7 +10,6 @@ import com.boydti.fawe.util.*; import com.boydti.fawe.util.chat.ChatManager; import com.boydti.fawe.util.chat.PlainChatManager; import com.boydti.fawe.util.cui.CUI; -import com.boydti.fawe.util.metrics.BStats; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.extension.factory.DefaultTransformParser; import com.sk89q.worldedit.extension.platform.Actor; @@ -18,9 +17,7 @@ import com.sk89q.worldedit.session.request.Request; import javax.annotation.Nullable; import javax.management.InstanceAlreadyExistsException; -import javax.management.Notification; import javax.management.NotificationEmitter; -import javax.management.NotificationListener; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -152,10 +149,10 @@ public class Fawe { * The platform specific implementation */ private final IFawe IMP; - private Thread thread = Thread.currentThread(); + private Thread thread; private Fawe(final IFawe implementation) { - this.INSTANCE = this; + INSTANCE = this; this.IMP = implementation; this.thread = Thread.currentThread(); /* @@ -164,26 +161,18 @@ public class Fawe { this.setupConfigs(); TaskManager.IMP = this.IMP.getTaskManager(); - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - 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); - } + 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); }); if (Settings.IMP.METRICS) { try { this.stats = new BStats(); this.IMP.startMetrics(); - TaskManager.IMP.later(new Runnable() { - @Override - public void run() { - stats.start(); - } - }, 1); - } catch (Throwable ignore) { - ignore.printStackTrace(); + TaskManager.IMP.later(() -> stats.start(), 1); + } catch (Throwable throwable) { + throwable.printStackTrace(); } } /* @@ -216,7 +205,7 @@ public class Fawe { WEManager.IMP.managers.addAll(Fawe.this.IMP.getMaskManagers()); WEManager.IMP.managers.add(new PlotSquaredFeature()); Fawe.debug("Plugin 'PlotSquared' found. Using it now."); - } catch (Throwable e) {} + } catch (Throwable ignored) {} }, 0); TaskManager.IMP.repeat(timer, 1); @@ -224,8 +213,8 @@ public class Fawe { if (!Settings.IMP.UPDATE.equalsIgnoreCase("false")) { // Delayed updating updater = new Updater(); - TaskManager.IMP.async(() -> update()); - TaskManager.IMP.repeatAsync(() -> update(), 36000); + TaskManager.IMP.async(this::update); + TaskManager.IMP.repeatAsync(this::update, 36000); } } @@ -452,16 +441,13 @@ public class Fawe { final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean(); final NotificationEmitter ne = (NotificationEmitter) memBean; - ne.addNotificationListener(new NotificationListener() { - @Override - public void handleNotification(final Notification notification, final Object handback) { - final long heapSize = Runtime.getRuntime().totalMemory(); - final long heapMaxSize = Runtime.getRuntime().maxMemory(); - if (heapSize < heapMaxSize) { - return; - } - MemUtil.memoryLimitedTask(); + ne.addNotificationListener((notification, handback) -> { + final long heapSize = Runtime.getRuntime().totalMemory(); + final long heapMaxSize = Runtime.getRuntime().maxMemory(); + if (heapSize < heapMaxSize) { + return; } + MemUtil.memoryLimitedTask(); }, null, null); final List memPools = ManagementFactory.getMemoryPoolMXBeans(); 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 435524283..a6b0275a1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/FaweAPI.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/FaweAPI.java @@ -19,47 +19,38 @@ import com.boydti.fawe.util.SetQueue; import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.WEManager; import com.boydti.fawe.wrappers.WorldWrapper; -import com.sk89q.jnbt.ByteArrayTag; -import com.sk89q.jnbt.IntTag; -import com.sk89q.jnbt.NBTInputStream; -import com.sk89q.jnbt.ShortTag; -import com.sk89q.jnbt.Tag; +import com.google.common.collect.Sets; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.extension.factory.DefaultMaskParser; import com.sk89q.worldedit.extension.factory.DefaultTransformParser; -import com.sk89q.worldedit.extension.factory.HashTagPatternParser; +import com.sk89q.worldedit.extension.factory.parser.mask.DefaultMaskParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.DefaultPatternParser; import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.internal.registry.AbstractFactory; import com.sk89q.worldedit.internal.registry.InputParser; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.AbstractWorld; import com.sk89q.worldedit.world.World; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStream; import java.lang.reflect.Field; import java.net.URL; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Set; import java.util.UUID; -import java.util.zip.GZIPInputStream; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -112,7 +103,7 @@ public class FaweAPI { * @see com.sk89q.worldedit.command.PatternCommands */ public static boolean registerPatterns(Object methods) { - HashTagPatternParser parser = getParser(HashTagPatternParser.class); + DefaultPatternParser parser = getParser(DefaultPatternParser.class); if (parser != null) parser.register(methods); return parser != null; } @@ -202,12 +193,12 @@ public class FaweAPI { List worlds = platform.getWorlds(); for (World current : worlds) { if (Fawe.imp().getWorldName(current).equals(worldName)) { - return WorldWrapper.wrap((AbstractWorld) current); + return WorldWrapper.wrap(current); } } for (World current : worlds) { if (current.getName().equals(worldName)) { - return WorldWrapper.wrap((AbstractWorld) current); + return WorldWrapper.wrap(current); } } return null; @@ -233,7 +224,7 @@ public class FaweAPI { * @see com.boydti.fawe.object.schematic.Schematic */ public static Schematic load(File file) throws IOException { - return ClipboardFormat.SCHEMATIC.load(file); + return ClipboardFormats.findByFile(file).load(file); } /** @@ -257,11 +248,10 @@ public class FaweAPI { /** * Use ThreadLocalRandom instead * - * @return */ @Deprecated public static PseudoRandom getFastRandom() { - return new PseudoRandom(); + throw new UnsupportedOperationException("Please Use ThreadLocalRandom instead."); } /** @@ -375,20 +365,17 @@ public class FaweAPI { } } World world = origin.getWorld(); - Collections.sort(files, new Comparator() { - @Override - public int compare(File a, File b) { - String aName = a.getName(); - String bName = b.getName(); - int aI = Integer.parseInt(aName.substring(0, aName.length() - 3)); - int bI = Integer.parseInt(bName.substring(0, bName.length() - 3)); - long value = aI - bI; - return value == 0 ? 0 : value < 0 ? -1 : 1; - } + files.sort((a, b) -> { + String aName = a.getName(); + String bName = b.getName(); + int aI = Integer.parseInt(aName.substring(0, aName.length() - 3)); + int bI = Integer.parseInt(bName.substring(0, bName.length() - 3)); + long value = aI - bI; + return value == 0 ? 0 : value < 0 ? -1 : 1; }); RegionWrapper bounds = new RegionWrapper(origin.x - radius, origin.x + radius, origin.z - radius, origin.z + radius); RegionWrapper boundsPlus = new RegionWrapper(bounds.minX - 64, bounds.maxX + 512, bounds.minZ - 64, bounds.maxZ + 512); - HashSet regionSet = new HashSet(Arrays.asList(bounds)); + HashSet regionSet = Sets.newHashSet(bounds); ArrayList result = new ArrayList<>(); for (File file : files) { UUID uuid = UUID.fromString(file.getParentFile().getName()); @@ -468,8 +455,8 @@ public class FaweAPI { * @return */ public static int fixLighting(World world, Region selection, @Nullable FaweQueue queue, final FaweQueue.RelightMode mode) { - final Vector bot = selection.getMinimumPoint(); - final Vector top = selection.getMaximumPoint(); + final BlockVector3 bot = selection.getMinimumPoint(); + final BlockVector3 top = selection.getMaximumPoint(); final int minX = bot.getBlockX() >> 4; final int minZ = bot.getBlockZ() >> 4; 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 44301147b..a6d9394c9 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/FaweCache.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/FaweCache.java @@ -76,7 +76,7 @@ public class FaweCache { } public static Map asMap(Object... pairs) { - HashMap map = new HashMap(pairs.length >> 1); + HashMap map = new HashMap<>(pairs.length >> 1); for (int i = 0; i < pairs.length; i += 2) { String key = (String) pairs[i]; Object value = pairs[i + 1]; @@ -174,7 +174,7 @@ public class FaweCache { if (clazz.getName().startsWith("com.intellectualcrafters.jnbt")) { try { if (clazz.getName().equals("com.intellectualcrafters.jnbt.EndTag")) { - return EndTag.INSTANCE; + return new EndTag(); } Field field = clazz.getDeclaredField("value"); field.setAccessible(true); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/IFawe.java b/worldedit-core/src/main/java/com/boydti/fawe/IFawe.java index 5708ee912..ecba46a2f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/IFawe.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/IFawe.java @@ -6,63 +6,60 @@ import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.regions.FaweMaskManager; import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.cui.CUI; -import com.boydti.fawe.util.gui.FormBuilder; import com.boydti.fawe.util.image.ImageViewer; import com.sk89q.worldedit.world.World; + import java.io.File; import java.util.Collection; import java.util.UUID; public interface IFawe { - public void debug(final String s); + void debug(final String s); - public File getDirectory(); + File getDirectory(); - public void setupCommand(final String label, final FaweCommand cmd); + void setupCommand(final String label, final FaweCommand cmd); - public FawePlayer wrap(final Object obj); + FawePlayer wrap(final Object obj); - public void setupVault(); + void setupVault(); - public TaskManager getTaskManager(); + TaskManager getTaskManager(); - public FaweQueue getNewQueue(World world, boolean fast); + FaweQueue getNewQueue(World world, boolean fast); - public FaweQueue getNewQueue(String world, boolean fast); + FaweQueue getNewQueue(String world, boolean fast); - public String getWorldName(World world); + String getWorldName(World world); - public Collection getMaskManagers(); + Collection getMaskManagers(); - public void startMetrics(); + void startMetrics(); default CUI getCUI(FawePlayer player) { return null; } default ImageViewer getImageViewer(FawePlayer player) { return null; } - public default void registerPacketListener() {} + default void registerPacketListener() {} default int getPlayerCount() { return Fawe.get().getCachedPlayers().size(); } - public String getPlatformVersion(); + String getPlatformVersion(); - public boolean isOnlineMode(); + boolean isOnlineMode(); - public String getPlatform(); + String getPlatform(); - public UUID getUUID(String name); + UUID getUUID(String name); - public String getName(UUID uuid); + String getName(UUID uuid); - public Object getBlocksHubApi(); + Object getBlocksHubApi(); - public default String getDebugInfo() { + default String getDebugInfo() { return ""; } - public default FormBuilder getFormBuilder() { - return null; - } } 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 a39c0f203..c4a1be496 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 @@ -21,14 +21,12 @@ import com.boydti.fawe.util.StringMan; import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.blocks.BlockType; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.RandomPattern; import com.sk89q.worldedit.internal.annotation.Selection; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.command.binding.Switch; @@ -396,8 +394,8 @@ public class AnvilCommands { ) @CommandPermissions("worldedit.anvil.clear") public void unset(Player player, EditSession editSession, @Selection Region selection) throws WorldEditException { - Vector bot = selection.getMinimumPoint(); - Vector top = selection.getMaximumPoint(); + BlockVector3 bot = selection.getMinimumPoint(); + BlockVector3 top = selection.getMaximumPoint(); RegionWrapper region = new RegionWrapper(bot, top); MCAFilterCounter filter = new MCAFilterCounter() { @@ -618,8 +616,8 @@ public class AnvilCommands { ) @CommandPermissions("worldedit.anvil.removelayer") public void removeLayers(Player player, EditSession editSession, @Selection Region selection, int id) throws WorldEditException { - Vector min = selection.getMinimumPoint(); - Vector max = selection.getMaximumPoint(); + BlockVector3 min = selection.getMinimumPoint(); + BlockVector3 max = selection.getMaximumPoint(); int minY = min.getBlockY(); int maxY = max.getBlockY(); RemoveLayerFilter filter = new RemoveLayerFilter(minY, maxY, id); @@ -644,7 +642,7 @@ public class AnvilCommands { String worldName = Fawe.imp().getWorldName(editSession.getWorld()); FaweQueue tmp = SetQueue.IMP.getNewQueue(worldName, true, false); MCAQueue queue = new MCAQueue(tmp); - Vector origin = session.getPlacementPosition(player); + BlockVector3 origin = session.getPlacementPosition(player); MCAClipboard clipboard = new MCAClipboard(queue, cuboid, origin); FawePlayer fp = FawePlayer.wrap(player); fp.setMeta(FawePlayer.METADATA_KEYS.ANVIL_CLIPBOARD, clipboard); 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 e5cb2539b..22d6b21f3 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 @@ -12,35 +12,38 @@ import com.boydti.fawe.object.pattern.PatternExtent; import com.boydti.fawe.util.*; import com.boydti.fawe.util.chat.Message; import com.boydti.fawe.util.image.ImageUtil; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.commands.Auto; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.worlds.PlotAreaManager; -import com.intellectualcrafters.plot.object.worlds.SinglePlotArea; -import com.intellectualcrafters.plot.object.worlds.SinglePlotAreaManager; -import com.intellectualcrafters.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.commands.Auto; +import com.github.intellectualsites.plotsquared.plot.config.Captions; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.command.MethodCommands; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.registry.state.PropertyKey; import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.session.request.Request; @@ -85,7 +88,7 @@ public class CFICommands extends MethodCommands { } private File getFolder(String worldName) { - return new File(PS.imp().getWorldContainer(), worldName + File.separator + "region"); + return new File(PlotSquared.imp().getWorldContainer(), worldName + File.separator + "region"); } @Command( @@ -172,7 +175,7 @@ public class CFICommands extends MethodCommands { } @Deprecated - public static void autoClaimFromDatabase(PlotPlayer player, PlotArea area, PlotId start, com.intellectualcrafters.plot.object.RunnableVal whenDone) { + public static void autoClaimFromDatabase(PlotPlayer player, PlotArea area, PlotId start, com.github.intellectualsites.plotsquared.plot.object.RunnableVal whenDone) { final Plot plot = area.getNextFreePlot(player, start); if (plot == null) { whenDone.run(null); @@ -197,7 +200,7 @@ public class CFICommands extends MethodCommands { public void done(FawePlayer fp) throws ParameterException, IOException { CFISettings settings = assertSettings(fp); - PlotAreaManager manager = PS.get().getPlotAreaManager(); + PlotAreaManager manager = PlotSquared.get().getPlotAreaManager(); if (manager instanceof SinglePlotAreaManager) { SinglePlotAreaManager sManager = (SinglePlotAreaManager) manager; SinglePlotArea area = sManager.getArea(); @@ -210,7 +213,7 @@ public class CFICommands extends MethodCommands { int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(area.worldname); int diff = player.getAllowedPlots() - currentPlots; if (diff < 1) { - C.CANT_CLAIM_MORE_PLOTS_NUM.send(player, -diff); + Captions.CANT_CLAIM_MORE_PLOTS_NUM.send(player, -diff); return; } @@ -421,7 +424,7 @@ public class CFICommands extends MethodCommands { ClipboardHolder holder = fp.getSession().getClipboard(); Clipboard clipboard = holder.getClipboard(); boolean[] ids = new boolean[BlockTypes.size()]; - for (Vector pt : clipboard.getRegion()) { + for (BlockVector3 pt : clipboard.getRegion()) { ids[clipboard.getBlock(pt).getInternalBlockTypeId()] = true; } blocks = new HashSet<>(); @@ -447,7 +450,7 @@ public class CFICommands extends MethodCommands { BlockType type = BlockTypes.get(typeId); BlockStateHolder block = type.getDefaultState(); pattern.setBlock(block); - if (mask.test(Vector.ZERO)) blocks.add(type); + if (mask.test(BlockVector3.ZERO)) blocks.add(type); } break; } @@ -501,7 +504,7 @@ public class CFICommands extends MethodCommands { HeightMapMCAGenerator gen = assertSettings(fp).getGenerator(); World world = fp.getWorld(); - MultiClipboardHolder multi = ClipboardFormat.SCHEMATIC.loadAllFromInput(fp.getPlayer(), schematic, null, true); + MultiClipboardHolder multi = ClipboardFormats.loadAllFromInput(fp.getPlayer(), schematic, null, true); if (multi == null) { return; } @@ -663,7 +666,7 @@ public class CFICommands extends MethodCommands { public void tp(FawePlayer fp) throws ParameterException, WorldEditException { HeightMapMCAGenerator gen = assertSettings(fp).getGenerator(); msg("Teleporting...").send(fp); - Vector origin = gen.getOrigin(); + Vector3 origin = gen.getOrigin(); Player player = fp.getPlayer(); player.setPosition(origin.subtract(16, 0, 16)); player.findFreePosition(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/FaweBinding.java b/worldedit-core/src/main/java/com/boydti/fawe/command/FaweBinding.java index 73b8c7a25..2973feb5e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/FaweBinding.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/command/FaweBinding.java @@ -1,13 +1,12 @@ package com.boydti.fawe.command; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.internal.command.WorldEditBinding; +import com.sk89q.worldedit.util.command.parametric.BindingHelper; -public class FaweBinding extends WorldEditBinding { +public class FaweBinding extends BindingHelper { private final WorldEdit worldEdit; public FaweBinding(WorldEdit worldEdit) { - super(worldEdit); this.worldEdit = worldEdit; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/FawePrimitiveBinding.java b/worldedit-core/src/main/java/com/boydti/fawe/command/FawePrimitiveBinding.java index c3c6b6a94..0a2c76534 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/FawePrimitiveBinding.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/command/FawePrimitiveBinding.java @@ -9,8 +9,6 @@ import com.boydti.fawe.util.TextureUtil; import com.boydti.fawe.util.image.ImageUtil; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.Player; @@ -22,6 +20,10 @@ import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.ExpressionException; import com.sk89q.worldedit.internal.expression.runtime.EvaluationException; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector2; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.util.command.binding.Range; import com.sk89q.worldedit.util.command.binding.Text; @@ -40,7 +42,7 @@ import java.net.URI; import java.net.URL; import javax.annotation.Nullable; -public class FawePrimitiveBinding extends BindingHelper { +public class FawePrimitiveBinding { @BindingMatch(type = {Long.class, long.class}, behavior = BindingBehavior.CONSUMES, consumedCount = 1, @@ -257,11 +259,11 @@ public class FawePrimitiveBinding extends BindingHelper { * @return the requested type * @throws ParameterException on error */ - @BindingMatch(type = Vector.class, + @BindingMatch(type = Vector3.class, behavior = BindingBehavior.CONSUMES, consumedCount = 1, provideModifiers = true) - public Vector getVector(ArgumentStack context, Annotation[] modifiers) throws ParameterException { + public Vector3 getVector3(ArgumentStack context, Annotation[] modifiers) throws ParameterException { String radiusString = context.next(); String[] radii = radiusString.split(","); final double radiusX, radiusY, radiusZ; @@ -279,7 +281,7 @@ public class FawePrimitiveBinding extends BindingHelper { default: throw new ParameterException("You must either specify 1 or 3 radius values."); } - return new Vector(radiusX, radiusY, radiusZ); + return Vector3.at(radiusX, radiusY, radiusZ); } @@ -290,11 +292,11 @@ public class FawePrimitiveBinding extends BindingHelper { * @return the requested type * @throws ParameterException on error */ - @BindingMatch(type = Vector2D.class, + @BindingMatch(type = Vector2.class, behavior = BindingBehavior.CONSUMES, consumedCount = 1, provideModifiers = true) - public Vector2D getVector2D(ArgumentStack context, Annotation[] modifiers) throws ParameterException { + public Vector2 getVector2(ArgumentStack context, Annotation[] modifiers) throws ParameterException { String radiusString = context.next(); String[] radii = radiusString.split(","); final double radiusX, radiusZ; @@ -311,8 +313,70 @@ public class FawePrimitiveBinding extends BindingHelper { default: throw new ParameterException("You must either specify 1 or 2 radius values."); } - return new Vector2D(radiusX, radiusZ); - } + return Vector2.at(radiusX, radiusZ); + } /** + * Gets a type from a {@link ArgumentStack}. + * + * @param context the context + * @return the requested type + * @throws ParameterException on error + */ + @BindingMatch(type = BlockVector3.class, + behavior = BindingBehavior.CONSUMES, + consumedCount = 1, + provideModifiers = true) + public BlockVector3 getBlockVector3(ArgumentStack context, Annotation[] modifiers) throws ParameterException { + String radiusString = context.next(); + String[] radii = radiusString.split(","); + final double radiusX, radiusY, radiusZ; + switch (radii.length) { + case 1: + radiusX = radiusY = radiusZ = Math.max(1, FawePrimitiveBinding.parseNumericInput(radii[0])); + break; + + case 3: + radiusX = Math.max(1, FawePrimitiveBinding.parseNumericInput(radii[0])); + radiusY = Math.max(1, FawePrimitiveBinding.parseNumericInput(radii[1])); + radiusZ = Math.max(1, FawePrimitiveBinding.parseNumericInput(radii[2])); + break; + + default: + throw new ParameterException("You must either specify 1 or 3 radius values."); + } + return BlockVector3.at(radiusX, radiusY, radiusZ); + } + + + /** + * Gets a type from a {@link ArgumentStack}. + * + * @param context the context + * @return the requested type + * @throws ParameterException on error + */ + @BindingMatch(type = BlockVector2.class, + behavior = BindingBehavior.CONSUMES, + consumedCount = 1, + provideModifiers = true) + public BlockVector2 getBlockVector2(ArgumentStack context, Annotation[] modifiers) throws ParameterException { + String radiusString = context.next(); + String[] radii = radiusString.split(","); + final double radiusX, radiusZ; + switch (radii.length) { + case 1: + radiusX = radiusZ = Math.max(1, FawePrimitiveBinding.parseNumericInput(radii[0])); + break; + + case 2: + radiusX = Math.max(1, FawePrimitiveBinding.parseNumericInput(radii[0])); + radiusZ = Math.max(1, FawePrimitiveBinding.parseNumericInput(radii[1])); + break; + + default: + throw new ParameterException("You must either specify 1 or 2 radius values."); + } + return BlockVector2.at(radiusX, radiusZ); + } /** * Try to parse numeric input as either a number or a mathematical expression. diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/MaskBinding.java b/worldedit-core/src/main/java/com/boydti/fawe/command/MaskBinding.java index 2173aff6b..5711c43a4 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/MaskBinding.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/command/MaskBinding.java @@ -1,7 +1,6 @@ package com.boydti.fawe.command; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.extension.factory.DefaultMaskParser; import com.sk89q.worldedit.util.command.parametric.ParameterData; import com.sk89q.worldedit.world.block.BlockTypes; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/PatternBinding.java b/worldedit-core/src/main/java/com/boydti/fawe/command/PatternBinding.java index 078042d21..fb05ed40a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/PatternBinding.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/command/PatternBinding.java @@ -4,8 +4,6 @@ import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.util.command.parametric.ParameterData; import com.sk89q.worldedit.world.block.BlockTypes; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/config/BBC.java b/worldedit-core/src/main/java/com/boydti/fawe/config/BBC.java index 33d853177..57fc2d9b1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/config/BBC.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/config/BBC.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; public enum BBC { @@ -523,7 +524,7 @@ public enum BBC { } public BBC or(BBC... others) { - int index = PseudoRandom.random.nextInt(others.length + 1); + int index = ThreadLocalRandom.current().nextInt(others.length + 1); return index == 0 ? this : others[index - 1]; } 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 b4d115097..1f0b1474c 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 @@ -33,9 +33,9 @@ public final class TypeDescription { public TypeDescription(Class clazz, Tag tag) { this.type = clazz; this.tag = tag; - listProperties = new HashMap>(); - keyProperties = new HashMap>(); - valueProperties = new HashMap>(); + listProperties = new HashMap<>(); + keyProperties = new HashMap<>(); + valueProperties = new HashMap<>(); } public TypeDescription(Class clazz, String tag) { 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 470c3090d..400d19c24 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 @@ -175,7 +175,7 @@ public class Yaml { * @return YAML String */ public String dump(Object data) { - List list = new ArrayList(1); + List list = new ArrayList<>(1); list.add(data); return dumpAll(list.iterator()); } @@ -215,7 +215,7 @@ public class Yaml { * stream to write to */ public void dump(Object data, Writer output) { - List list = new ArrayList(1); + List list = new ArrayList<>(1); list.add(data); dumpAll(list.iterator(), output, null); } @@ -292,7 +292,7 @@ public class Yaml { if (flowStyle != null) { representer.setDefaultFlowStyle(flowStyle); } - List list = new ArrayList(1); + List list = new ArrayList<>(1); list.add(data); StringWriter buffer = new StringWriter(); dumpAll(list.iterator(), buffer, rootTag); @@ -345,7 +345,7 @@ public class Yaml { } private static class SilentEmitter implements Emitable { - private List events = new ArrayList(100); + private List events = new ArrayList<>(100); public List getEvents() { return events; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/configuration/serialization/ConfigurationSerialization.java b/worldedit-core/src/main/java/com/boydti/fawe/configuration/serialization/ConfigurationSerialization.java index 05f6464a6..445702c6f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/configuration/serialization/ConfigurationSerialization.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/configuration/serialization/ConfigurationSerialization.java @@ -16,7 +16,7 @@ public class ConfigurationSerialization { public static final String SERIALIZED_TYPE_KEY = "=="; private static final Map> aliases = - new HashMap>(); + new HashMap<>(); private final Class clazz; protected ConfigurationSerialization(Class clazz) { 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 f29066d04..6e11ca542 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 @@ -9,7 +9,8 @@ import com.boydti.fawe.object.changeset.DiskStorageHistory; import com.boydti.fawe.object.task.AsyncNotifyQueue; import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.TaskManager; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.world.World; import java.io.File; import java.io.IOException; @@ -126,7 +127,7 @@ public class RollbackDatabase extends AsyncNotifyQueue { }); } - public void getPotentialEdits(final UUID uuid, final long minTime, final Vector pos1, final Vector pos2, final RunnableVal onEach, final Runnable whenDone, final boolean delete, final boolean ascending) { + public void getPotentialEdits(final UUID uuid, final long minTime, final BlockVector3 pos1, final BlockVector3 pos2, final RunnableVal onEach, final Runnable whenDone, final boolean delete, final boolean ascending) { final World world = FaweAPI.getWorld(this.worldName); addTask(new Runnable() { @Override diff --git a/worldedit-core/src/main/java/com/boydti/fawe/example/IntFaweChunk.java b/worldedit-core/src/main/java/com/boydti/fawe/example/IntFaweChunk.java index 8b284ab89..6b924faaf 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/example/IntFaweChunk.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/example/IntFaweChunk.java @@ -163,7 +163,7 @@ public abstract class IntFaweChunk extends FaweChunk @Override public Map getTiles() { - return tiles == null ? new HashMap() : tiles; + return tiles == null ? new HashMap<>() : tiles; } @Override @@ -189,7 +189,7 @@ public abstract class IntFaweChunk extends FaweChunk @Override public HashSet getEntityRemoves() { - return entityRemoves == null ? new HashSet() : entityRemoves; + return entityRemoves == null ? new HashSet<>() : entityRemoves; } @Override @@ -202,16 +202,12 @@ public abstract class IntFaweChunk extends FaweChunk } vs[j] = combinedId; this.count[i]++; - switch (BlockTypes.getFromStateId(combinedId)) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - this.air[i]++; - return; - default: - heightMap[z << 4 | x] = (byte) y; - return; + if (BlockTypes.getFromStateId(combinedId).getMaterial().isAir()) { + this.air[i]++; + return; } + heightMap[z << 4 | x] = (byte) y; + return; } @Deprecated diff --git a/worldedit-core/src/main/java/com/boydti/fawe/example/MappedFaweQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/example/MappedFaweQueue.java index 7645ef234..1c5c6fda8 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/example/MappedFaweQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/example/MappedFaweQueue.java @@ -111,12 +111,7 @@ public abstract class MappedFaweQueue impl map.forEachChunk(new RunnableVal() { @Override public void run(final FaweChunk chunk) { - pool.submit(new Runnable() { - @Override - public void run() { - chunk.optimize(); - } - }); + pool.submit(chunk::optimize); } }); pool.awaitQuiescence(Long.MAX_VALUE, TimeUnit.MILLISECONDS); @@ -300,8 +295,8 @@ public abstract class MappedFaweQueue impl @Override public boolean supports(Capability capability) { - switch (capability) { - case CHANGE_TASKS: return true; + if (capability == Capability.CHANGE_TASKS) { + return true; } return false; } @@ -416,12 +411,7 @@ public abstract class MappedFaweQueue impl public boolean queueChunkLoad(final int cx, final int cz) { CHUNK chunk = getCachedChunk(getWorld(), cx, cz); if (chunk == null) { - SetQueue.IMP.addTask(new Runnable() { - @Override - public void run() { - loadChunk(getWorld(), cx, cz, true); - } - }); + SetQueue.IMP.addTask(() -> loadChunk(getWorld(), cx, cz, true)); return true; } return false; @@ -430,12 +420,9 @@ public abstract class MappedFaweQueue impl public boolean queueChunkLoad(final int cx, final int cz, RunnableVal operation) { operation.value = getCachedChunk(getWorld(), cx, cz); if (operation.value == null) { - SetQueue.IMP.addTask(new Runnable() { - @Override - public void run() { - operation.value = loadChunk(getWorld(), cx, cz, true); - if (operation.value != null) TaskManager.IMP.async(operation); - } + SetQueue.IMP.addTask(() -> { + operation.value = loadChunk(getWorld(), cx, cz, true); + if (operation.value != null) TaskManager.IMP.async(operation); }); return true; } else { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/example/NMSMappedFaweQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/example/NMSMappedFaweQueue.java index 7c12c2878..33b475905 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/example/NMSMappedFaweQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/example/NMSMappedFaweQueue.java @@ -40,14 +40,11 @@ public abstract class NMSMappedFaweQueue ex public void runTasks() { super.runTasks(); if (!getRelighter().isEmpty()) { - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - if (getSettings().IMP.LIGHTING.REMOVE_FIRST) { - getRelighter().removeAndRelight(hasSky()); - } else { - getRelighter().fixLightingSafe(hasSky()); - } + TaskManager.IMP.async(() -> { + if (getSettings().IMP.LIGHTING.REMOVE_FIRST) { + getRelighter().removeAndRelight(hasSky()); + } else { + getRelighter().fixLightingSafe(hasSky()); } }); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/example/WeakFaweQueueMap.java b/worldedit-core/src/main/java/com/boydti/fawe/example/WeakFaweQueueMap.java index e5c5a87ae..681745ec4 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/example/WeakFaweQueueMap.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/example/WeakFaweQueueMap.java @@ -123,7 +123,7 @@ public class WeakFaweQueueMap implements IFaweQueueMap { @Override public void add(FaweChunk chunk) { long pair = MathMan.pairInt(chunk.getX(), chunk.getZ()); - Reference previous = this.blocks.put(pair, new SoftReference(chunk)); + Reference previous = this.blocks.put(pair, new SoftReference<>(chunk)); if (previous != null) { FaweChunk previousChunk = previous.get(); if (previousChunk != null) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/CorruptSchematicStreamer.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/CorruptSchematicStreamer.java index a58f9f377..c3e7c046c 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/CorruptSchematicStreamer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/CorruptSchematicStreamer.java @@ -9,10 +9,11 @@ import com.boydti.fawe.object.clipboard.MemoryOptimizedClipboard; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.ListTag; import com.sk89q.jnbt.NBTInputStream; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.CuboidRegion; import java.io.BufferedInputStream; import java.io.DataInputStream; @@ -81,7 +82,7 @@ public class CorruptSchematicStreamer { if (fc != null) { return fc; } - Vector dimensions = guessDimensions(volume.get(), width.get(), height.get(), length.get()); + BlockVector3 dimensions = guessDimensions(volume.get(), width.get(), height.get(), length.get()); if (width.get() == 0 || height.get() == 0 || length.get() == 0) { Fawe.debug("No dimensions found! Estimating based on factors:" + dimensions); } @@ -265,21 +266,21 @@ public class CorruptSchematicStreamer { // } } - private Vector guessDimensions(int volume, int width, int height, int length) { + private BlockVector3 guessDimensions(int volume, int width, int height, int length) { if (volume == 0) { - return new Vector(width, height, length); + return BlockVector3.at(width, height, length); } if (volume == width * height * length) { - return new Vector(width, height, length); + return BlockVector3.at(width, height, length); } if (width == 0 && height != 0 && length != 0 && volume % (height * length) == 0 && height * length <= volume) { - return new Vector(volume / (height * length), height, length); + return BlockVector3.at(volume / (height * length), height, length); } if (height == 0 && width != 0 && length != 0 && volume % (width * length) == 0 && width * length <= volume) { - return new Vector(width, volume / (width * length), length); + return BlockVector3.at(width, volume / (width * length), length); } if (length == 0 && height != 0 && width != 0 && volume % (height * width) == 0 && height * width <= volume) { - return new Vector(width, height, volume / (width * height)); + return BlockVector3.at(width, height, volume / (width * height)); } List factors = new ArrayList<>(); for (int i = (int) Math.sqrt(volume); i > 0; i--) { @@ -289,7 +290,7 @@ public class CorruptSchematicStreamer { } } int min = Integer.MAX_VALUE; - Vector dimensions = new Vector(); + int vx = 0, vy = 0, vz = 0; for (int x = 0; x < factors.size(); x++) { int xValue = factors.get(x); for (int y = 0; y < factors.size(); y++) { @@ -300,12 +301,14 @@ public class CorruptSchematicStreamer { int max = Math.max(Math.max(xValue, yValue), z); if (max < min) { min = max; - dimensions = new Vector(xValue, z, yValue); + vx = xValue; + vz = z; + vy = yValue; } } } } - return dimensions; + return BlockVector3.at(vx, vz, vy); } public interface CorruptReader { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/JSON2NBT.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/JSON2NBT.java index 97eadc54d..9d53caec8 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/JSON2NBT.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/JSON2NBT.java @@ -406,7 +406,7 @@ public class JSON2NBT { } public Tag parse() throws NBTException { - HashMap map = new HashMap(); + HashMap map = new HashMap<>(); Iterator var2 = this.tagList.iterator(); while (var2.hasNext()) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/NBTStreamer.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/NBTStreamer.java index 15dd8036e..172f5f67c 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/NBTStreamer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/NBTStreamer.java @@ -9,24 +9,18 @@ import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.util.HashMap; -import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Function; public class NBTStreamer { private final NBTInputStream is; - private final Map readers; + private final HashMap readers; public NBTStreamer(NBTInputStream stream) { this.is = stream; readers = new HashMap<>(); } - public NBTStreamer(NBTInputStream stream, Map readers) { - this.is = stream; - this.readers = readers; - } - /** * Reads the entire stream and runs the applicable readers * diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java index 670107c7b..2ecfc7101 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/SchematicStreamer.java @@ -14,12 +14,11 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.ListTag; import com.sk89q.jnbt.NBTInputStream; import com.sk89q.jnbt.StringTag; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BlockMaterial; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.registry.state.PropertyKey; import com.sk89q.worldedit.util.Direction; @@ -27,6 +26,7 @@ import com.sk89q.worldedit.world.block.*; import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.entity.EntityTypes; import com.sk89q.worldedit.world.item.ItemTypes; +import com.sk89q.worldedit.world.registry.BlockMaterial; import com.sk89q.worldedit.world.registry.LegacyMapper; import net.jpountz.lz4.LZ4BlockInputStream; import net.jpountz.lz4.LZ4BlockOutputStream; @@ -49,7 +49,7 @@ public class SchematicStreamer extends NBTStreamer { public SchematicStreamer(NBTInputStream stream, UUID uuid) { super(stream); this.uuid = uuid; - clipboard = new BlockArrayClipboard(new CuboidRegion(new Vector(0, 0, 0), new Vector(0, 0, 0)), fc); + clipboard = new BlockArrayClipboard(new CuboidRegion(BlockVector3.at(0, 0, 0), BlockVector3.at(0, 0, 0)), fc); } public void addBlockReaders() throws IOException { @@ -133,39 +133,33 @@ public class SchematicStreamer extends NBTStreamer { addReader("Schematic.Biomes.#", biomeReader); // FAWE stores as a byte[] (4x smaller) // Tiles - addReader("Schematic.TileEntities.#", new BiConsumer() { - @Override - public void accept(Integer index, CompoundTag value) { - if (fc == null) { - setupClipboard(0); - } - int x = value.getInt("x"); - int y = value.getInt("y"); - int z = value.getInt("z"); - fc.setTile(x, y, z, value); + addReader("Schematic.TileEntities.#", (BiConsumer) (index, value) -> { + if (fc == null) { + setupClipboard(0); } + int x = value.getInt("x"); + int y = value.getInt("y"); + int z = value.getInt("z"); + fc.setTile(x, y, z, value); }); // Entities - addReader("Schematic.Entities.#", new BiConsumer() { - @Override - public void accept(Integer index, CompoundTag compound) { - if (fc == null) { - setupClipboard(0); - } - String id = compound.getString("id"); - if (id.isEmpty()) { - return; - } - ListTag positionTag = compound.getListTag("Pos"); - ListTag directionTag = compound.getListTag("Rotation"); - EntityType type = EntityTypes.parse(id); - if (type != null) { - compound.getValue().put("Id", new StringTag(type.getId())); - BaseEntity state = new BaseEntity(type, compound); - fc.createEntity(clipboard, positionTag.asDouble(0), positionTag.asDouble(1), positionTag.asDouble(2), (float) directionTag.asDouble(0), (float) directionTag.asDouble(1), state); - } else { - Fawe.debug("Invalid entity: " + id); - } + addReader("Schematic.Entities.#", (BiConsumer) (index, compound) -> { + if (fc == null) { + setupClipboard(0); + } + String id = compound.getString("id"); + if (id.isEmpty()) { + return; + } + ListTag positionTag = compound.getListTag("Pos"); + ListTag directionTag = compound.getListTag("Rotation"); + EntityType type = EntityTypes.parse(id); + if (type != null) { + compound.getValue().put("Id", new StringTag(type.getId())); + BaseEntity state = new BaseEntity(type, compound); + fc.createEntity(clipboard, positionTag.asDouble(0), positionTag.asDouble(1), positionTag.asDouble(2), (float) directionTag.asDouble(0), (float) directionTag.asDouble(1), state); + } else { + Fawe.debug("Invalid entity: " + id); } }); } @@ -180,7 +174,7 @@ public class SchematicStreamer extends NBTStreamer { FaweInputStream dataIn = new FaweInputStream(new LZ4BlockInputStream(new FastByteArraysInputStream(dataOut.toByteArrays()))); LegacyMapper remap = LegacyMapper.getInstance(); - Vector dimensions = fc.getDimensions(); + BlockVector3 dimensions = fc.getDimensions(); int length = dimensions.getBlockX() * dimensions.getBlockY() * dimensions.getBlockZ(); if (adds == null) { for (int i = 0; i < length; i++) { @@ -200,47 +194,47 @@ public class SchematicStreamer extends NBTStreamer { private void fixStates() { fc.forEach(new FaweClipboard.BlockReader() { @Override - public void run(int x, int y, int z, BlockState block) { - BlockTypes type = block.getBlockType(); - switch (type) { - case ACACIA_STAIRS: - case BIRCH_STAIRS: - case BRICK_STAIRS: - case COBBLESTONE_STAIRS: - case DARK_OAK_STAIRS: - case DARK_PRISMARINE_STAIRS: - case JUNGLE_STAIRS: - case NETHER_BRICK_STAIRS: - case OAK_STAIRS: - case PRISMARINE_BRICK_STAIRS: - case PRISMARINE_STAIRS: - case PURPUR_STAIRS: - case QUARTZ_STAIRS: - case RED_SANDSTONE_STAIRS: - case SANDSTONE_STAIRS: - case SPRUCE_STAIRS: - case STONE_BRICK_STAIRS: + public > void run(int x, int y, int z, B block) { + BlockType type = block.getBlockType(); + switch (type.getResource().toUpperCase()) { + case "ACACIA_STAIRS": + case "BIRCH_STAIRS": + case "BRICK_STAIRS": + case "COBBLESTONE_STAIRS": + case "DARK_OAK_STAIRS": + case "DARK_PRISMARINE_STAIRS": + case "JUNGLE_STAIRS": + case "NETHER_BRICK_STAIRS": + case "OAK_STAIRS": + case "PRISMARINE_BRICK_STAIRS": + case "PRISMARINE_STAIRS": + case "PURPUR_STAIRS": + case "QUARTZ_STAIRS": + case "RED_SANDSTONE_STAIRS": + case "SANDSTONE_STAIRS": + case "SPRUCE_STAIRS": + case "STONE_BRICK_STAIRS": Object half = block.getState(PropertyKey.HALF); Direction facing = block.getState(PropertyKey.FACING); - BlockVector forward = facing.toBlockVector(); + BlockVector3 forward = facing.toBlockVector(); Direction left = facing.getLeft(); Direction right = facing.getRight(); BlockStateHolder forwardBlock = fc.getBlock(x + forward.getBlockX(), y + forward.getBlockY(), z + forward.getBlockZ()); - BlockTypes forwardType = forwardBlock.getBlockType(); + BlockType forwardType = forwardBlock.getBlockType(); if (forwardType.hasProperty(PropertyKey.SHAPE) && forwardType.hasProperty(PropertyKey.FACING)) { Direction forwardFacing = (Direction) forwardBlock.getState(PropertyKey.FACING); if (forwardFacing == left) { BlockStateHolder rightBlock = fc.getBlock(x + right.getBlockX(), y + right.getBlockY(), z + right.getBlockZ()); - BlockTypes rightType = rightBlock.getBlockType(); + BlockType rightType = rightBlock.getBlockType(); if (!rightType.hasProperty(PropertyKey.SHAPE) || rightBlock.getState(PropertyKey.FACING) != facing) { fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "inner_left")); } return; } else if (forwardFacing == right) { BlockStateHolder leftBlock = fc.getBlock(x + left.getBlockX(), y + left.getBlockY(), z + left.getBlockZ()); - BlockTypes leftType = leftBlock.getBlockType(); + BlockType leftType = leftBlock.getBlockType(); if (!leftType.hasProperty(PropertyKey.SHAPE) || leftBlock.getState(PropertyKey.FACING) != facing) { fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "inner_right")); } @@ -249,19 +243,19 @@ public class SchematicStreamer extends NBTStreamer { } BlockStateHolder backwardsBlock = fc.getBlock(x - forward.getBlockX(), y - forward.getBlockY(), z - forward.getBlockZ()); - BlockTypes backwardsType = backwardsBlock.getBlockType(); + BlockType backwardsType = backwardsBlock.getBlockType(); if (backwardsType.hasProperty(PropertyKey.SHAPE) && backwardsType.hasProperty(PropertyKey.FACING)) { Direction backwardsFacing = (Direction) backwardsBlock.getState(PropertyKey.FACING); if (backwardsFacing == left) { BlockStateHolder rightBlock = fc.getBlock(x + right.getBlockX(), y + right.getBlockY(), z + right.getBlockZ()); - BlockTypes rightType = rightBlock.getBlockType(); + BlockType rightType = rightBlock.getBlockType(); if (!rightType.hasProperty(PropertyKey.SHAPE) || rightBlock.getState(PropertyKey.FACING) != facing) { fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "outer_left")); } return; } else if (backwardsFacing == right) { BlockStateHolder leftBlock = fc.getBlock(x + left.getBlockX(), y + left.getBlockY(), z + left.getBlockZ()); - BlockTypes leftType = leftBlock.getBlockType(); + BlockType leftType = leftBlock.getBlockType(); if (!leftType.hasProperty(PropertyKey.SHAPE) || leftBlock.getState(PropertyKey.FACING) != facing) { fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "outer_right")); } @@ -301,43 +295,43 @@ public class SchematicStreamer extends NBTStreamer { private boolean merge(int group, int x, int y, int z) { BlockStateHolder block = fc.getBlock(x, y, z); - BlockTypes type = block.getBlockType(); + BlockType type = block.getBlockType(); return group(type) == group || fullCube.apply(type); } - private int group(BlockTypes type) { - switch (type) { - case ACACIA_FENCE: - case BIRCH_FENCE: - case DARK_OAK_FENCE: - case JUNGLE_FENCE: - case OAK_FENCE: - case SPRUCE_FENCE: + private int group(BlockType type) { + switch (type.getResource().toUpperCase()) { + case "ACACIA_FENCE": + case "BIRCH_FENCE": + case "DARK_OAK_FENCE": + case "JUNGLE_FENCE": + case "OAK_FENCE": + case "SPRUCE_FENCE": return 0; - case NETHER_BRICK_FENCE: + case "NETHER_BRICK_FENCE": return 1; - case COBBLESTONE_WALL: - case MOSSY_COBBLESTONE_WALL: + case "COBBLESTONE_WALL": + case "MOSSY_COBBLESTONE_WALL": return 2; - case IRON_BARS: - case BLACK_STAINED_GLASS_PANE: - case BLUE_STAINED_GLASS_PANE: - case BROWN_MUSHROOM_BLOCK: - case BROWN_STAINED_GLASS_PANE: - case CYAN_STAINED_GLASS_PANE: - case GLASS_PANE: - case GRAY_STAINED_GLASS_PANE: - case GREEN_STAINED_GLASS_PANE: - case LIGHT_BLUE_STAINED_GLASS_PANE: - case LIGHT_GRAY_STAINED_GLASS_PANE: - case LIME_STAINED_GLASS_PANE: - case MAGENTA_STAINED_GLASS_PANE: - case ORANGE_STAINED_GLASS_PANE: - case PINK_STAINED_GLASS_PANE: - case PURPLE_STAINED_GLASS_PANE: - case RED_STAINED_GLASS_PANE: - case WHITE_STAINED_GLASS_PANE: - case YELLOW_STAINED_GLASS_PANE: + case "IRON_BARS": + case "BLACK_STAINED_GLASS_PANE": + case "BLUE_STAINED_GLASS_PANE": + case "BROWN_MUSHROOM_BLOCK": + case "BROWN_STAINED_GLASS_PANE": + case "CYAN_STAINED_GLASS_PANE": + case "GLASS_PANE": + case "GRAY_STAINED_GLASS_PANE": + case "GREEN_STAINED_GLASS_PANE": + case "LIGHT_BLUE_STAINED_GLASS_PANE": + case "LIGHT_GRAY_STAINED_GLASS_PANE": + case "LIME_STAINED_GLASS_PANE": + case "MAGENTA_STAINED_GLASS_PANE": + case "ORANGE_STAINED_GLASS_PANE": + case "PINK_STAINED_GLASS_PANE": + case "PURPLE_STAINED_GLASS_PANE": + case "RED_STAINED_GLASS_PANE": + case "WHITE_STAINED_GLASS_PANE": + case "YELLOW_STAINED_GLASS_PANE": return 3; default: return -1; @@ -345,60 +339,23 @@ public class SchematicStreamer extends NBTStreamer { } public void addDimensionReaders() { - addReader("Schematic.Height", new BiConsumer() { - @Override - public void accept(Integer index, Short value) { - height = (value); - } - }); - addReader("Schematic.Width", new BiConsumer() { - @Override - public void accept(Integer index, Short value) { - width = (value); - } - }); - addReader("Schematic.Length", new BiConsumer() { - @Override - public void accept(Integer index, Short value) { - length = (value); - } - }); - addReader("Schematic.WEOriginX", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - originX = (value); - } - }); - addReader("Schematic.WEOriginY", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - originY = (value); - } - }); - addReader("Schematic.WEOriginZ", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - originZ = (value); - } - }); - addReader("Schematic.WEOffsetX", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - offsetX = (value); - } - }); - addReader("Schematic.WEOffsetY", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - offsetY = (value); - } - }); - addReader("Schematic.WEOffsetZ", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - offsetZ = (value); - } - }); + addReader("Schematic.Height", + (BiConsumer) (index, value) -> height = (value)); + addReader("Schematic.Width", (BiConsumer) (index, value) -> width = (value)); + addReader("Schematic.Length", + (BiConsumer) (index, value) -> length = (value)); + addReader("Schematic.WEOriginX", + (BiConsumer) (index, value) -> originX = (value)); + addReader("Schematic.WEOriginY", + (BiConsumer) (index, value) -> originY = (value)); + addReader("Schematic.WEOriginZ", + (BiConsumer) (index, value) -> originZ = (value)); + addReader("Schematic.WEOffsetX", + (BiConsumer) (index, value) -> offsetX = (value)); + addReader("Schematic.WEOffsetY", + (BiConsumer) (index, value) -> offsetY = (value)); + addReader("Schematic.WEOffsetZ", + (BiConsumer) (index, value) -> offsetZ = (value)); } private int height; @@ -419,7 +376,7 @@ public class SchematicStreamer extends NBTStreamer { private FaweClipboard setupClipboard(int size) { if (fc != null) { if (fc.getDimensions().getX() == 0) { - fc.setDimensions(new Vector(size, 1, 1)); + fc.setDimensions(BlockVector3.at(size, 1, 1)); } return fc; } @@ -432,16 +389,16 @@ public class SchematicStreamer extends NBTStreamer { } } - public Vector getOrigin() { - return new Vector(originX, originY, originZ); + public BlockVector3 getOrigin() { + return BlockVector3.at(originX, originY, originZ); } - public Vector getOffset() { - return new Vector(offsetX, offsetY, offsetZ); + public BlockVector3 getOffset() { + return BlockVector3.at(offsetX, offsetY, offsetZ); } - public Vector getDimensions() { - return new Vector(width, height, length); + public BlockVector3 getDimensions() { + return BlockVector3.at(width, height, length); } public void setClipboard(FaweClipboard clipboard) { @@ -450,16 +407,17 @@ public class SchematicStreamer extends NBTStreamer { public Clipboard getClipboard() throws IOException { try { + setupClipboard(0); addDimensionReaders(); addBlockReaders(); readFully(); - Vector min = new Vector(originX, originY, originZ); - Vector offset = new Vector(offsetX, offsetY, offsetZ); - Vector origin = min.subtract(offset); - Vector dimensions = new Vector(width, height, length); + BlockVector3 min = BlockVector3.at(originX, originY, originZ); + BlockVector3 offset = BlockVector3.at(offsetX, offsetY, offsetZ); + BlockVector3 origin = min.subtract(offset); + BlockVector3 dimensions = BlockVector3.at(width, height, length); fc.setDimensions(dimensions); fixStates(); - CuboidRegion region = new CuboidRegion(min, min.add(width, height, length).subtract(Vector.ONE)); + CuboidRegion region = new CuboidRegion(min, min.add(width, height, length).subtract(BlockVector3.ONE)); clipboard.init(region, fc); clipboard.setOrigin(origin); return clipboard; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCADrawer.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCADrawer.java index baa7db80d..4e79230d7 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCADrawer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCADrawer.java @@ -4,6 +4,7 @@ import com.boydti.fawe.Fawe; import com.boydti.fawe.FaweCache; import com.boydti.fawe.util.MathMan; import com.boydti.fawe.util.TextureUtil; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import java.awt.image.BufferedImage; @@ -80,17 +81,14 @@ public final class HeightMapMCADrawer { if (height + 1 < waterHeight) { int waterId = gen.primtives.waterId; int waterColor = 0; - BlockTypes waterType = BlockTypes.get(waterId); - switch (waterType) { - case WATER: - color = tu.averageColor((0x11 << 16) + (0x66 << 8) + (0xCC), color); - break; - case LAVA: - color = (0xCC << 16) + (0x33 << 8) + (0); - break; - default: - color = tu.getColor(waterType); - break; + BlockType waterType = BlockTypes.get(waterId); + String s = waterType.getResource().toUpperCase(); + if (waterType == BlockTypes.WATER) { + color = tu.averageColor((0x11 << 16) + (0x66 << 8) + (0xCC), color); + } else if (waterType == BlockTypes.LAVA) { + color = (0xCC << 16) + (0x33 << 8) + (0); + } else { + color = tu.getColor(waterType); } } raw[index] = color; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java index c8118e4d1..b47a8400b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/HeightMapMCAGenerator.java @@ -16,13 +16,16 @@ import com.boydti.fawe.util.image.Drawable; import com.boydti.fawe.util.image.ImageViewer; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.regions.CuboidRegion; @@ -42,11 +45,12 @@ import java.io.IOException; import java.lang.reflect.Field; import java.util.*; import java.util.List; +import java.util.concurrent.ThreadLocalRandom; import javax.annotation.Nullable; // TODO FIXME public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Drawable, VirtualWorld { - private final MutableBlockVector mutable = new MutableBlockVector(); + private final MutableBlockVector3 mutable = new MutableBlockVector3(); private final ThreadLocal indexStore = new ThreadLocal() { @Override @@ -194,7 +198,7 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr // These three variables should be set together // private FaweQueue packetQueue; private FawePlayer player; - private Vector2D chunkOffset = Vector2D.ZERO; + private BlockVector2 chunkOffset = BlockVector2.ZERO; private EditSession editSession; // end @@ -229,8 +233,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr } @Override - public Vector getOrigin() { - return new BlockVector(chunkOffset.getBlockX() << 4, 0, chunkOffset.getBlockZ() << 4); + public Vector3 getOrigin() { + return Vector3.at(chunkOffset.getBlockX() << 4, 0, chunkOffset.getBlockZ() << 4); } public boolean hasPacketViewer() { @@ -241,7 +245,7 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr this.player = player; if (player != null) { FaweLocation pos = player.getLocation(); - this.chunkOffset = new Vector2D(1 + (pos.x >> 4), 1 + (pos.z >> 4)); + this.chunkOffset = BlockVector2.at(1 + (pos.x >> 4), 1 + (pos.z >> 4)); } } @@ -296,7 +300,7 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr for (int cx = scx; cx <= ecx; cx++) { final int finalCX = cx; final int finalCZ = cz; - TaskManager.IMP.getPublicForkJoinPool().submit((Runnable) () -> { + TaskManager.IMP.getPublicForkJoinPool().submit(() -> { try { FaweChunk toSend = getSnapshot(finalCX, finalCZ); toSend.setLoc(HeightMapMCAGenerator.this, finalCX + OX, finalCZ + OZ); @@ -375,7 +379,7 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr smooth(null, mask, false, radius, iterations); } - public void smooth(Vector2D min, Vector2D max, int radius, int iterations) { + public void smooth(BlockVector2 min, BlockVector2 max, int radius, int iterations) { int snowLayer = BlockTypes.SNOW.getInternalId(); int snowBlock = BlockTypes.SNOW_BLOCK.getInternalId(); @@ -441,20 +445,17 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr private final void setLayerHeight(int index, int blockHeight, int layerHeight) { int floorState = floor.get()[index]; - switch (BlockTypes.getFromStateId(floorState)) { - case SNOW: - case SNOW_BLOCK: - if (layerHeight != 0) { - this.heights.setByte(index, (byte) (blockHeight + 1)); - this.floor.setInt(index, (BlockTypes.SNOW.getInternalId() + layerHeight)); - } else { - this.heights.setByte(index, (byte) (blockHeight)); - this.floor.setInt(index, (BlockTypes.SNOW_BLOCK.getInternalId())); - } - break; - default: + BlockType type = BlockTypes.getFromStateId(floorState); + if (type == BlockTypes.SNOW || type == BlockTypes.SNOW_BLOCK) { + if (layerHeight != 0) { + this.heights.setByte(index, (byte) (blockHeight + 1)); + this.floor.setInt(index, (BlockTypes.SNOW.getInternalId() + layerHeight)); + } else { this.heights.setByte(index, (byte) (blockHeight)); - break; + this.floor.setInt(index, (BlockTypes.SNOW_BLOCK.getInternalId())); + } + } else { + this.heights.setByte(index, (byte) (blockHeight)); } } @@ -466,20 +467,17 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr private final void setLayerHeightRaw(int index, int blockHeight, int layerHeight) { int floorState = floor.get()[index]; - switch (BlockTypes.getFromStateId(floorState)) { - case SNOW: - case SNOW_BLOCK: - if (layerHeight != 0) { - this.heights.getByteArray()[index] = (byte) (blockHeight + 1); - this.floor.getIntArray()[index] = (BlockTypes.SNOW.getInternalId() + layerHeight); - } else { - this.heights.getByteArray()[index] = (byte) (blockHeight); - this.floor.getIntArray()[index] = (BlockTypes.SNOW_BLOCK.getInternalId()); - } - break; - default: + BlockType type = BlockTypes.getFromStateId(floorState); + if (type == BlockTypes.SNOW || type == BlockTypes.SNOW_BLOCK) { + if (layerHeight != 0) { + this.heights.getByteArray()[index] = (byte) (blockHeight + 1); + this.floor.getIntArray()[index] = (BlockTypes.SNOW.getInternalId() + layerHeight); + } else { this.heights.getByteArray()[index] = (byte) (blockHeight); - break; + this.floor.getIntArray()[index] = (BlockTypes.SNOW_BLOCK.getInternalId()); + } + } else { + this.heights.getByteArray()[index] = (byte) (blockHeight); } } @@ -509,7 +507,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr for (int z = 0; z < getLength(); z++) { for (int x = 0; x < getWidth(); x++, index++) { int height = img.getRGB(x, z) & 0xFF; - if (height == 255 || height > 0 && !white && PseudoRandom.random.nextInt(256) <= height) { + if (height == 255 || height > 0 && !white && ThreadLocalRandom.current() + .nextInt(256) <= height) { int newHeight = table.average(x, z, index); setLayerHeightRaw(index, newHeight); } @@ -550,13 +549,13 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr } public void addCaves() throws WorldEditException { - CuboidRegion region = new CuboidRegion(new Vector(0, 0, 0), new Vector(getWidth() -1, 255, getLength() -1)); + CuboidRegion region = new CuboidRegion(BlockVector3.at(0, 0, 0), BlockVector3.at(getWidth() -1, 255, getLength() -1)); addCaves(region); } @Deprecated public void addSchems(Mask mask, List clipboards, int rarity, boolean rotate) throws WorldEditException { - CuboidRegion region = new CuboidRegion(new Vector(0, 0, 0), new Vector(getWidth() -1, 255, getLength() -1)); + CuboidRegion region = new CuboidRegion(BlockVector3.at(0, 0, 0), BlockVector3.at(getWidth() -1, 255, getLength() -1)); addSchems(region, mask, clipboards, rarity, rotate); } @@ -572,7 +571,7 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr for (int x = 0; x < getWidth(); x++, index++) { int y = heights.getByte(index) & 0xFF; int height = img.getRGB(x, z) & 0xFF; - if (height == 0 || PseudoRandom.random.nextInt(256) > height * doubleRarity) { + if (height == 0 || ThreadLocalRandom.current().nextInt(256) > height * doubleRarity) { continue; } mutable.mutX(x); @@ -620,7 +619,7 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr mutable.mutZ(z); for (int x = 0; x < getWidth(); x++, index++) { int y = heights.getByte(index) & 0xFF; - if (PseudoRandom.random.nextInt(256) > scaledRarity) { + if (ThreadLocalRandom.current().nextInt(256) > scaledRarity) { continue; } mutable.mutX(x); @@ -661,17 +660,17 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr } public void addOre(Mask mask, Pattern material, int size, int frequency, int rarity, int minY, int maxY) throws WorldEditException { - CuboidRegion region = new CuboidRegion(new Vector(0, 0, 0), new Vector(getWidth() -1, 255, getLength() -1)); + CuboidRegion region = new CuboidRegion(BlockVector3.at(0, 0, 0), BlockVector3.at(getWidth() -1, 255, getLength() -1)); addOre(region, mask, material, size, frequency, rarity, minY, maxY); } public void addDefaultOres(Mask mask) throws WorldEditException { - addOres(new CuboidRegion(new Vector(0, 0, 0), new Vector(getWidth() -1, 255, getLength() -1)), mask); + addOres(new CuboidRegion(BlockVector3.at(0, 0, 0), BlockVector3.at(getWidth() -1, 255, getLength() -1)), mask); } @Override - public Vector getMinimumPoint() { - return new Vector(0, 0, 0); + public BlockVector3 getMinimumPoint() { + return BlockVector3.at(0, 0, 0); } @Override @@ -680,17 +679,17 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr } @Override - public Vector getMaximumPoint() { - return new Vector(getWidth() - 1, 255, getLength() - 1); + public BlockVector3 getMaximumPoint() { + return BlockVector3.at(getWidth() - 1, 255, getLength() - 1); } @Override - public boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 position, BlockStateHolder block) throws WorldEditException { return setBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ(), block); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return this.setBiome(position.getBlockX(), position.getBlockZ(), biome); } @@ -1011,12 +1010,12 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return FaweCache.CACHE_BIOME[getBiomeId(position.getBlockX(), position.getBlockZ())]; } @Override - public BlockState getBlock(Vector position) { + public BlockState getBlock(BlockVector3 position) { return getLazyBlock(position); } @@ -1040,7 +1039,7 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr } @Override - public BlockState getLazyBlock(Vector position) { + public BlockState getLazyBlock(BlockVector3 position) { return getLazyBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ()); } @@ -1081,7 +1080,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr for (int z = 0; z < getLength(); z++) { for (int x = 0; x < getWidth(); x++, index++) { int height = img.getRGB(x, z) & 0xFF; - if (height == 255 || height > 0 && !white && PseudoRandom.random.nextInt(256) <= height) { + if (height == 255 || height > 0 && !white && ThreadLocalRandom.current() + .nextInt(256) <= height) { biomeArr[index] = biome; } } @@ -1132,7 +1132,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr } if (imgMask != null) { int height = imgMask.getRGB(x, z) & 0xFF; - if (height != 255 && (height <= 0 || !whiteOnly || PseudoRandom.random.nextInt(256) > height)) continue; + if (height != 255 && (height <= 0 || !whiteOnly || ThreadLocalRandom + .current().nextInt(256) > height)) continue; } int color = img.getRGB(x, z); if (textureUtil.getIsBlockCloserThanBiome(buffer, color, primtives.biomePriority)) { @@ -1216,7 +1217,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr for (int z = 0; z < getLength(); z++) { for (int x = 0; x < getWidth(); x++, index++) { int height = mask.getRGB(x, z) & 0xFF; - if (height == 255 || height > 0 && !white && PseudoRandom.random.nextInt(256) <= height) { + if (height == 255 || height > 0 && !white && ThreadLocalRandom.current() + .nextInt(256) <= height) { int color = img.getRGB(x, z); BlockType block = textureUtil.getNearestBlock(color); if (block != null) { @@ -1349,7 +1351,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr mutable.mutZ(z); for (int x = 0; x < getWidth(); x++, index++) { int height = img.getRGB(x, z) & 0xFF; - if (height == 255 || height > 0 && !white && PseudoRandom.random.nextInt(256) <= height) { + if (height == 255 || height > 0 && !white && ThreadLocalRandom.current() + .nextInt(256) <= height) { mutable.mutX(x); mutable.mutY(height); overlayArr[index] = pattern.apply(mutable).getInternalId(); @@ -1376,7 +1379,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr mutable.mutZ(z); for (int x = 0; x < getWidth(); x++, index++) { int height = img.getRGB(x, z) & 0xFF; - if (height == 255 || height > 0 && !white && PseudoRandom.random.nextInt(256) <= height) { + if (height == 255 || height > 0 && !white && ThreadLocalRandom.current() + .nextInt(256) <= height) { mutable.mutX(x); mutable.mutY(height); mainArr[index] = pattern.apply(mutable).getInternalId(); @@ -1401,7 +1405,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr mutable.mutZ(z); for (int x = 0; x < getWidth(); x++, index++) { int height = img.getRGB(x, z) & 0xFF; - if (height == 255 || height > 0 && !white && PseudoRandom.random.nextInt(256) <= height) { + if (height == 255 || height > 0 && !white && ThreadLocalRandom.current() + .nextInt(256) <= height) { mutable.mutX(x); mutable.mutY(height); floorArr[index] = pattern.apply(mutable).getInternalId(); @@ -1428,7 +1433,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr mutable.mutZ(z); for (int x = 0; x < getWidth(); x++, index++) { int height = img.getRGB(x, z) & 0xFF; - if (height == 255 || height > 0 && !white && PseudoRandom.random.nextInt(256) <= height) { + if (height == 255 || height > 0 && !white && ThreadLocalRandom.current() + .nextInt(256) <= height) { mutable.mutX(x); mutable.mutY(height); int combined = pattern.apply(mutable).getInternalId(); @@ -2074,7 +2080,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr for (int z = 0; z < getLength(); z++) { for (int x = 0; x < getWidth(); x++, index++) { int height = img.getRGB(x, z) & 0xFF; - if (height == 255 || height > 0 && white && PseudoRandom.random.nextInt(256) <= height) { + if (height == 255 || height > 0 && white && ThreadLocalRandom.current() + .nextInt(256) <= height) { overlay.get()[index] = combined; } } @@ -2092,7 +2099,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr for (int z = 0; z < getLength(); z++) { for (int x = 0; x < getWidth(); x++, index++) { int height = img.getRGB(x, z) & 0xFF; - if (height == 255 || height > 0 && !white && PseudoRandom.random.nextInt(256) <= height) { + if (height == 255 || height > 0 && !white && ThreadLocalRandom.current() + .nextInt(256) <= height) { main.get()[index] = combined; } } @@ -2109,7 +2117,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr for (int z = 0; z < getLength(); z++) { for (int x = 0; x < getWidth(); x++, index++) { int height = img.getRGB(x, z) & 0xFF; - if (height == 255 || height > 0 && !white && PseudoRandom.random.nextInt(256) <= height) { + if (height == 255 || height > 0 && !white && ThreadLocalRandom.current() + .nextInt(256) <= height) { floor.get()[index] = combined; } } @@ -2127,7 +2136,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr for (int z = 0; z < getLength(); z++) { for (int x = 0; x < getWidth(); x++, index++) { int height = img.getRGB(x, z) & 0xFF; - if (height == 255 || height > 0 && !white && PseudoRandom.random.nextInt(256) <= height) { + if (height == 255 || height > 0 && !white && ThreadLocalRandom.current() + .nextInt(256) <= height) { main.get()[index] = combined; floor.get()[index] = combined; } @@ -2240,33 +2250,52 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr } @Override - public boolean setBlock(Vector position, BlockStateHolder block, boolean notifyAndLight) throws WorldEditException { + public boolean setBlock(BlockVector3 position, BlockStateHolder block, boolean notifyAndLight) throws WorldEditException { return setBlock(position, block); } // These aren't implemented yet... @Override - public int getBlockLightLevel(Vector position) { + public int getBlockLightLevel(BlockVector3 position) { return 0; } @Override - public boolean clearContainerBlockContents(Vector position) { + public boolean clearContainerBlockContents(BlockVector3 position) { return false; } - @Override - public void dropItem(Vector position, BaseItemStack item) { - - } - @Override public boolean regenerate(Region region, EditSession editSession) { return false; } @Override - public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, Vector position) throws MaxChangedBlocksException { + public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) throws MaxChangedBlocksException { return false; } + + @Override + public void dropItem(Vector3 position, BaseItemStack item) { + // TODO Auto-generated method stub + + } + + @Override + public boolean playEffect(Vector3 position, int type, int data) { + // 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/jnbt/anvil/MCAChunk.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAChunk.java index 84a856d11..b90c63794 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 @@ -91,49 +91,47 @@ public class MCAChunk extends FaweChunk { public void write(NBTOutputStream nbtOut) throws IOException { nbtOut.writeNamedTagName("", NBTConstants.TYPE_COMPOUND); - nbtOut.writeLazyCompoundTag("Level", new NBTOutputStream.LazyWrite() { - @Override - public void write(NBTOutputStream out) throws IOException { - out.writeNamedTag("V", (byte) 1); - out.writeNamedTag("xPos", getX()); - out.writeNamedTag("zPos", getZ()); - out.writeNamedTag("LightPopulated", (byte) 0); - out.writeNamedTag("TerrainPopulated", (byte) 1); - if (entities.isEmpty()) { - out.writeNamedEmptyList("Entities"); - } else { - out.writeNamedTag("Entities", new ListTag(CompoundTag.class, new ArrayList(entities.values()))); - } - if (tiles.isEmpty()) { - out.writeNamedEmptyList("TileEntities"); - } else { - out.writeNamedTag("TileEntities", new ListTag(CompoundTag.class, new ArrayList(tiles.values()))); - } - out.writeNamedTag("InhabitedTime", inhabitedTime); - out.writeNamedTag("LastUpdate", lastUpdate); - if (biomes != null) { - out.writeNamedTag("Biomes", biomes); - } - out.writeNamedTag("HeightMap", heightMap); - out.writeNamedTagName("Sections", NBTConstants.TYPE_LIST); - nbtOut.getOutputStream().writeByte(NBTConstants.TYPE_COMPOUND); - int len = 0; - for (int layer = 0; layer < ids.length; layer++) { - if (ids[layer] != null) len++; - } - nbtOut.getOutputStream().writeInt(len); - for (int layer = 0; layer < ids.length; layer++) { - byte[] idLayer = ids[layer]; - if (idLayer == null) { - continue; - } - out.writeNamedTag("Y", (byte) layer); - out.writeNamedTag("BlockLight", blockLight[layer]); - out.writeNamedTag("SkyLight", skyLight[layer]); - out.writeNamedTag("Blocks", idLayer); - out.writeNamedTag("Data", data[layer]); - out.writeEndTag(); + nbtOut.writeLazyCompoundTag("Level", out -> { + out.writeNamedTag("V", (byte) 1); + out.writeNamedTag("xPos", getX()); + out.writeNamedTag("zPos", getZ()); + out.writeNamedTag("LightPopulated", (byte) 0); + out.writeNamedTag("TerrainPopulated", (byte) 1); + if (entities.isEmpty()) { + out.writeNamedEmptyList("Entities"); + } else { + out.writeNamedTag("Entities", new ListTag(CompoundTag.class, new ArrayList<>(entities.values()))); + } + if (tiles.isEmpty()) { + out.writeNamedEmptyList("TileEntities"); + } else { + out.writeNamedTag("TileEntities", new ListTag(CompoundTag.class, + new ArrayList<>(tiles.values()))); + } + out.writeNamedTag("InhabitedTime", inhabitedTime); + out.writeNamedTag("LastUpdate", lastUpdate); + if (biomes != null) { + out.writeNamedTag("Biomes", biomes); + } + out.writeNamedTag("HeightMap", heightMap); + out.writeNamedTagName("Sections", NBTConstants.TYPE_LIST); + nbtOut.getOutputStream().writeByte(NBTConstants.TYPE_COMPOUND); + int len = 0; + for (int layer = 0; layer < ids.length; layer++) { + if (ids[layer] != null) len++; + } + nbtOut.getOutputStream().writeInt(len); + for (int layer = 0; layer < ids.length; layer++) { + byte[] idLayer = ids[layer]; + if (idLayer == null) { + continue; } + out.writeNamedTag("Y", (byte) layer); + out.writeNamedTag("BlockLight", blockLight[layer]); + out.writeNamedTag("SkyLight", skyLight[layer]); + out.writeNamedTag("Blocks", idLayer); + out.writeNamedTag("Data", data[layer]); + out.writeEndTag(); } }); nbtOut.writeEndTag(); @@ -422,9 +420,9 @@ public class MCAChunk extends FaweChunk { return null; } // e.g. by precalculating the length - HashMap level = new HashMap(); - level.put("Entities", new ListTag(CompoundTag.class, new ArrayList(entities.values()))); - level.put("TileEntities", new ListTag(CompoundTag.class, new ArrayList(tiles.values()))); + HashMap level = new HashMap<>(); + level.put("Entities", new ListTag(CompoundTag.class, new ArrayList<>(entities.values()))); + level.put("TileEntities", new ListTag(CompoundTag.class, new ArrayList<>(tiles.values()))); level.put("InhabitedTime", inhabitedTime); level.put("LastUpdate", lastUpdate); level.put("LightPopulated", (byte) 0); @@ -442,7 +440,7 @@ public class MCAChunk extends FaweChunk { if (idLayer == null) { continue; } - HashMap map = new HashMap(); + HashMap map = new HashMap<>(); map.put("Y", (byte) layer); map.put("BlockLight", blockLight[layer]); map.put("SkyLight", skyLight[layer]); @@ -463,74 +461,43 @@ public class MCAChunk extends FaweChunk { skyLight = new byte[16][]; blockLight = new byte[16][]; NBTStreamer streamer = new NBTStreamer(nis); - streamer.addReader(".Level.InhabitedTime", new BiConsumer() { - @Override - public void accept(Integer index, Long value) { - inhabitedTime = value; - } + streamer.addReader(".Level.InhabitedTime", + (BiConsumer) (index, value) -> inhabitedTime = value); + streamer.addReader(".Level.LastUpdate", + (BiConsumer) (index, value) -> lastUpdate = value); + streamer.addReader(".Level.Sections.#", (BiConsumer) (index, tag) -> { + int layer = tag.getByte("Y"); + ids[layer] = tag.getByteArray("Blocks"); + data[layer] = tag.getByteArray("Data"); + skyLight[layer] = tag.getByteArray("SkyLight"); + blockLight[layer] = tag.getByteArray("BlockLight"); }); - streamer.addReader(".Level.LastUpdate", new BiConsumer() { - @Override - public void accept(Integer index, Long value) { - lastUpdate = value; - } - }); - streamer.addReader(".Level.Sections.#", new BiConsumer() { - @Override - public void accept(Integer index, CompoundTag tag) { - int layer = tag.getByte("Y"); - ids[layer] = tag.getByteArray("Blocks"); - data[layer] = tag.getByteArray("Data"); - skyLight[layer] = tag.getByteArray("SkyLight"); - blockLight[layer] = tag.getByteArray("BlockLight"); - } - }); - streamer.addReader(".Level.TileEntities.#", new BiConsumer() { - @Override - public void accept(Integer index, CompoundTag tile) { - int x = tile.getInt("x") & 15; + streamer.addReader(".Level.TileEntities.#", + (BiConsumer) (index, tile) -> { + int x1 = tile.getInt("x") & 15; int y = tile.getInt("y"); - int z = tile.getInt("z") & 15; - short pair = MathMan.tripleBlockCoord(x, y, z); + int z1 = tile.getInt("z") & 15; + short pair = MathMan.tripleBlockCoord(x1, y, z1); tiles.put(pair, tile); - } - }); - streamer.addReader(".Level.Entities.#", new BiConsumer() { - @Override - public void accept(Integer index, CompoundTag entityTag) { + }); + streamer.addReader(".Level.Entities.#", + (BiConsumer) (index, entityTag) -> { if (entities == null) { - entities = new HashMap(); + entities = new HashMap<>(); } long least = entityTag.getLong("UUIDLeast"); long most = entityTag.getLong("UUIDMost"); entities.put(new UUID(most, least), entityTag); - } - }); - streamer.addReader(".Level.Biomes", new BiConsumer() { - @Override - public void accept(Integer index, byte[] value) { - biomes = value; - } - }); - streamer.addReader(".Level.HeightMap", new BiConsumer() { - @Override - public void accept(Integer index, int[] value) { - heightMap = value; - } - }); + }); + streamer.addReader(".Level.Biomes", + (BiConsumer) (index, value) -> biomes = value); + streamer.addReader(".Level.HeightMap", + (BiConsumer) (index, value) -> heightMap = value); if (readPos) { - streamer.addReader(".Level.xPos", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - MCAChunk.this.setLoc(getParent(), value, getZ()); - } - }); - streamer.addReader(".Level.zPos", new BiConsumer() { - @Override - public void accept(Integer index, Integer value) { - MCAChunk.this.setLoc(getParent(), getX(), value); - } - }); + streamer.addReader(".Level.xPos", + (BiConsumer) (index, value) -> MCAChunk.this.setLoc(getParent(), value, getZ())); + streamer.addReader(".Level.zPos", + (BiConsumer) (index, value) -> MCAChunk.this.setLoc(getParent(), getX(), value)); } streamer.readFully(); } @@ -635,7 +602,7 @@ public class MCAChunk extends FaweChunk { @Override public Map getTiles() { - return tiles == null ? new HashMap() : tiles; + return tiles == null ? new HashMap<>() : tiles; } @Override diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAClipboard.java index 9a12188d3..0315da413 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAClipboard.java @@ -1,14 +1,14 @@ package com.boydti.fawe.jnbt.anvil; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; public class MCAClipboard { private final MCAQueue queue; private final CuboidRegion region; - private final Vector origin; + private final BlockVector3 origin; - public MCAClipboard(MCAQueue queue, CuboidRegion region, Vector origin) { + public MCAClipboard(MCAQueue queue, CuboidRegion region, BlockVector3 origin) { this.queue = queue; this.region = region; this.origin = origin; @@ -22,7 +22,7 @@ public class MCAClipboard { return region; } - public Vector getOrigin() { + public BlockVector3 getOrigin() { return origin; } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFilter.java index 8f42da156..f264d6d23 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAFilter.java @@ -1,7 +1,7 @@ package com.boydti.fawe.jnbt.anvil; import com.boydti.fawe.object.collection.IterableThreadLocal; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAQueue.java index 7a3206e67..28dab081e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MCAQueue.java @@ -16,7 +16,7 @@ import com.boydti.fawe.object.RunnableVal4; import com.boydti.fawe.object.collection.IterableThreadLocal; import com.boydti.fawe.util.MainUtil; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BaseBiome; import java.io.File; import java.io.IOException; @@ -155,11 +155,11 @@ public class MCAQueue extends NMSMappedFaweQueue nbt = ReflectionUtils.getMap(block.getNbtData().getValue()); if (nbt.containsKey("Items")) { @@ -75,7 +77,7 @@ public class MCAWorld implements SimpleWorld { } @Override - public void dropItem(Vector position, BaseItemStack item) { + public void dropItem(Vector3 position, BaseItemStack item) { } @@ -101,17 +103,34 @@ public class MCAWorld implements SimpleWorld { } @Override - public BlockState getBlock(Vector position) { + public BlockState getBlock(BlockVector3 position) { return extent.getLazyBlock(position); } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return extent.getBiome(position); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return extent.setBiome(position, biome); } + + @Override + public boolean playEffect(Vector3 position, int type, int data) { + // 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() { + return queue.getWEWorld().getSpawnPosition(); + } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MutableMCABackedBaseBlock.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MutableMCABackedBaseBlock.java index c17945a9f..054ae1b0b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MutableMCABackedBaseBlock.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/MutableMCABackedBaseBlock.java @@ -2,7 +2,7 @@ package com.boydti.fawe.jnbt.anvil; import com.boydti.fawe.FaweCache; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import javax.annotation.Nullable; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/CountFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/CountFilter.java index 2ada18c01..09591bc70 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/CountFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/CountFilter.java @@ -4,7 +4,7 @@ import com.boydti.fawe.FaweCache; import com.boydti.fawe.jnbt.anvil.MCAChunk; import com.boydti.fawe.jnbt.anvil.MCAFilterCounter; import com.boydti.fawe.object.number.MutableLong; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; // TODO FIXME diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/CountIdFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/CountIdFilter.java index 9137c6fa7..1d09ea9bf 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/CountIdFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/CountIdFilter.java @@ -4,7 +4,6 @@ import com.boydti.fawe.FaweCache; import com.boydti.fawe.jnbt.anvil.MCAChunk; import com.boydti.fawe.jnbt.anvil.MCAFilterCounter; import com.boydti.fawe.object.number.MutableLong; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/DelegateMCAFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/DelegateMCAFilter.java index 166006b60..b418c2ccf 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/DelegateMCAFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/DelegateMCAFilter.java @@ -4,7 +4,7 @@ import com.boydti.fawe.jnbt.anvil.MCAChunk; import com.boydti.fawe.jnbt.anvil.MCAFile; import com.boydti.fawe.jnbt.anvil.MCAFilter; import com.boydti.fawe.jnbt.anvil.MCAQueue; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/MappedReplacePatternFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/MappedReplacePatternFilter.java index 76ac980ba..7be8caf8b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/MappedReplacePatternFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/MappedReplacePatternFilter.java @@ -4,8 +4,7 @@ import com.boydti.fawe.FaweCache; import com.boydti.fawe.jnbt.anvil.MCAFilterCounter; import com.boydti.fawe.object.number.MutableLong; import com.boydti.fawe.util.StringMan; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.function.pattern.Pattern; @@ -53,7 +52,7 @@ public class MappedReplacePatternFilter extends MCAFilterCounter { // map[block.getCombined()] = pattern; } - private final MutableBlockVector mutable = new MutableBlockVector(0, 0, 0); +// private final MutableBlockVector3 mutable = new MutableBlockVector3(0, 0, 0); @Override public void applyBlock(int x, int y, int z, BaseBlock block, MutableLong ignore) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/PlotTrimFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/PlotTrimFilter.java index 397a8f5ef..329b6b9c8 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/PlotTrimFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/PlotTrimFilter.java @@ -5,14 +5,14 @@ import com.boydti.fawe.jnbt.anvil.MCAChunk; import com.boydti.fawe.jnbt.anvil.MCAFile; import com.boydti.fawe.object.RunnableVal4; import com.boydti.fawe.object.collection.LongHashSet; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.generator.HybridGen; -import com.intellectualcrafters.plot.generator.HybridPlotWorld; -import com.intellectualcrafters.plot.generator.IndependentPlotGenerator; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.util.expiry.ExpireManager; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.generator.HybridGen; +import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; +import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; +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.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.registry.LegacyMapper; @@ -37,7 +37,7 @@ public class PlotTrimFilter extends DeleteUninhabitedFilter { IndependentPlotGenerator gen = area.getGenerator(); if (area instanceof HybridPlotWorld && gen instanceof HybridGen) { HybridPlotWorld hpw = (HybridPlotWorld) area; - return hpw.PLOT_BEDROCK && !hpw.PLOT_SCHEMATIC && hpw.MAIN_BLOCK.length == 1 && hpw.TOP_BLOCK.length == 1; + return hpw.PLOT_BEDROCK && !hpw.PLOT_SCHEMATIC && hpw.MAIN_BLOCK.getBlocks().size() == 1 && hpw.TOP_BLOCK.getBlocks().size() == 1; } return false; } @@ -47,21 +47,21 @@ public class PlotTrimFilter extends DeleteUninhabitedFilter { Fawe.debug("Initializing Plot trim..."); String worldName = Fawe.imp().getWorldName(world); - PlotArea area = PS.get().getPlotAreaByString(worldName); + PlotArea area = PlotSquared.get().getPlotAreaByString(worldName); IndependentPlotGenerator gen = area.getGenerator(); if (!(area instanceof HybridPlotWorld) || !(gen instanceof HybridGen)) { throw new UnsupportedOperationException("Trim does not support non hybrid plot worlds"); } this.hg = (HybridGen) gen; this.hpw = (HybridPlotWorld) area; - if (hpw.PLOT_SCHEMATIC || hpw.MAIN_BLOCK.length != 1 || hpw.TOP_BLOCK.length != 1) { + if (hpw.PLOT_SCHEMATIC || hpw.MAIN_BLOCK.getBlocks().size() != 1 || hpw.TOP_BLOCK.getBlocks().size() != 1) { throw new UnsupportedOperationException("WIP - will implement later"); } this.occupiedRegions = new LongHashSet(); this.unoccupiedChunks = new LongHashSet(); this.reference = calculateReference(); - + Fawe.debug(" - calculating claims"); this.calculateClaimedArea(); } @@ -70,11 +70,11 @@ public class PlotTrimFilter extends DeleteUninhabitedFilter { MCAChunk reference = new MCAChunk(null, 0, 0); if (hpw.PLOT_BEDROCK) { reference.fillCuboid(0, 15, 0, 0, 0, 15, BlockTypes.BEDROCK.getInternalId()); - } else if (hpw.MAIN_BLOCK[0].id == 0 && hpw.TOP_BLOCK[0].id == 0) { + } else if (hpw.MAIN_BLOCK.hasSingleItem() && hpw.MAIN_BLOCK.getBlock().isAir() && hpw.TOP_BLOCK.hasSingleItem() && hpw.TOP_BLOCK.getBlock().isAir()) { referenceIsVoid = true; } - reference.fillCuboid(0, 15, 1, hpw.PLOT_HEIGHT - 1, 0, 15, LegacyMapper.getInstance().getBlockFromLegacy(hpw.MAIN_BLOCK[0].id).getInternalId()); - reference.fillCuboid(0, 15, hpw.PLOT_HEIGHT, hpw.PLOT_HEIGHT, 0, 15, LegacyMapper.getInstance().getBlockFromLegacy(hpw.TOP_BLOCK[0].id).getInternalId()); + reference.fillCuboid(0, 15, 1, hpw.PLOT_HEIGHT - 1, 0, 15, LegacyMapper.getInstance().getBaseBlockFromPlotBlock(hpw.MAIN_BLOCK.getBlock()).getInternalBlockTypeId()); + reference.fillCuboid(0, 15, hpw.PLOT_HEIGHT, hpw.PLOT_HEIGHT, 0, 15, LegacyMapper.getInstance().getBaseBlockFromPlotBlock(hpw.TOP_BLOCK.getBlock()).getInternalBlockTypeId()); return reference; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/RemapFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/RemapFilter.java index 9ea17ea58..e485bea92 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/RemapFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/RemapFilter.java @@ -13,7 +13,7 @@ import com.sk89q.jnbt.ByteTag; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.IntTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import java.io.File; import java.util.ArrayList; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/ReplacePatternFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/ReplacePatternFilter.java index 782b36721..cbec9959a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/ReplacePatternFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/ReplacePatternFilter.java @@ -4,7 +4,7 @@ import com.boydti.fawe.FaweCache; import com.boydti.fawe.jnbt.anvil.MCAFilterCounter; import com.boydti.fawe.object.mask.FaweBlockMatcher; import com.boydti.fawe.object.number.MutableLong; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.function.pattern.Pattern; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/ReplaceSimpleFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/ReplaceSimpleFilter.java index 10e9a511c..fffed04fd 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/ReplaceSimpleFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/ReplaceSimpleFilter.java @@ -3,7 +3,7 @@ package com.boydti.fawe.jnbt.anvil.filters; import com.boydti.fawe.jnbt.anvil.MCAFilterCounter; import com.boydti.fawe.object.mask.FaweBlockMatcher; import com.boydti.fawe.object.number.MutableLong; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; public class ReplaceSimpleFilter extends MCAFilterCounter { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/SetPatternFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/SetPatternFilter.java index 58241cb38..c8025e6a7 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/SetPatternFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/filters/SetPatternFilter.java @@ -3,7 +3,7 @@ package com.boydti.fawe.jnbt.anvil.filters; import com.boydti.fawe.FaweCache; import com.boydti.fawe.jnbt.anvil.MCAFilterCounter; import com.boydti.fawe.object.number.MutableLong; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.function.pattern.Pattern; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java index 5787f5bf1..3d87e2f07 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/CavesGen.java @@ -1,17 +1,16 @@ package com.boydti.fawe.jnbt.anvil.generator; -import com.boydti.fawe.FaweCache; import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.util.MathMan; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; +import java.util.concurrent.ThreadLocalRandom; + public class CavesGen extends GenBase { private boolean evenCaveDistribution = false; @@ -42,11 +41,12 @@ public class CavesGen extends GenBase { this.caveSystemPocketMaxSize = caveSystemPocketMaxSize; } - protected void generateLargeCaveNode(long seed, Vector2D pos, Extent chunk, double x, double y, double z) throws WorldEditException { - generateCaveNode(seed, pos, chunk, x, y, z, 1.0F + PseudoRandom.random.nextDouble() * 6.0F, 0.0F, 0.0F, -1, -1, 0.5D); + protected void generateLargeCaveNode(long seed, BlockVector2 pos, Extent chunk, double x, double y, double z) throws WorldEditException { + generateCaveNode(seed, pos, chunk, x, y, z, 1.0F + ThreadLocalRandom.current().nextDouble() + * 6.0F, 0.0F, 0.0F, -1, -1, 0.5D); } - protected void generateCaveNode(long seed, Vector2D chunkPos, Extent chunk, double x, double y, double z, double paramdouble1, double paramdouble2, double paramdouble3, int angle, int maxAngle, double paramDouble4) throws WorldEditException { + protected void generateCaveNode(long seed, BlockVector2 chunkPos, Extent chunk, double x, double y, double z, double paramdouble1, double paramdouble2, double paramdouble3, int angle, int maxAngle, double paramDouble4) throws WorldEditException { int bx = (chunkPos.getBlockX() << 4); int bz = (chunkPos.getBlockZ() << 4); double real_x = bx + 7; @@ -55,11 +55,9 @@ public class CavesGen extends GenBase { double f1 = 0.0F; double f2 = 0.0F; - PseudoRandom localRandom = new PseudoRandom(seed); - if (maxAngle <= 0) { int checkAreaSize = this.getCheckAreaSize() * 16 - 16; - maxAngle = checkAreaSize - localRandom.nextInt(checkAreaSize / 4); + maxAngle = checkAreaSize - ThreadLocalRandom.current().nextInt(checkAreaSize / 4); } boolean isLargeCave = false; @@ -68,8 +66,8 @@ public class CavesGen extends GenBase { isLargeCave = true; } - int j = localRandom.nextInt(maxAngle / 2) + maxAngle / 4; - int k = localRandom.nextInt(6) == 0 ? 1 : 0; + int j = ThreadLocalRandom.current().nextInt(maxAngle / 2) + maxAngle / 4; + int k = ThreadLocalRandom.current().nextInt(6) == 0 ? 1 : 0; for (; angle < maxAngle; angle++) { double d3 = 1.5D + MathMan.sinInexact(angle * 3.141593F / maxAngle) * paramdouble1 * 1.0F; @@ -91,15 +89,19 @@ public class CavesGen extends GenBase { f2 *= 0.9F; f1 *= 0.75F; - f2 += (localRandom.nextDouble() - localRandom.nextDouble()) * localRandom.nextDouble() * 2.0F; - f1 += (localRandom.nextDouble() - localRandom.nextDouble()) * localRandom.nextDouble() * 4.0F; + f2 += (ThreadLocalRandom.current().nextDouble() - ThreadLocalRandom.current() + .nextDouble()) * ThreadLocalRandom.current().nextDouble() * 2.0F; + f1 += (ThreadLocalRandom.current().nextDouble() - ThreadLocalRandom.current() + .nextDouble()) * ThreadLocalRandom.current().nextDouble() * 4.0F; if ((!isLargeCave) && (angle == j) && (paramdouble1 > 1.0F) && (maxAngle > 0)) { - generateCaveNode(localRandom.nextLong(), chunkPos, chunk, x, y, z, localRandom.nextDouble() * 0.5F + 0.5F, paramdouble2 - 1.570796F, paramdouble3 / 3.0F, angle, maxAngle, 1.0D); - generateCaveNode(localRandom.nextLong(), chunkPos, chunk, x, y, z, localRandom.nextDouble() * 0.5F + 0.5F, paramdouble2 + 1.570796F, paramdouble3 / 3.0F, angle, maxAngle, 1.0D); + generateCaveNode(ThreadLocalRandom.current().nextLong(), chunkPos, chunk, x, y, z, ThreadLocalRandom + .current().nextDouble() * 0.5F + 0.5F, paramdouble2 - 1.570796F, paramdouble3 / 3.0F, angle, maxAngle, 1.0D); + generateCaveNode(ThreadLocalRandom.current().nextLong(), chunkPos, chunk, x, y, z, ThreadLocalRandom + .current().nextDouble() * 0.5F + 0.5F, paramdouble2 + 1.570796F, paramdouble3 / 3.0F, angle, maxAngle, 1.0D); return; } - if ((!isLargeCave) && (localRandom.nextInt(4) == 0)) { + if ((!isLargeCave) && (ThreadLocalRandom.current().nextInt(4) == 0)) { continue; } @@ -146,7 +148,7 @@ public class CavesGen extends GenBase { for (int local_x = m; (!waterFound) && (local_x < n); local_x++) { for (int local_z = i3; (!waterFound) && (local_z < i4); local_z++) { for (int local_y = i2 + 1; (!waterFound) && (local_y >= i1 - 1); local_y--) { - if (local_y >= 0 && local_y < 255) { + if (local_y < 255) { BlockStateHolder material = chunk.getLazyBlock(bx + local_x, local_y, bz + local_z); if (material.getBlockType() == BlockTypes.WATER) { waterFound = true; @@ -173,11 +175,9 @@ public class CavesGen extends GenBase { if ((d11 > -0.7D) && (d9 * d9 + d11 * d11 + d10 * d10 < 1.0D)) { BlockStateHolder material = chunk.getLazyBlock(bx + local_x, local_y, bz + local_z); BlockStateHolder materialAbove = chunk.getLazyBlock(bx + local_x, local_y + 1, bz + local_z); - switch (material.getBlockType()) { - case GRASS: - case MYCELIUM: - grassFound = true; - break; + BlockType blockType = material.getBlockType(); + if (blockType == BlockTypes.MYCELIUM || blockType == BlockTypes.GRASS) { + grassFound = true; } if (this.isSuitableBlock(material, materialAbove)) { if (local_y - 1 < 10) { @@ -206,13 +206,13 @@ public class CavesGen extends GenBase { } protected boolean isSuitableBlock(BlockStateHolder material, BlockStateHolder materialAbove) { - switch (material.getBlockType()) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - case WATER: - case LAVA: - case BEDROCK: + switch (material.getBlockType().getResource().toUpperCase()) { + case "AIR": + case "CAVE_AIR": + case "VOID_AIR": + case "WATER": + case "LAVA": + case "BEDROCK": return false; default: return true; @@ -220,43 +220,49 @@ public class CavesGen extends GenBase { } @Override - public void generateChunk(Vector2D adjacentChunk, Vector2D originChunk, Extent chunk) throws WorldEditException { - PseudoRandom random = getRandom(); - int i = random.nextInt(random.nextInt(random.nextInt(this.caveFrequency) + 1) + 1); + 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) i = this.caveFrequency; - if (random.nextInt(100) >= this.caveRarity) + if (ThreadLocalRandom.current().nextInt(100) >= this.caveRarity) i = 0; for (int j = 0; j < i; j++) { - double x = (adjacentChunk.getBlockX() << 4) + random.nextInt(16); + double x = (chunkX << 4) + ThreadLocalRandom.current().nextInt(16); double y; if (this.evenCaveDistribution) - y = random.nextInt(this.caveMinAltitude, this.caveMaxAltitude); - else - y = random.nextInt(random.nextInt(this.caveMaxAltitude - this.caveMinAltitude + 1) + 1) + this.caveMinAltitude; + y = ThreadLocalRandom.current().nextInt(this.caveMinAltitude, this.caveMaxAltitude); + else { + y = ThreadLocalRandom.current() + .nextInt(ThreadLocalRandom.current() + .nextInt(this.caveMaxAltitude - this.caveMinAltitude + 1) + 1) + this.caveMinAltitude; + } - double z = (adjacentChunk.getBlockZ() << 4) + random.nextInt(16); + double z = (chunkZ << 4) + ThreadLocalRandom.current().nextInt(16); int count = this.caveSystemFrequency; boolean largeCaveSpawned = false; - if (random.nextInt(100) <= this.individualCaveRarity) { - generateLargeCaveNode(random.nextLong(), originChunk, chunk, x, y, z); + if (ThreadLocalRandom.current().nextInt(100) <= this.individualCaveRarity) { + generateLargeCaveNode(ThreadLocalRandom.current().nextLong(), originChunk, chunk, x, y, z); largeCaveSpawned = true; } - if ((largeCaveSpawned) || (random.nextInt(100) <= this.caveSystemPocketChance - 1)) { - count += random.nextInt(this.caveSystemPocketMinSize, this.caveSystemPocketMaxSize); + if ((largeCaveSpawned) || (ThreadLocalRandom.current().nextInt(100) + <= this.caveSystemPocketChance - 1)) { + count += ThreadLocalRandom.current() + .nextInt(this.caveSystemPocketMinSize, this.caveSystemPocketMaxSize); } while (count > 0) { count--; - double f1 = random.nextDouble() * 3.141593F * 2.0F; - double f2 = (random.nextDouble() - 0.5F) * 2.0F / 8.0F; - double f3 = random.nextDouble() * 2.0F + random.nextDouble(); - generateCaveNode(random.nextLong(), originChunk, chunk, x, y, z, f3, f1, f2, 0, 0, 1.0D); + double f1 = ThreadLocalRandom.current().nextDouble() * 3.141593F * 2.0F; + double f2 = (ThreadLocalRandom.current().nextDouble() - 0.5F) * 2.0F / 8.0F; + double f3 = ThreadLocalRandom.current().nextDouble() * 2.0F + ThreadLocalRandom + .current().nextDouble(); + generateCaveNode(ThreadLocalRandom.current().nextLong(), originChunk, chunk, x, y, z, f3, f1, f2, 0, 0, 1.0D); } } } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/GenBase.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/GenBase.java index ca46d4fef..c3adeb880 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/GenBase.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/GenBase.java @@ -1,10 +1,11 @@ package com.boydti.fawe.jnbt.anvil.generator; import com.boydti.fawe.object.PseudoRandom; -import com.sk89q.worldedit.MutableBlockVector2D; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; + +import java.util.concurrent.ThreadLocalRandom; public abstract class GenBase { @@ -12,14 +13,13 @@ public abstract class GenBase { private final PseudoRandom random; private final long seed; private final long worldSeed1, worldSeed2; - private MutableBlockVector2D mutable = new MutableBlockVector2D(); public GenBase(int area) { this.random = new PseudoRandom(); this.checkAreaSize = area; - this.seed = PseudoRandom.random.nextLong(); - this.worldSeed1 = PseudoRandom.random.nextLong(); - this.worldSeed2 = PseudoRandom.random.nextLong(); + this.seed = ThreadLocalRandom.current().nextLong(); + this.worldSeed1 = ThreadLocalRandom.current().nextLong(); + this.worldSeed2 = ThreadLocalRandom.current().nextLong(); } public int getCheckAreaSize() { @@ -30,20 +30,16 @@ public abstract class GenBase { return random; } - public void generate(Vector2D chunkPos, Extent chunk) throws WorldEditException { + public void generate(BlockVector2 chunkPos, Extent chunk) throws WorldEditException { int i = this.checkAreaSize; int chunkX = chunkPos.getBlockX(); int chunkZ = chunkPos.getBlockZ(); - for (int x = chunkX - i; x <= chunkX + i; x++) { - mutable.mutX(x); for (int z = chunkZ - i; z <= chunkZ + i; z++) { - mutable.mutZ(z); - this.random.setSeed(worldSeed1 * x ^ worldSeed2 * z ^ seed); - generateChunk(mutable, chunkPos, chunk); + generateChunk(x, z, chunkPos, chunk); } } } - public abstract void generateChunk(Vector2D adjacentChunk, Vector2D originChunk, Extent chunk) throws WorldEditException; + public abstract void generateChunk(int x, int z, BlockVector2 originChunk, Extent chunk) throws WorldEditException; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/OreGen.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/OreGen.java index c9af936e1..7ded48ea7 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/OreGen.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/OreGen.java @@ -1,12 +1,11 @@ package com.boydti.fawe.jnbt.anvil.generator; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.util.MathMan; -import com.sk89q.worldedit.MutableBlockVector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.MutableBlockVector3; import java.util.Random; @@ -20,7 +19,7 @@ public class OreGen extends Resource { private final Pattern pattern; private final Extent extent; private final Mask mask; - private MutableBlockVector mutable = new MutableBlockVector(); + private MutableBlockVector3 mutable = new MutableBlockVector3(); private double ONE_2 = 1 / 2F; private double ONE_8 = 1 / 8F; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/SchemGen.java b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/SchemGen.java index 020a9ca9a..a404b38e5 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/SchemGen.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/jnbt/anvil/generator/SchemGen.java @@ -2,7 +2,7 @@ package com.boydti.fawe.jnbt.anvil.generator; import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.schematic.Schematic; -import com.sk89q.worldedit.MutableBlockVector; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.Clipboard; @@ -20,7 +20,7 @@ public class SchemGen extends Resource { private final boolean randomRotate; private final Mask mask; - private MutableBlockVector mutable = new MutableBlockVector(); + private MutableBlockVector3 mutable = new MutableBlockVector3(); public SchemGen(Mask mask, Extent extent, List clipboards, boolean randomRotate) { this.mask = mask; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/logging/LoggingChangeSet.java b/worldedit-core/src/main/java/com/boydti/fawe/logging/LoggingChangeSet.java index 13c6e0ed5..8ac50bbde 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/logging/LoggingChangeSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/logging/LoggingChangeSet.java @@ -27,7 +27,7 @@ public class LoggingChangeSet extends AbstractDelegateChangeSet { // public static IBlocksHubApi api; // -// private final MutableVector loc; +// private final MutableVector3 loc; // private final IPlayer player; // private IWorld world; // private final MutableBlockData oldBlock; @@ -46,7 +46,7 @@ public class LoggingChangeSet extends AbstractDelegateChangeSet { // } catch (Throwable ignore) { // this.world = api.getWorld(world); // } -// this.loc = new MutableVector(); +// this.loc = new MutableVector3(); // this.oldBlock = new MutableBlockData(); // this.newBlock = new MutableBlockData(); // this.player = api.getPlayer(player.getUUID()); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/logging/MutableVector.java b/worldedit-core/src/main/java/com/boydti/fawe/logging/MutableVector.java index 974fd06ea..d2a4e4af0 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/logging/MutableVector.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/logging/MutableVector.java @@ -2,11 +2,11 @@ // //import org.primesoft.blockshub.api.Vector; // -//public class MutableVector extends Vector { +//public class MutableVector3 extends Vector { // // public double x, y, z; // -// public MutableVector() { +// public MutableVector3() { // super(0, 0, 0); // this.x = 0; // this.y = 0; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/logging/rollback/RollbackOptimizedHistory.java b/worldedit-core/src/main/java/com/boydti/fawe/logging/rollback/RollbackOptimizedHistory.java index 50251c4ac..78351c6b7 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/logging/rollback/RollbackOptimizedHistory.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/logging/rollback/RollbackOptimizedHistory.java @@ -4,7 +4,7 @@ import com.boydti.fawe.Fawe; import com.boydti.fawe.database.DBHandler; import com.boydti.fawe.database.RollbackDatabase; import com.boydti.fawe.object.changeset.DiskStorageHistory; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.World; import java.io.IOException; import java.io.OutputStream; @@ -68,7 +68,7 @@ public class RollbackOptimizedHistory extends DiskStorageHistory { return maxZ; } - public void setDimensions(Vector pos1, Vector pos2) { + public void setDimensions(BlockVector3 pos1, BlockVector3 pos2) { this.minX = pos1.getBlockX(); this.minY = pos1.getBlockY(); this.minZ = pos1.getBlockZ(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/ChangeSetFaweQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/object/ChangeSetFaweQueue.java index af427589e..0fa79e911 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/ChangeSetFaweQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/ChangeSetFaweQueue.java @@ -5,6 +5,7 @@ import com.boydti.fawe.object.changeset.FaweChangeSet; import com.boydti.fawe.object.queue.DelegateFaweQueue; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; public class ChangeSetFaweQueue extends DelegateFaweQueue { @@ -28,7 +29,7 @@ public class ChangeSetFaweQueue extends DelegateFaweQueue { if (super.setBlock(x, y, z, combinedId)) { int combinedFrom = getParent().getCombinedId4Data(x, y, z); - BlockTypes typeFrom = BlockTypes.getFromStateId(combinedFrom); + BlockType typeFrom = BlockTypes.getFromStateId(combinedFrom); if (typeFrom.getMaterial().hasContainer()) { CompoundTag nbt = getParent().getTileEntity(x, y, z); if (nbt != null) { 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 37e924fc8..323e918e3 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 @@ -2,12 +2,12 @@ package com.boydti.fawe.object; import com.boydti.fawe.FaweCache; import com.boydti.fawe.object.extent.ExtentHeightCacher; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; @@ -24,7 +24,7 @@ public class DataAnglePattern extends AbstractPattern { this.FACTOR = (1D / distance) * (1D / 255); } - public int getSlope(BlockStateHolder block, Vector vector) { + public int getSlope(BlockStateHolder block, BlockVector3 vector) { int x = vector.getBlockX(); int y = vector.getBlockY(); int z = vector.getBlockZ(); @@ -41,16 +41,16 @@ public class DataAnglePattern extends AbstractPattern { } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { BlockStateHolder block = extent.getBlock(position); int slope = getSlope(block, position); - if (slope == -1) return block; + if (slope == -1) return block.toBaseBlock(); int data = (Math.min(slope, 255)) >> 4; - return block.withPropertyId(data); + return block.withPropertyId(data).toBaseBlock(); } @Override - public boolean apply(Extent extent, Vector setPosition, Vector getPosition) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { BlockStateHolder block = extent.getBlock(getPosition); int slope = getSlope(block, getPosition); if (slope == -1) return false; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/FaweChunk.java b/worldedit-core/src/main/java/com/boydti/fawe/object/FaweChunk.java index ed2e2e8d7..91339926a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/FaweChunk.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/FaweChunk.java @@ -3,7 +3,7 @@ package com.boydti.fawe.object; import com.boydti.fawe.object.visitor.FaweChunkVisitor; import com.boydti.fawe.util.MainUtil; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -21,7 +21,7 @@ public abstract class FaweChunk implements Callable { private int x, z; public static int HEIGHT = 256; - private final ArrayDeque tasks = new ArrayDeque(0); + private final ArrayDeque tasks = new ArrayDeque<>(0); /** * A FaweSections object represents a chunk and the blocks that you wish to change in it. @@ -107,10 +107,10 @@ public abstract class FaweChunk implements Callable { */ public abstract int getBlockCombinedId(int x, int y, int z); - public void setBlock(int x, int y, int z, BlockStateHolder block) { + public > void setBlock(int x, int y, int z, B block) { setBlock(x, y, z, block.getInternalId()); - if (block.hasNbtData()) { - setTile(x & 15, y, z & 15, block.getNbtData()); + if (block instanceof BaseBlock && ((BaseBlock)block).hasNbtData()) { + setTile(x & 15, y, z & 15, ((BaseBlock)block).getNbtData()); } } @@ -120,7 +120,7 @@ public abstract class FaweChunk implements Callable { try { CompoundTag tile = getTile(x & 15, y, z & 15); if (tile != null) { - return BaseBlock.getFromInternalId(combined, tile); + return BaseBlock.getFromInternalId(combined, tile).toImmutableState(); } } catch (Throwable e) { MainUtil.handleError(e); 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 2669a0ff0..f5d161c56 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 @@ -1,6 +1,5 @@ package com.boydti.fawe.object; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import java.util.Collections; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java b/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java index 81ff10de0..7c621d460 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/FawePlayer.java @@ -9,7 +9,6 @@ import com.boydti.fawe.object.brush.visualization.VirtualWorld; import com.boydti.fawe.object.clipboard.DiskOptimizedClipboard; import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.object.task.SimpleAsyncNotifyQueue; -import com.boydti.fawe.object.task.ThrowableSupplier; import com.boydti.fawe.regions.FaweMaskManager; import com.boydti.fawe.util.*; import com.boydti.fawe.wrappers.FakePlayer; @@ -17,13 +16,13 @@ import com.boydti.fawe.wrappers.LocationMaskedPlayerWrapper; import com.boydti.fawe.wrappers.PlayerWrapper; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.command.tool.BrushTool; -import com.sk89q.worldedit.command.tool.Tool; + import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.extension.platform.*; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.*; import com.sk89q.worldedit.regions.selector.ConvexPolyhedralRegionSelector; import com.sk89q.worldedit.regions.selector.CuboidRegionSelector; @@ -40,7 +39,6 @@ import java.text.NumberFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; public abstract class FawePlayer extends Metadatable { @@ -163,18 +161,10 @@ public abstract class FawePlayer extends Metadatable { private void setConfirmTask(@Nullable Runnable task, CommandContext context, String command) { if (task != null) { - Runnable newTask = new Runnable() { - @Override - public void run() { - CommandManager.getInstance().handleCommandTask(new ThrowableSupplier() { - @Override - public Object get() throws Throwable { - task.run(); - return null; - } - }, context.getLocals()); - } - }; + Runnable newTask = () -> CommandManager.getInstance().handleCommandTask(() -> { + task.run(); + return null; + }, context.getLocals()); setMeta("cmdConfirm", newTask); } else { setMeta("cmdConfirm", new CommandEvent(getPlayer(), command)); @@ -208,12 +198,13 @@ public abstract class FawePlayer extends Metadatable { public void checkConfirmationStack(@Nullable Runnable task, String command, Region region, int times, CommandContext context) throws RegionOperationException { if (command != null && !getMeta("cmdConfirmRunning", false)) { if (region != null) { - Vector min = region.getMinimumPoint().toBlockVector(); - Vector max = region.getMaximumPoint().toBlockVector(); + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); long area = (long) ((max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1)) * times; if (area > 2 << 18) { setConfirmTask(task, context, command); - long volume = (long) max.subtract(min).add(Vector.ONE).volume() * times; + BlockVector3 base = max.subtract(min).add(BlockVector3.ONE); + long volume = (long) base.getX() * base.getZ() * base.getY() * times; throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(min, max, command, NumberFormat.getNumberInstance().format(volume))); } } @@ -224,12 +215,13 @@ public abstract class FawePlayer extends Metadatable { public void checkConfirmationRegion(@Nullable Runnable task, String command, Region region, CommandContext context) throws RegionOperationException { if (command != null && !getMeta("cmdConfirmRunning", false)) { if (region != null) { - Vector min = region.getMinimumPoint().toBlockVector(); - Vector max = region.getMaximumPoint().toBlockVector(); + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); long area = (long) ((max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1)); if (area > 2 << 18) { setConfirmTask(task, context, command); - long volume = (long) max.subtract(min).add(Vector.ONE).volume(); + BlockVector3 base = max.subtract(min).add(BlockVector3.ONE); + long volume = (long) base.getX() * base.getZ() * base.getY(); throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(min, max, command, NumberFormat.getNumberInstance().format(volume))); } } @@ -362,15 +354,15 @@ public abstract class FawePlayer extends Metadatable { } } catch (EmptyClipboardException e) { } - if (player != null && session != null) { + if (player != null) { Clipboard clip = doc.toClipboard(); ClipboardHolder holder = new ClipboardHolder(clip); getSession().setClipboard(holder); } } - } catch (Exception ignore) { + } catch (Exception event) { Fawe.debug("====== INVALID CLIPBOARD ======"); - MainUtil.handleError(ignore, false); + MainUtil.handleError(event, false); Fawe.debug("===============---============="); Fawe.debug("This shouldn't result in any failure"); Fawe.debug("File: " + file.getName() + " (len:" + file.length() + ")"); @@ -561,8 +553,8 @@ public abstract class FawePlayer extends Metadatable { @Deprecated public void setSelection(final RegionWrapper region) { final Player player = this.getPlayer(); - Vector top = region.getMaximumPoint(); - top.mutY(getWorld().getMaxY()); + BlockVector3 top = region.getMaximumPoint(); + top.withY(getWorld().getMaxY()); final RegionSelector selector = new CuboidRegionSelector(player.getWorld(), region.getMinimumPoint(), top); this.getSession().setRegionSelector(player.getWorld(), selector); } @@ -692,7 +684,7 @@ public abstract class FawePlayer extends Metadatable { PlayerProxy proxy = new PlayerProxy(player, permActor, cuiActor, world); if (world instanceof VirtualWorld) { - proxy.setOffset(Vector.ZERO.subtract(((VirtualWorld) world).getOrigin())); + proxy.setOffset(Vector3.ZERO.subtract(((VirtualWorld) world).getOrigin())); } return proxy; } @@ -731,4 +723,4 @@ public abstract class FawePlayer extends Metadatable { } return map; } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/FaweQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/object/FaweQueue.java index cd82ce393..026d9d38f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/FaweQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/FaweQueue.java @@ -12,17 +12,18 @@ import com.boydti.fawe.util.MemUtil; import com.boydti.fawe.util.SetQueue; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import java.io.File; @@ -61,13 +62,13 @@ public interface FaweQueue extends HasFaweQueue, Extent { } @Override - default Vector getMinimumPoint() { - return new Vector(-30000000, 0, -30000000); + default BlockVector3 getMinimumPoint() { + return BlockVector3.at(-30000000, 0, -30000000); } @Override - default Vector getMaximumPoint() { - return new Vector(30000000, getMaxY(), 30000000); + default BlockVector3 getMaximumPoint() { + return BlockVector3.at(30000000, getMaxY(), 30000000); } @Override @@ -75,12 +76,6 @@ public interface FaweQueue extends HasFaweQueue, Extent { int combinedId4Data = getCachedCombinedId4Data(x, y, z, BlockTypes.AIR.getInternalId()); try { BlockState state = BlockState.getFromInternalId(combinedId4Data); - if (state.getMaterial().hasContainer()) { - CompoundTag tile = getTileEntity(x, y, z); - if (tile != null) { - return BaseBlock.getFromInternalId(combinedId4Data, tile); - } - } return state; } catch (Throwable e) { MainUtil.handleError(e); @@ -89,22 +84,35 @@ public interface FaweQueue extends HasFaweQueue, Extent { } @Override - default boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { - return setBlock(x, y, z, block.getInternalId(), block.getNbtData()); + default > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { + return setBlock(x, y, z, block.getInternalId(), block instanceof BaseBlock ? ((BaseBlock)block).getNbtData() : null); } @Override - default BlockState getFullBlock(Vector position) { - return getLazyBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ()); + default BaseBlock getFullBlock(BlockVector3 position) { + int combinedId4Data = getCachedCombinedId4Data(position.getBlockX(), position.getBlockY(), position.getBlockZ(), BlockTypes.AIR.getInternalId()); + try { + BaseBlock block = BaseBlock.getFromInternalId(combinedId4Data, null); + if (block.getMaterial().hasContainer()) { + CompoundTag tile = getTileEntity(position.getBlockX(), position.getBlockY(), position.getBlockZ()); + if (tile != null) { + return BaseBlock.getFromInternalId(combinedId4Data, tile); + } + } + return block; + } catch (Throwable e) { + MainUtil.handleError(e); + return BlockTypes.AIR.getDefaultState().toBaseBlock(); + } } @Override - default BaseBiome getBiome(Vector2D position) { + default BaseBiome getBiome(BlockVector2 position) { return null; } @Override - default boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + default > boolean setBlock(BlockVector3 position, B block) throws WorldEditException { return setBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ(), block); } @@ -119,7 +127,7 @@ public interface FaweQueue extends HasFaweQueue, Extent { } @Override - default boolean setBiome(Vector2D position, BaseBiome biome) { + default boolean setBiome(BlockVector2 position, BaseBiome biome) { return setBiome(position.getBlockX(), position.getBlockZ(), biome); } @@ -262,10 +270,10 @@ public interface FaweQueue extends HasFaweQueue, Extent { void addTask(Runnable whenFree); - default void forEachBlockInChunk(int cx, int cz, RunnableVal2 onEach) { + default void forEachBlockInChunk(int cx, int cz, RunnableVal2 onEach) { int bx = cx << 4; int bz = cz << 4; - MutableBlockVector mutable = new MutableBlockVector(0, 0, 0); + MutableBlockVector3 mutable = new MutableBlockVector3(0, 0, 0); for (int x = 0; x < 16; x++) { int xx = x + bx; mutable.mutX(xx); @@ -274,31 +282,27 @@ public interface FaweQueue extends HasFaweQueue, Extent { mutable.mutZ(zz); for (int y = 0; y <= getMaxY(); y++) { int combined = getCombinedId4Data(xx, y, zz); - BlockState state = BlockState.getFromInternalId(combined); - BlockTypes type = state.getBlockType(); - switch (type.getTypeEnum()) { - case AIR: - case VOID_AIR: - case CAVE_AIR: - continue; + BaseBlock block = BlockState.getFromInternalId(combined).toBaseBlock(); + BlockType type = block.getBlockType(); + if (type.getMaterial().isAir()) { + continue; } mutable.mutY(y); CompoundTag tile = getTileEntity(x, y, z); if (tile != null) { - BaseBlock block = BaseBlock.getFromInternalId(combined, tile); - onEach.run(mutable, block); + onEach.run(mutable, block.toBaseBlock(tile)); } else { - onEach.run(mutable, state); + onEach.run(mutable, block); } } } } } - default void forEachTileInChunk(int cx, int cz, RunnableVal2 onEach) { + default void forEachTileInChunk(int cx, int cz, RunnableVal2 onEach) { int bx = cx << 4; int bz = cz << 4; - MutableBlockVector mutable = new MutableBlockVector(0, 0, 0); + MutableBlockVector3 mutable = new MutableBlockVector3(0, 0, 0); for (int x = 0; x < 16; x++) { int xx = x + bx; for (int z = 0; z < 16; z++) { @@ -308,7 +312,7 @@ public interface FaweQueue extends HasFaweQueue, Extent { if (combined == 0) { continue; } - BlockTypes type = BlockTypes.getFromStateId(combined); + BlockType type = BlockTypes.getFromStateId(combined); if (type.getMaterial().hasContainer()) { CompoundTag tile = getTileEntity(x, y, z); if (tile != null) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/HistoryExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/HistoryExtent.java index 9d858e8d3..bbc6510b3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/HistoryExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/HistoryExtent.java @@ -5,13 +5,16 @@ import com.boydti.fawe.object.changeset.FaweChangeSet; import com.boydti.fawe.object.exception.FaweException; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.history.changeset.ChangeSet; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector2; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; @@ -57,19 +60,19 @@ public class HistoryExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { - BlockStateHolder previous = queue.getLazyBlock(x, y, z); + public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { + BaseBlock previous = queue.getFullBlock(BlockVector3.at(x, y, z)).toBaseBlock(); if (previous.getInternalId() == block.getInternalId()) { - if (!previous.hasNbtData() && !block.hasNbtData()) { + if (!previous.hasNbtData() && (block instanceof BaseBlock && !((BaseBlock)block).hasNbtData())) { return false; } } - this.changeSet.add(x, y, z, previous, block); + this.changeSet.add(x, y, z, previous, block.toBaseBlock()); return getExtent().setBlock(x, y, z, block); } @Override - public boolean setBlock(final Vector location, final BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(final BlockVector3 location, final B block) throws WorldEditException { return setBlock(location.getBlockX(), location.getBlockY(), location.getBlockZ(), block); } @@ -94,7 +97,7 @@ public class HistoryExtent extends AbstractDelegateExtent { } private List wrapEntities(final List entities) { - final List newList = new ArrayList(entities.size()); + final List newList = new ArrayList<>(entities.size()); for (final Entity entity : entities) { newList.add(new TrackedEntity(entity)); } @@ -102,7 +105,7 @@ public class HistoryExtent extends AbstractDelegateExtent { } @Override - public boolean setBiome(Vector2D position, BaseBiome newBiome) { + public boolean setBiome(BlockVector2 position, BaseBiome newBiome) { BaseBiome oldBiome = this.getBiome(position); if (oldBiome.getId() != newBiome.getId()) { this.changeSet.addBiomeChange(position.getBlockX(), position.getBlockZ(), oldBiome, newBiome); @@ -114,7 +117,7 @@ public class HistoryExtent extends AbstractDelegateExtent { @Override public boolean setBiome(int x, int y, int z, BaseBiome newBiome) { - BaseBiome oldBiome = this.getBiome(MutableBlockVector2D.get(x, z)); + BaseBiome oldBiome = this.getBiome(BlockVector2.at(x, z)); if (oldBiome.getId() != newBiome.getId()) { this.changeSet.addBiomeChange(x, z, oldBiome, newBiome); return getExtent().setBiome(x, y, z, newBiome); @@ -161,5 +164,10 @@ public class HistoryExtent extends AbstractDelegateExtent { public T getFacet(final Class cls) { return this.entity.getFacet(cls); } + + @Override + public boolean setLocation(Location location) { + return this.entity.setLocation(location); + } } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/MaskedFaweQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/object/MaskedFaweQueue.java index a6cdb24b0..c460009a6 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/MaskedFaweQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/MaskedFaweQueue.java @@ -6,10 +6,9 @@ import com.boydti.fawe.object.extent.MultiRegionExtent; import com.boydti.fawe.object.extent.SingleRegionExtent; import com.boydti.fawe.object.queue.DelegateFaweQueue; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.biome.BaseBiome; @@ -73,7 +72,7 @@ public class MaskedFaweQueue extends DelegateFaweQueue { } @Override - public boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 position, BlockStateHolder block) throws WorldEditException { if (region.contains(position.getBlockX(), position.getBlockZ())) { return super.setBlock(position, block); } @@ -89,7 +88,7 @@ public class MaskedFaweQueue extends DelegateFaweQueue { } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { if (region.contains(position.getBlockX(), position.getBlockZ())) { return super.setBiome(position, biome); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/NullChangeSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/NullChangeSet.java index 31bc342ad..7117c30f0 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/NullChangeSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/NullChangeSet.java @@ -72,4 +72,16 @@ public class NullChangeSet extends FaweChangeSet { public final int size() { return 0; } + + @Override + public boolean isRecordingChanges() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void setRecordChanges(boolean recordChanges) { + // TODO Auto-generated method stub + + } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/PseudoRandom.java b/worldedit-core/src/main/java/com/boydti/fawe/object/PseudoRandom.java index fd5f15f7f..dabda02d6 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/PseudoRandom.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/PseudoRandom.java @@ -1,5 +1,7 @@ package com.boydti.fawe.object; +import java.util.concurrent.ThreadLocalRandom; + @Deprecated /** * @Deprecated use ThreadLocalRandom instead @@ -7,50 +9,15 @@ package com.boydti.fawe.object; public class PseudoRandom { public static PseudoRandom random = new PseudoRandom(); - private long state; - public PseudoRandom() { - this.state = System.nanoTime(); - } - - public PseudoRandom(final long state) { - this.state = state; - } - - public void setSeed(long state) { - this.state = state; - } - - public long nextLong() { - final long a = this.state; - this.state = this.xorShift64(a); - return a; - } - - public long xorShift64(long a) { - a ^= (a << 21); - a ^= (a >>> 35); - a ^= (a << 4); - return a; - } - - public double nextDouble() { - return 0x1.0p-63 * (((nextLong()) & 0x7FFFFFFFFFFFFFFFl)); } public int random(final int n) { if (n == 1) { return 0; } - final long r = ((this.nextLong() >>> 32) * n) >> 32; + final long r = ((ThreadLocalRandom.current().nextLong() >>> 32) * n) >> 32; return (int) r; } - public int nextInt(int i) { - return random(i); - } - - public int nextInt(int start, int end) { - return nextInt(end - start + 1) + start; - } } 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 ed60c8fc7..8547e081e 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 @@ -1,6 +1,6 @@ package com.boydti.fawe.object; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; @Deprecated @@ -23,10 +23,10 @@ public class RegionWrapper extends CuboidRegion { } public RegionWrapper(final int minX, final int maxX, final int minY, final int maxY, final int minZ, final int maxZ) { - this(new Vector(minX, 0, minZ), new Vector(maxX, 255, maxZ)); + this(BlockVector3.at(minX, 0, minZ), BlockVector3.at(maxX, 255, maxZ)); } - public RegionWrapper(final Vector pos1, final Vector pos2) { + public RegionWrapper(final BlockVector3 pos1, final BlockVector3 pos2) { super(pos1, pos2); this.minX = Math.min(pos1.getBlockX(), pos2.getBlockX()); this.minZ = Math.min(pos1.getBlockZ(), pos2.getBlockZ()); @@ -39,8 +39,8 @@ public class RegionWrapper extends CuboidRegion { @Override protected void recalculate() { super.recalculate(); - Vector pos1 = getMinimumPoint(); - Vector pos2 = getMaximumPoint(); + BlockVector3 pos1 = getMinimumPoint(); + BlockVector3 pos2 = getMaximumPoint(); this.minX = Math.min(pos1.getBlockX(), pos2.getBlockX()); this.minZ = Math.min(pos1.getBlockZ(), pos2.getBlockZ()); this.maxX = Math.max(pos1.getBlockX(), pos2.getBlockX()); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/AngleBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/AngleBrush.java index ea1ae8d15..fdc04129a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/AngleBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/AngleBrush.java @@ -4,10 +4,10 @@ import com.boydti.fawe.object.mask.RadiusMask; import com.boydti.fawe.object.mask.SurfaceMask; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.mask.SolidBlockMask; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; public class AngleBrush implements Brush { @@ -18,7 +18,7 @@ public class AngleBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { SurfaceMask surface = new SurfaceMask(editSession); final SolidBlockMask solid = new SolidBlockMask(editSession); final RadiusMask radius = new RadiusMask(0, (int) size); 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 ccf36e92c..bb94e1a66 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 @@ -3,9 +3,9 @@ package com.boydti.fawe.object.brush; import com.google.common.collect.Maps; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; @@ -15,7 +15,7 @@ import java.util.Map; public class BlendBall implements Brush { @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { final int outsetSize = (int) (size + 1); double brushSizeSquared = size * size; 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 5e32fa456..db139fbf7 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 @@ -4,20 +4,21 @@ import com.boydti.fawe.object.random.SimplexNoise; import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.AffineTransform; import java.util.concurrent.ThreadLocalRandom; public class BlobBrush implements Brush { private final double amplitude; private final double frequency; - private final Vector radius; + private final Vector3 radius; private final double sphericity; - public BlobBrush(Vector radius, double frequency, double amplitude, double sphericity) { + public BlobBrush(Vector3 radius, double frequency, double amplitude, double sphericity) { this.frequency = frequency; this.amplitude = amplitude; this.radius = radius; @@ -25,7 +26,7 @@ public class BlobBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { double seedX = ThreadLocalRandom.current().nextDouble(); double seedY = ThreadLocalRandom.current().nextDouble(); double seedZ = ThreadLocalRandom.current().nextDouble(); @@ -70,7 +71,7 @@ public class BlobBrush implements Brush { double manScaleY = (1.25 + seedY * 0.5); double manScaleZ = (1.25 + seedZ * 0.5); - MutableBlockVector mutable = new MutableBlockVector(); + MutableVector3 mutable = new MutableVector3(); double roughness = 1 - sphericity; for (int xr = -sizeInt; xr <= sizeInt; xr++) { mutable.mutX(xr); @@ -78,10 +79,10 @@ public class BlobBrush implements Brush { mutable.mutY(yr); for (int zr = -sizeInt; zr <= sizeInt; zr++) { mutable.mutZ(zr); - Vector pt = transform.apply(mutable); - int x = MathMan.roundInt(pt.getBlockX()); - int y = MathMan.roundInt(pt.getBlockY()); - int z = MathMan.roundInt(pt.getBlockZ()); + Vector3 pt = transform.apply(mutable); + int x = MathMan.roundInt(pt.getX()); + int y = MathMan.roundInt(pt.getY()); + int z = MathMan.roundInt(pt.getZ()); double xScaled = Math.abs(x) * modX; double yScaled = Math.abs(y) * modY; 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 193f350ac..2010772a6 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 @@ -2,12 +2,15 @@ package com.boydti.fawe.object.brush; import com.boydti.fawe.config.BBC; import com.boydti.fawe.object.brush.visualization.VisualExtent; +import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MathUtils; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.Location; import java.util.Arrays; @@ -18,9 +21,9 @@ public class CatenaryBrush implements Brush, ResettableTool { private final boolean shell, select, direction; private final double slack; - private Vector pos1; - private Vector pos2; - private Vector vertex; + private BlockVector3 pos1; + private BlockVector3 pos2; + private BlockVector3 vertex; public CatenaryBrush(boolean shell, boolean select, boolean direction, double lengthFactor) { this.shell = shell; @@ -30,7 +33,7 @@ public class CatenaryBrush implements Brush, ResettableTool { } @Override - public void build(EditSession editSession, Vector pos2, final Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 pos2, final Pattern pattern, double size) throws MaxChangedBlocksException { boolean visual = (editSession.getExtent() instanceof VisualExtent); if (pos1 == null || pos2.equals(pos1)) { if (!visual) { @@ -47,12 +50,12 @@ public class CatenaryBrush implements Brush, ResettableTool { } } else if (this.direction) { Location loc = editSession.getPlayer().getPlayer().getLocation(); - Vector facing = loc.getDirection().normalize(); - Vector midpoint = pos1.add(pos2).divide(2); - Vector offset = midpoint.subtract(vertex); - vertex = midpoint.add(facing.multiply(offset.length())); + Vector3 facing = loc.getDirection().normalize(); + BlockVector3 midpoint = pos1.add(pos2).divide(2); + BlockVector3 offset = midpoint.subtract(vertex); + vertex = midpoint.add(facing.multiply(offset.length()).toBlockPoint()); } - List nodes = Arrays.asList(pos1, vertex, pos2); + List nodes = Arrays.asList(pos1, vertex, pos2); vertex = null; try { editSession.drawSpline(pattern, nodes, 0, 0, 0, 10, size, !shell); @@ -76,8 +79,8 @@ public class CatenaryBrush implements Brush, ResettableTool { return true; } - public static Vector getVertex(Vector pos1, Vector pos2, double lenPercent) { - if (lenPercent <= 1) return Vector.getMidpoint(pos1, pos2); + public static BlockVector3 getVertex(BlockVector3 pos1, BlockVector3 pos2, double lenPercent) { + if (lenPercent <= 1) return MathUtils.midpoint(pos1, pos2); double curveLen = pos1.distance(pos2) * lenPercent; double dy = pos2.getY() - pos1.getY(); double dx = pos2.getX() - pos1.getX(); @@ -90,6 +93,6 @@ public class CatenaryBrush implements Brush, ResettableTool { double z = (dh/2)/a; double oY = (dy - curveLen * (Math.cosh(z) / Math.sinh(z))) / 2; double vertY = a * 1 + oY; - return pos1.add(pos2.subtract(pos1).multiply(vertX / dh).add(0, vertY, 0)).round(); + return pos1.add(pos2.subtract(pos1).multiply(MathMan.roundInt(vertX / dh)).add(0, MathMan.roundInt(vertY), 0)).round(); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CircleBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CircleBrush.java index 024a279fb..b7160c710 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CircleBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CircleBrush.java @@ -3,10 +3,11 @@ package com.boydti.fawe.object.brush; import com.boydti.fawe.wrappers.LocationMaskedPlayerWrapper; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; 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; import com.sk89q.worldedit.math.transform.AffineTransform; public class CircleBrush implements Brush { @@ -17,21 +18,21 @@ public class CircleBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { - Vector normal = position.subtract(player.getLocation()); + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { + Vector3 normal = position.toVector3().subtract(player.getLocation()); editSession.makeCircle(position, pattern, size, size, size, false, normal); } - private Vector any90Rotate(Vector normal) { + private Vector3 any90Rotate(Vector3 normal) { normal = normal.normalize(); if (normal.getX() == 1 || normal.getY() == 1 || normal.getZ() == 1) { - return new Vector(normal.getZ(), normal.getX(), normal.getY()); + return Vector3.at(normal.getZ(), normal.getX(), normal.getY()); } AffineTransform affine = new AffineTransform(); affine = affine.rotateX(90); affine = affine.rotateY(90); affine = affine.rotateZ(90); - Vector random = affine.apply(normal); + Vector3 random = affine.apply(normal); return random.cross(normal).normalize(); } -} +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CommandBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CommandBrush.java index 82c59a302..396ba249d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CommandBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/CommandBrush.java @@ -7,12 +7,12 @@ import com.boydti.fawe.wrappers.PlayerWrapper; import com.boydti.fawe.wrappers.SilentPlayerWrapper; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.selector.CuboidRegionSelector; import com.sk89q.worldedit.util.Location; import java.util.List; @@ -26,7 +26,7 @@ public class CommandBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { int radius = (int) size; CuboidRegionSelector selector = new CuboidRegionSelector(editSession.getWorld(), position.subtract(radius, radius, radius), position.add(radius, radius, radius)); String replaced = command.replace("{x}", position.getBlockX() + "") @@ -41,10 +41,10 @@ public class CommandBrush implements Brush { if (face == null) { position = position.add(0, 1, 1); } else { - position = position.add(face.getDirection()); + position = position.add(face.getDirection().toBlockPoint()); } fp.setSelection(selector); - PlayerWrapper wePlayer = new SilentPlayerWrapper(new LocationMaskedPlayerWrapper(player, new Location(player.getExtent(), position))); + PlayerWrapper wePlayer = new SilentPlayerWrapper(new LocationMaskedPlayerWrapper(player, new Location(player.getExtent(), position.toVector3()))); List cmds = StringMan.split(replaced, ';'); for (String cmd : cmds) { CommandEvent event = new CommandEvent(wePlayer, cmd); 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 db16b9196..4ddafd9d0 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 @@ -2,7 +2,6 @@ package com.boydti.fawe.object.brush; import com.boydti.fawe.config.BBC; import com.boydti.fawe.object.FawePlayer; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.brush.visualization.VisualExtent; import com.boydti.fawe.object.clipboard.ResizableClipboardBuilder; import com.boydti.fawe.object.function.NullRegionFunction; @@ -10,9 +9,7 @@ import com.boydti.fawe.object.function.mask.AbstractDelegateMask; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extent.clipboard.Clipboard; @@ -22,11 +19,13 @@ import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.world.block.BlockStateHolder; + +import java.util.concurrent.ThreadLocalRandom; public class CopyPastaBrush implements Brush, ResettableTool { @@ -50,7 +49,7 @@ public class CopyPastaBrush implements Brush, ResettableTool { } @Override - public void build(final EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(final EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { FawePlayer fp = editSession.getPlayer(); ClipboardHolder clipboard = session.getExistingClipboard(); if (clipboard == null) { @@ -66,11 +65,11 @@ public class CopyPastaBrush implements Brush, ResettableTool { final int minY = position.getBlockY(); mask = new AbstractDelegateMask(mask) { @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { if (super.test(vector) && vector.getBlockY() >= minY) { - BlockStateHolder block = editSession.getLazyBlock(vector); + BaseBlock block = editSession.getFullBlock(position); if (!block.getBlockType().getMaterial().isAir()) { - builder.add(vector, EditSession.nullBlock, block); + builder.add(vector, EditSession.nullBlock.toBaseBlock(), block); return true; } } @@ -94,7 +93,7 @@ public class CopyPastaBrush implements Brush, ResettableTool { AffineTransform transform = null; if (randomRotate) { if (transform == null) transform = new AffineTransform(); - int rotate = 90 * PseudoRandom.random.nextInt(4); + int rotate = 90 * ThreadLocalRandom.current().nextInt(4); transform = transform.rotateY(rotate); } if (autoRotate) { @@ -120,4 +119,4 @@ public class CopyPastaBrush implements Brush, ResettableTool { editSession.flushQueue(); } } -} \ No newline at end of file +} 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 ee6a8ef50..36f90aeff 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 @@ -7,12 +7,11 @@ import com.boydti.fawe.object.clipboard.FaweClipboard; import com.boydti.fawe.object.clipboard.OffsetFaweClipboard; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.Blocks; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; @@ -23,14 +22,14 @@ public class ErodeBrush implements Brush { private PseudoRandom rand = new PseudoRandom(); - private static final Vector[] FACES_TO_CHECK = {new Vector(0, 0, 1), new Vector(0, 0, -1), new Vector(0, 1, 0), new Vector(0, -1, 0), new Vector(1, 0, 0), new Vector(-1, 0, 0)}; + private static final BlockVector3[] FACES_TO_CHECK = {BlockVector3.at(0, 0, 1), BlockVector3.at(0, 0, -1), BlockVector3.at(0, 1, 0), BlockVector3.at(0, -1, 0), BlockVector3.at(1, 0, 0), BlockVector3.at(-1, 0, 0)}; @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { this.erosion(editSession, 2, 1, 5, 1, position, size); } - public void erosion(final EditSession es, int erodeFaces, int erodeRec, int fillFaces, int fillRec, Vector target, double size) { + public void erosion(final EditSession es, int erodeFaces, int erodeRec, int fillFaces, int fillRec, BlockVector3 target, double size) { int brushSize = (int) size + 1; int brushSizeSquared = (int) (size * size); int dimension = brushSize * 2 + 1; @@ -68,7 +67,7 @@ public class ErodeBrush implements Brush { finalBuffer.forEach(new FaweClipboard.BlockReader() { @Override - public void run(int x, int y, int z, BlockState block) { + public > void run(int x, int y, int z, B block) { es.setBlock(x + bx, y + by, z + bz, block); } }, true); @@ -98,7 +97,7 @@ public class ErodeBrush implements Brush { } else { Arrays.fill(frequency, 0); } - for (Vector offs : FACES_TO_CHECK) { + for (BlockVector3 offs : FACES_TO_CHECK) { BlockStateHolder next = current.getBlock(x + offs.getBlockX(), y + offs.getBlockY(), z + offs.getBlockZ()); if (!next.getBlockType().getMaterial().isMovementBlocker()) { continue; @@ -142,7 +141,7 @@ public class ErodeBrush implements Brush { } else { Arrays.fill(frequency, 0); } - for (Vector offs : FACES_TO_CHECK) { + for (BlockVector3 offs : FACES_TO_CHECK) { BlockStateHolder next = current.getBlock(x + offs.getBlockX(), y + offs.getBlockY(), z + offs.getBlockZ()); if (next.getBlockType().getMaterial().isMovementBlocker()) { continue; 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 e0334ea86..e4506ca6d 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 @@ -3,13 +3,13 @@ package com.boydti.fawe.object.brush; import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; public class FallingSphere implements Brush { @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { int px = position.getBlockX(); int py = position.getBlockY(); int pz = position.getBlockZ(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/FlattenBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/FlattenBrush.java index d446770a7..de2cbc45a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/FlattenBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/FlattenBrush.java @@ -4,11 +4,12 @@ import com.boydti.fawe.object.brush.heightmap.HeightMap; import com.boydti.fawe.object.brush.heightmap.ScalableHeightMap; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Masks; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; + import java.io.InputStream; public class FlattenBrush extends HeightBrush { @@ -18,7 +19,7 @@ public class FlattenBrush extends HeightBrush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double sizeDouble) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double sizeDouble) throws MaxChangedBlocksException { int size = (int) sizeDouble; Mask mask = editSession.getMask(); if (mask == Masks.alwaysTrue() || mask == Masks.alwaysTrue2D()) { 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 c8f73b3a4..8fe610c89 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 @@ -3,7 +3,6 @@ package com.boydti.fawe.object.brush; import com.boydti.fawe.config.BBC; import com.boydti.fawe.jnbt.anvil.HeightMapMCAGenerator; import com.boydti.fawe.object.FaweQueue; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.brush.heightmap.HeightMap; import com.boydti.fawe.object.brush.heightmap.RotatableHeightMap; import com.boydti.fawe.object.brush.heightmap.ScalableHeightMap; @@ -11,15 +10,18 @@ import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Masks; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; + import java.io.IOException; import java.io.InputStream; +import java.util.concurrent.ThreadLocalRandom; public class HeightBrush implements Brush { @@ -58,7 +60,7 @@ public class HeightBrush implements Brush { heightMap = new RotatableHeightMap(heightMap); } RotatableHeightMap rotatable = (RotatableHeightMap) heightMap; - rotatable.rotate(PseudoRandom.random.nextInt(360)); + rotatable.rotate(ThreadLocalRandom.current().nextInt(360)); } return heightMap; } @@ -68,7 +70,7 @@ public class HeightBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double sizeDouble) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double sizeDouble) throws MaxChangedBlocksException { int size = (int) sizeDouble; HeightMap map = getHeightMap(); map.setSize(size); @@ -83,7 +85,7 @@ public class HeightBrush implements Brush { hmmg.getMetaData().setMeta("PRECISION_HEIGHT", metaHeight = new byte[hmmg.getArea()]); } - Vector origin = hmmg.getOrigin(); + Vector3 origin = hmmg.getOrigin(); int bx = position.getBlockX(); int bz = position.getBlockZ(); @@ -131,14 +133,14 @@ public class HeightBrush implements Brush { } if (smooth) { - Vector2D min = new Vector2D(Math.max(0, bx - size), Math.max(0, bz - size)); - Vector2D max = new Vector2D(Math.min(hmmg.getWidth() - 1, bx + size), Math.min(hmmg.getLength() - 1, bz + size)); + BlockVector2 min = BlockVector2.at(Math.max(0, bx - size), Math.max(0, bz - size)); + BlockVector2 max = BlockVector2.at(Math.min(hmmg.getWidth() - 1, bx + size), Math.min(hmmg.getLength() - 1, bz + size)); hmmg.smooth(min, max, 8, 1); if (size > 20) { int smoothSize = size + 8; - min = new Vector2D(Math.max(0, bx - smoothSize), Math.max(0, bz - smoothSize)); - max = new Vector2D(Math.min(hmmg.getWidth() - 1, bx + smoothSize), Math.min(hmmg.getLength() - 1, bz + smoothSize)); + min = BlockVector2.at(Math.max(0, bx - smoothSize), Math.max(0, bz - smoothSize)); + max = BlockVector2.at(Math.min(hmmg.getWidth() - 1, bx + smoothSize), Math.min(hmmg.getLength() - 1, bz + smoothSize)); hmmg.smooth(min, max, 1, 1); } } 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 670fb66f0..31d9ace89 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 @@ -6,16 +6,15 @@ import com.boydti.fawe.util.TextureUtil; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.Mask; -import com.sk89q.worldedit.function.mask.SolidBlockMask; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -64,15 +63,15 @@ public class ImageBrush implements Brush { } private interface ColorFunction { - int call(int x1, int z1, int x2, int z2, Extent extent, Vector pos); + int call(int x1, int z1, int x2, int z2, Extent extent, BlockVector3 pos); } private interface BlockFunction { - void apply(int color, Extent extent, Vector pos); + void apply(int color, Extent extent, BlockVector3 pos); } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double sizeDouble) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double sizeDouble) throws MaxChangedBlocksException { TextureUtil texture = session.getTextureUtil(); final int cx = position.getBlockX(); @@ -88,19 +87,19 @@ public class ImageBrush implements Brush { AffineTransform transform = new AffineTransform().rotateY((-yaw) % 360).rotateX((pitch - 90) % 360).inverse(); RecursiveVisitor visitor = new RecursiveVisitor(new Mask() { - private final Vector mutable = new Vector(); + private final MutableVector3 mutable = new MutableVector3(); @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { if (solid.test(vector)) { int dx = vector.getBlockX() - cx; int dy = vector.getBlockY() - cy; int dz = vector.getBlockZ() - cz; - Vector pos1 = transform.apply(mutable.setComponents(dx - 0.5, dy - 0.5, dz - 0.5)); + Vector3 pos1 = transform.apply(mutable.setComponents(dx - 0.5, dy - 0.5, dz - 0.5)); int x1 = (int) (pos1.getX() * scale + centerX); int z1 = (int) (pos1.getZ() * scale + centerZ); - Vector pos2 = transform.apply(mutable.setComponents(dx + 0.5, dy + 0.5, dz + 0.5)); + Vector3 pos2 = transform.apply(mutable.setComponents(dx + 0.5, dy + 0.5, dz + 0.5)); int x2 = (int) (pos2.getX() * scale + centerX); int z2 = (int) (pos2.getZ() * scale + centerZ); if (x2 < x1) { 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 143115aa1..785ab43af 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 @@ -13,12 +13,13 @@ import com.boydti.fawe.util.EditSessionBuilder; import com.boydti.fawe.util.MainUtil; import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.BrushTool; import com.sk89q.worldedit.command.tool.DoubleActionTraceTool; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Platform; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.block.BlockState; @@ -47,14 +48,14 @@ public class InspectBrush extends BrushTool implements DoubleActionTraceTool { return perform(player, session, true); } - public Vector getTarget(Player player, boolean adjacent) { + public Vector3 getTarget(Player player, boolean adjacent) { Location target = null; int range = this.range > -1 ? getRange() : MAX_RANGE; if (adjacent) { Location face = player.getBlockTraceFace(range, true); - return face.toVector().add(face.getDirection()); + return face.add(face.getDirection()); } else { - return player.getBlockTrace(getRange(), true).toVector(); + return player.getBlockTrace(getRange(), true); } } @@ -67,7 +68,7 @@ public class InspectBrush extends BrushTool implements DoubleActionTraceTool { player.print(BBC.getPrefix() + BBC.SETTING_DISABLE.f("history.use-database (Import with /frb #import )")); return false; } - Vector target = getTarget(player, rightClick); + BlockVector3 target = getTarget(player, rightClick).toBlockPoint(); final int x = target.getBlockX(); final int y = target.getBlockY(); final int z = target.getBlockZ(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/LayerBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/LayerBrush.java index 3635a11f1..fccf2502c 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/LayerBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/LayerBrush.java @@ -6,10 +6,7 @@ import com.boydti.fawe.object.mask.AdjacentAnyMask; import com.boydti.fawe.object.mask.RadiusMask; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; -import com.sk89q.worldedit.function.mask.BlockMask; import com.sk89q.worldedit.function.mask.BlockTypeMask; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.SolidBlockMask; @@ -17,7 +14,8 @@ import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.visitor.BreadthFirstSearch; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; @@ -27,14 +25,14 @@ public class LayerBrush implements Brush { private final BlockStateHolder[] layers; private RecursiveVisitor visitor; - private MutableBlockVector mutable = new MutableBlockVector(); + private MutableBlockVector3 mutable = new MutableBlockVector3(); public LayerBrush(BlockStateHolder[] layers) { this.layers = layers; } @Override - public void build(EditSession editSession, Vector position, Pattern ignore, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern ignore, double size) throws MaxChangedBlocksException { final FaweQueue queue = editSession.getQueue(); final AdjacentAnyMask adjacent = new AdjacentAnyMask(new BlockTypeMask(editSession, BlockTypes.AIR, BlockTypes.CAVE_AIR, BlockTypes.VOID_AIR)); final SolidBlockMask solid = new SolidBlockMask(editSession); @@ -51,7 +49,7 @@ public class LayerBrush implements Brush { boolean found = false; int previous = layers[depth - 1].getInternalId(); int previous2 = layers[depth - 2].getInternalId(); - for (Vector dir : BreadthFirstSearch.DEFAULT_DIRECTIONS) { + for (BlockVector3 dir : BreadthFirstSearch.DEFAULT_DIRECTIONS) { mutable.setComponents(pos.getBlockX() + dir.getBlockX(), pos.getBlockY() + dir.getBlockY(), pos.getBlockZ() + dir.getBlockZ()); if (visitor.isVisited(mutable) && queue.getCachedCombinedId4Data(mutable.getBlockX(), mutable.getBlockY(), mutable.getBlockZ()) == previous) { mutable.setComponents(pos.getBlockX() + dir.getBlockX() * 2, pos.getBlockY() + dir.getBlockY() * 2, pos.getBlockZ() + dir.getBlockZ() * 2); @@ -73,7 +71,7 @@ public class LayerBrush implements Brush { BlockStateHolder currentPattern = layers[depth]; return editSession.setBlock(pos, currentPattern); }, layers.length - 1, editSession); - for (Vector pos : visited) { + for (BlockVector3 pos : visited) { visitor.visit(pos); } Operations.completeBlindly(visitor); 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 cdf6d0dcd..0ed02da3d 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 @@ -4,14 +4,14 @@ import com.boydti.fawe.config.BBC; import com.boydti.fawe.object.brush.visualization.VisualExtent; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; public class LineBrush implements Brush, ResettableTool { private final boolean shell, select, flat; - private Vector pos1; + private BlockVector3 pos1; public LineBrush(boolean shell, boolean select, boolean flat) { this.shell = shell; @@ -20,7 +20,7 @@ public class LineBrush implements Brush, ResettableTool { } @Override - public void build(EditSession editSession, Vector position, final Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, final Pattern pattern, double size) throws MaxChangedBlocksException { boolean visual = (editSession.getExtent() instanceof VisualExtent); if (pos1 == null) { if (!visual) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/PopulateSchem.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/PopulateSchem.java index 3c404e3a8..c16290a46 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/PopulateSchem.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/PopulateSchem.java @@ -2,13 +2,14 @@ package com.boydti.fawe.object.brush; import com.boydti.fawe.jnbt.anvil.generator.SchemGen; import com.boydti.fawe.util.MaskTraverser; +import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.session.ClipboardHolder; import java.util.List; @@ -27,10 +28,11 @@ public class PopulateSchem implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { new MaskTraverser(mask).reset(editSession); SchemGen gen = new SchemGen(mask, editSession, clipboards, randomRotate); - CuboidRegion cuboid = new CuboidRegion(editSession.getWorld(), position.subtract(size, size, size), position.add(size, size, size)); + int size1 = MathMan.roundInt(size); + CuboidRegion cuboid = new CuboidRegion(editSession.getWorld(), position.subtract(size1, size1, size1), position.add(size1, size1, size1)); try { editSession.addSchems(cuboid, mask, clipboards, rarity, randomRotate); } catch (WorldEditException e) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RaiseBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RaiseBrush.java index 7e7bd283d..4bbb4642a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RaiseBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RaiseBrush.java @@ -2,12 +2,12 @@ package com.boydti.fawe.object.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; public class RaiseBrush extends ErodeBrush { @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { this.erosion(editSession, 6, 0, 1, 1, position, size); } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RecurseBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RecurseBrush.java index 53a445242..0b41f3625 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RecurseBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/RecurseBrush.java @@ -4,8 +4,6 @@ import com.boydti.fawe.object.mask.RadiusMask; import com.boydti.fawe.object.visitor.DFSRecursiveVisitor; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.block.BlockReplace; @@ -14,6 +12,7 @@ import com.sk89q.worldedit.function.mask.Masks; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; public class RecurseBrush implements Brush { @@ -25,7 +24,7 @@ public class RecurseBrush implements Brush { } @Override - public void build(final EditSession editSession, final Vector position, Pattern to, double size) throws MaxChangedBlocksException { + public void build(final EditSession editSession, final BlockVector3 position, Pattern to, double size) throws MaxChangedBlocksException { Mask mask = editSession.getMask(); if (mask == null) { mask = Masks.alwaysTrue(); @@ -42,7 +41,7 @@ public class RecurseBrush implements Brush { final Mask radMask = new RadiusMask(0, (int) size); DFSRecursiveVisitor visitor = new DFSRecursiveVisitor(mask, replace, Integer.MAX_VALUE, Integer.MAX_VALUE) { @Override - public boolean isVisitable(Vector from, Vector to) { + public boolean isVisitable(BlockVector3 from, BlockVector3 to) { int y = to.getBlockY(); return y >= y && y < maxY && radMask.test(to) && super.isVisitable(from, to); } @@ -52,7 +51,7 @@ public class RecurseBrush implements Brush { } else { RecursiveVisitor visitor = new RecursiveVisitor(mask, replace, radius, editSession) { @Override - public boolean isVisitable(Vector from, Vector to) { + public boolean isVisitable(BlockVector3 from, BlockVector3 to) { int y = to.getBlockY(); return y >= y && y < maxY && super.isVisitable(from, to); } 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 c89d4e2e3..32cf5ba18 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 @@ -3,24 +3,26 @@ package com.boydti.fawe.object.brush; import com.boydti.fawe.object.random.SimplexNoise; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; + import java.util.concurrent.ThreadLocalRandom; public class RockBrush implements Brush { private final double amplitude; private final double frequency; - private final Vector radius; + private final Vector3 radius; - public RockBrush(Vector radius, double frequency, double amplitude) { + public RockBrush(Vector3 radius, double frequency, double amplitude) { this.frequency = frequency; this.amplitude = amplitude; this.radius = radius; } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { double seedX = ThreadLocalRandom.current().nextDouble(); double seedY = ThreadLocalRandom.current().nextDouble(); double seedZ = ThreadLocalRandom.current().nextDouble(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterBrush.java index 6049ae774..0b4dd8534 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterBrush.java @@ -1,6 +1,5 @@ package com.boydti.fawe.object.brush; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.collection.BlockVectorSet; import com.boydti.fawe.object.collection.LocalBlockVectorSet; import com.boydti.fawe.object.mask.AdjacentAnyMask; @@ -8,7 +7,6 @@ import com.boydti.fawe.object.mask.RadiusMask; import com.boydti.fawe.object.mask.SurfaceMask; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Masks; @@ -16,7 +14,10 @@ import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.visitor.BreadthFirstSearch; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; +import com.sk89q.worldedit.math.BlockVector3; + import java.util.Arrays; +import java.util.concurrent.ThreadLocalRandom; public class ScatterBrush implements Brush { @@ -39,7 +40,7 @@ public class ScatterBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { this.mask = editSession.getMask(); if (this.mask == null) { this.mask = Masks.alwaysTrue(); @@ -62,8 +63,8 @@ public class ScatterBrush implements Brush { LocalBlockVectorSet placed = new LocalBlockVectorSet(); int maxFails = 1000; for (int i = 0; i < count; i++) { - int index = PseudoRandom.random.nextInt(length); - Vector pos = visited.get(index); + int index = ThreadLocalRandom.current().nextInt(length); + BlockVector3 pos = visited.get(index); if (pos != null && canApply(editSession, pos)) { int x = pos.getBlockX(); int y = pos.getBlockY(); @@ -82,18 +83,18 @@ public class ScatterBrush implements Brush { finish(editSession, placed, position, pattern, size); } - public void finish(EditSession editSession, LocalBlockVectorSet placed, Vector pos, Pattern pattern, double size) { + public void finish(EditSession editSession, LocalBlockVectorSet placed, BlockVector3 pos, Pattern pattern, double size) { } - public boolean canApply(EditSession editSession, Vector pos) { + public boolean canApply(EditSession editSession, BlockVector3 pos) { return mask.test(pos); } - public Vector getDirection(Vector pt) { + public BlockVector3 getDirection(BlockVector3 pt) { return surface.direction(pt); } - public void apply(EditSession editSession, LocalBlockVectorSet placed, Vector pt, Pattern p, double size) throws MaxChangedBlocksException { + public void apply(EditSession editSession, LocalBlockVectorSet placed, BlockVector3 pt, Pattern p, double size) throws MaxChangedBlocksException { editSession.setBlock(pt, p); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterCommand.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterCommand.java index 02df4fa84..c7edce44c 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterCommand.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterCommand.java @@ -8,11 +8,11 @@ import com.boydti.fawe.wrappers.PlayerWrapper; import com.boydti.fawe.wrappers.SilentPlayerWrapper; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.selector.CuboidRegionSelector; import com.sk89q.worldedit.util.Location; import java.util.List; @@ -26,7 +26,7 @@ public class ScatterCommand extends ScatterBrush { } @Override - public void apply(EditSession editSession, LocalBlockVectorSet placed, Vector position, Pattern p, double size) throws MaxChangedBlocksException { + public void apply(EditSession editSession, LocalBlockVectorSet placed, BlockVector3 position, Pattern p, double size) throws MaxChangedBlocksException { int radius = getDistance(); CuboidRegionSelector selector = new CuboidRegionSelector(editSession.getWorld(), position.subtract(radius, radius, radius), position.add(radius, radius, radius)); String replaced = command.replace("{x}", position.getBlockX() + "") @@ -38,7 +38,7 @@ public class ScatterCommand extends ScatterBrush { FawePlayer fp = editSession.getPlayer(); Player player = fp.getPlayer(); fp.setSelection(selector); - PlayerWrapper wePlayer = new SilentPlayerWrapper(new LocationMaskedPlayerWrapper(player, new Location(player.getExtent(), position))); + PlayerWrapper wePlayer = new SilentPlayerWrapper(new LocationMaskedPlayerWrapper(player, new Location(player.getExtent(), position.toVector3()))); List cmds = StringMan.split(replaced, ';'); for (String cmd : cmds) { CommandEvent event = new CommandEvent(wePlayer, cmd); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterOverlayBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterOverlayBrush.java index fa29ebd8c..9e6f80c0b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterOverlayBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ScatterOverlayBrush.java @@ -3,8 +3,8 @@ package com.boydti.fawe.object.brush; import com.boydti.fawe.object.collection.LocalBlockVectorSet; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; public class ScatterOverlayBrush extends ScatterBrush { public ScatterOverlayBrush(int count, int distance) { @@ -12,12 +12,12 @@ public class ScatterOverlayBrush extends ScatterBrush { } @Override - public void apply(EditSession editSession, LocalBlockVectorSet placed, Vector pt, Pattern p, double size) throws MaxChangedBlocksException { + public void apply(EditSession editSession, LocalBlockVectorSet placed, BlockVector3 pt, Pattern p, double size) throws MaxChangedBlocksException { int x = pt.getBlockX(); int y = pt.getBlockY(); int z = pt.getBlockZ(); - Vector dir = getDirection(pt); - dir.setComponents(x + dir.getBlockX(), y + dir.getBlockY(), z + dir.getBlockZ()); - editSession.setBlock(dir, p); + BlockVector3 dir = getDirection(pt); +// dir.setComponents(x + dir.getBlockX(), y + dir.getBlockY(), z + dir.getBlockZ()); + editSession.setBlock(x + dir.getBlockX(), y + dir.getBlockY(), z + dir.getBlockZ(), p); } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ShatterBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ShatterBrush.java index 5617826b9..6b4fb75c9 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ShatterBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/ShatterBrush.java @@ -5,26 +5,26 @@ import com.boydti.fawe.object.collection.LocalBlockVectorSet; import com.boydti.fawe.object.mask.SurfaceMask; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Masks; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.visitor.BreadthFirstSearch; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; public class ShatterBrush extends ScatterBrush { - private final MutableBlockVector mutable = new MutableBlockVector(); + private final MutableBlockVector3 mutable = new MutableBlockVector3(); public ShatterBrush(int count) { super(count, 1); } @Override - public void apply(final EditSession editSession, final LocalBlockVectorSet placed, final Vector position, Pattern p, double size) throws MaxChangedBlocksException { + public void apply(final EditSession editSession, final LocalBlockVectorSet placed, final BlockVector3 position, Pattern p, double size) throws MaxChangedBlocksException { } @Override - public void finish(EditSession editSession, LocalBlockVectorSet placed, final Vector position, Pattern pattern, double size) { + public void finish(EditSession editSession, LocalBlockVectorSet placed, final BlockVector3 position, Pattern pattern, double size) { int radius2 = (int) (size * size); // Keep track of where we've visited LocalBlockVectorSet tmp = new LocalBlockVectorSet(); @@ -34,7 +34,7 @@ public class ShatterBrush extends ScatterBrush { LocalBlockVectorSet[] frontiersVisited = new LocalBlockVectorSet[placed.size()]; // Initiate the frontier with the starting points int i = 0; - for (Vector pos : placed) { + for (BlockVector3 pos : placed) { LocalBlockVectorSet set = new LocalBlockVectorSet(); set.add(pos); frontiers[i] = set; @@ -66,7 +66,7 @@ public class ShatterBrush extends ScatterBrush { return; } for (int i = 0; i < BreadthFirstSearch.DIAGONAL_DIRECTIONS.length; i++) { - Vector direction = BreadthFirstSearch.DIAGONAL_DIRECTIONS[i]; + BlockVector3 direction = BreadthFirstSearch.DIAGONAL_DIRECTIONS[i]; int x2 = x + direction.getBlockX(); int y2 = y + direction.getBlockY(); int z2 = z + direction.getBlockZ(); @@ -76,8 +76,9 @@ public class ShatterBrush extends ScatterBrush { int dz = position.getBlockZ() - z2; int dSqr = (dx * dx) + (dy * dy) + (dz * dz); if (dSqr <= radius2) { - MutableBlockVector v = mutable.setComponents(x2, y2, z2); - if (surfaceTest.test(v) && finalMask.test(v)) { + MutableBlockVector3 v = mutable.setComponents(x2, y2, z2); + BlockVector3 bv = v; + if (surfaceTest.test(bv) && finalMask.test(bv)) { // (collision) If it's visited and part of another frontier, set the block if (!placed.add(x2, y2, z2)) { if (!frontierVisited.contains(x2, y2, z2)) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SpikeBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SpikeBrush.java index bc1c3c039..e4362abaa 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SpikeBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SpikeBrush.java @@ -2,14 +2,14 @@ package com.boydti.fawe.object.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; public class SpikeBrush implements Brush { @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplatterBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplatterBrush.java index 93a5f756e..7b2e7f3ce 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplatterBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplatterBrush.java @@ -6,7 +6,6 @@ import com.boydti.fawe.object.mask.SurfaceMask; import com.boydti.fawe.object.pattern.BiomePattern; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.mask.Mask; @@ -14,6 +13,8 @@ import com.sk89q.worldedit.function.mask.SolidBlockMask; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; +import com.sk89q.worldedit.math.BlockVector3; + import java.util.Arrays; public class SplatterBrush extends ScatterBrush { @@ -27,7 +28,7 @@ public class SplatterBrush extends ScatterBrush { } @Override - public void apply(final EditSession editSession, final LocalBlockVectorSet placed, final Vector position, Pattern p, double size) throws MaxChangedBlocksException { + public void apply(final EditSession editSession, final LocalBlockVectorSet placed, final BlockVector3 position, Pattern p, double size) throws MaxChangedBlocksException { final Pattern finalPattern; if (solid) { Pattern tmp; @@ -46,7 +47,7 @@ public class SplatterBrush extends ScatterBrush { RecursiveVisitor visitor = new RecursiveVisitor(new Mask() { @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { double dist = vector.distanceSq(position); if (dist < size2 && !placed.contains(vector) && (PseudoRandom.random.random(5) < 2) && surface.test(vector)) { placed.add(vector); @@ -56,7 +57,7 @@ public class SplatterBrush extends ScatterBrush { } }, new RegionFunction() { @Override - public boolean apply(Vector vector) throws WorldEditException { + public boolean apply(BlockVector3 vector) throws WorldEditException { return editSession.setBlock(vector, finalPattern); } }, recursion, editSession); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplineBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplineBrush.java index a8f2ad339..c4f7d817d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplineBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SplineBrush.java @@ -8,7 +8,6 @@ import com.boydti.fawe.object.visitor.DFSRecursiveVisitor; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.entity.Player; @@ -17,6 +16,9 @@ import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.MaskIntersection; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.interpolation.Node; import java.util.ArrayList; import java.util.Collection; @@ -27,12 +29,12 @@ import java.util.List; public class SplineBrush implements Brush, ResettableTool { public static int MAX_POINTS = 15; - private ArrayList> positionSets; + private ArrayList> positionSets; private int numSplines; private final LocalSession session; private final Player player; - private Vector position; + private BlockVector3 position; public SplineBrush(Player player, LocalSession session) { this.session = session; @@ -50,7 +52,7 @@ public class SplineBrush implements Brush, ResettableTool { } @Override - public void build(EditSession editSession, final Vector position, Pattern pattern, double size) throws WorldEditException { + public void build(EditSession editSession, final BlockVector3 position, Pattern pattern, double size) throws WorldEditException { Mask mask = editSession.getMask(); if (mask == null) { mask = new IdMask(editSession); @@ -68,21 +70,21 @@ public class SplineBrush implements Brush, ResettableTool { if (positionSets.size() >= MAX_POINTS) { throw new FaweException(BBC.WORLDEDIT_CANCEL_REASON_MAX_CHECKS); } - final ArrayList points = new ArrayList<>(); + final ArrayList points = new ArrayList<>(); if (size > 0) { DFSRecursiveVisitor visitor = new DFSRecursiveVisitor(mask, new RegionFunction() { @Override - public boolean apply(Vector p) { - points.add(new Vector(p)); + public boolean apply(BlockVector3 p) { + points.add(p); return true; } }, (int) size, 1); - List directions = visitor.getDirections(); + List directions = visitor.getDirections(); for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { for (int z = -1; z <= 1; z++) { if (x != 0 || y != 0 || z != 0) { - Vector pos = new Vector(x, y, z); + BlockVector3 pos = BlockVector3.at(x, y, z); if (!directions.contains(pos)) { directions.add(pos); } @@ -109,8 +111,8 @@ public class SplineBrush implements Brush, ResettableTool { player.print(BBC.getPrefix() + BBC.BRUSH_SPLINE_SECONDARY_ERROR.s()); return; } - List centroids = new ArrayList<>(); - for (List points : positionSets) { + List centroids = new ArrayList<>(); + for (List points : positionSets) { centroids.add(getCentroid(points)); } @@ -119,9 +121,9 @@ public class SplineBrush implements Brush, ResettableTool { double continuity = 0; double quality = 10; - final List nodes = new ArrayList(centroids.size()); + final List nodes = new ArrayList<>(centroids.size()); - for (final Vector nodevector : centroids) { + for (final Vector3 nodevector : centroids) { final Node n = new Node(nodevector); n.setTension(tension); n.setBias(bias); @@ -130,8 +132,8 @@ public class SplineBrush implements Brush, ResettableTool { } int samples = numSplines; for (int i = 0; i < numSplines; i++) { - List currentSpline = new ArrayList<>(); - for (ArrayList points : positionSets) { + List currentSpline = new ArrayList<>(); + for (ArrayList points : positionSets) { int listSize = points.size(); int index = (int) (i * listSize / (double) (numSplines)); currentSpline.add(points.get(index)); @@ -148,9 +150,9 @@ public class SplineBrush implements Brush, ResettableTool { } } - private Vector getCentroid(Collection points) { - Vector sum = new Vector(); - for (Vector p : points) { + private Vector3 getCentroid(Collection points) { + MutableVector3 sum = new MutableVector3(); + for (BlockVector3 p : points) { sum.mutX(sum.getX() + p.getX()); sum.mutY(sum.getY() + p.getY()); sum.mutZ(sum.getZ() + p.getZ()); @@ -158,7 +160,7 @@ public class SplineBrush implements Brush, ResettableTool { return sum.multiply(1.0 / points.size()); } - private Vector normal(Collection points, Vector centroid) { + private BlockVector3 normal(Collection points, BlockVector3 centroid) { int n = points.size(); switch (n) { case 1: { @@ -177,8 +179,8 @@ public class SplineBrush implements Brush, ResettableTool { double yz = 0.0; double zz = 0.0; - Vector r = new Vector(); - for (Vector p : points) { + MutableVector3 r = new MutableVector3(); + for (BlockVector3 p : points) { r.mutX((p.getX() - centroid.getX())); r.mutY((p.getY() - centroid.getY())); r.mutZ((p.getZ() - centroid.getZ())); @@ -200,19 +202,19 @@ public class SplineBrush implements Brush, ResettableTool { } // Pick path with best conditioning: - Vector dir; + BlockVector3 dir; if (det_max == det_x) { double a = (xz * yz - xy * zz) / det_x; double b = (xy * yz - xz * yy) / det_x; - dir = new Vector(1.0, a, b); + dir = BlockVector3.at(1.0, a, b); } else if (det_max == det_y) { double a = (yz * xz - xy * zz) / det_y; double b = (xy * xz - yz * xx) / det_y; - dir = new Vector(a, 1.0, b); + dir = BlockVector3.at(a, 1.0, b); } else { double a = (yz * xy - xz * yy) / det_z; double b = (xz * xy - yz * xx) / det_z; - dir = new Vector(a, b, 1.0); + dir = BlockVector3.at(a, b, 1.0); } ; return dir.normalize(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/StencilBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/StencilBrush.java index 4383ab878..fbd2b5158 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/StencilBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/StencilBrush.java @@ -3,10 +3,9 @@ package com.boydti.fawe.object.brush; import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.brush.heightmap.HeightMap; import com.boydti.fawe.object.mask.AdjacentAnyMask; +import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.mask.Mask; @@ -15,6 +14,9 @@ import com.sk89q.worldedit.function.mask.SolidBlockMask; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.util.Location; import java.io.InputStream; @@ -29,7 +31,7 @@ public class StencilBrush extends HeightBrush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double sizeDouble) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double sizeDouble) throws MaxChangedBlocksException { final int cx = position.getBlockX(); final int cy = position.getBlockY(); final int cz = position.getBlockZ(); @@ -51,7 +53,7 @@ public class StencilBrush extends HeightBrush { Player player = editSession.getPlayer().getPlayer(); - Vector pos = player.getLocation(); +// BlockVector3 pos = player.getLocation(); @@ -62,17 +64,17 @@ public class StencilBrush extends HeightBrush { RecursiveVisitor visitor = new RecursiveVisitor(new Mask() { - private final MutableBlockVector mutable = new MutableBlockVector(); + private final MutableVector3 mutable = new MutableVector3(); @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { if (solid.test(vector)) { int dx = vector.getBlockX() - cx; int dy = vector.getBlockY() - cy; int dz = vector.getBlockZ() - cz; - Vector srcPos = transform.apply(mutable.setComponents(dx, dy, dz)); - dx = srcPos.getBlockX(); - dz = srcPos.getBlockZ(); + Vector3 srcPos = transform.apply(mutable.setComponents(dx, dy, dz)); + dx = MathMan.roundInt(srcPos.getX()); + dz = MathMan.roundInt(srcPos.getZ()); int distance = dx * dx + dz * dz; if (distance > size2 || Math.abs(dx) > 256 || Math.abs(dz) > 256) return false; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SurfaceSphereBrush.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SurfaceSphereBrush.java index c3fa7544d..194a43672 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SurfaceSphereBrush.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/SurfaceSphereBrush.java @@ -4,18 +4,19 @@ import com.boydti.fawe.object.mask.RadiusMask; import com.boydti.fawe.object.mask.SurfaceMask; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.mask.SolidBlockMask; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.visitor.BreadthFirstSearch; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; +import com.sk89q.worldedit.math.BlockVector3; + import java.util.Arrays; public class SurfaceSphereBrush implements Brush { @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { SurfaceMask surface = new SurfaceMask(editSession); final SolidBlockMask solid = new SolidBlockMask(editSession); final RadiusMask radius = new RadiusMask(0, (int) size); 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 979e29ab0..d3b9eb4d8 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 @@ -7,6 +7,9 @@ import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.*; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.interpolation.KochanekBartelsInterpolation; import com.sk89q.worldedit.math.interpolation.Node; import java.util.ArrayList; @@ -22,17 +25,17 @@ public class SurfaceSpline implements Brush { this.quality = quality; } - private ArrayList path = new ArrayList<>(); + private ArrayList path = new ArrayList<>(); @Override - public void build(EditSession editSession, Vector pos, Pattern pattern, double radius) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 pos, Pattern pattern, double radius) throws MaxChangedBlocksException { int maxY = editSession.getMaxY(); 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; - pos.mutY(max); - path.add(pos); +// pos.mutY(max); + path.add(Vector3.at(pos.getBlockX(), max, pos.getBlockZ())); editSession.getPlayer().sendMessage(BBC.getPrefix() + BBC.BRUSH_SPLINE_PRIMARY_2.s()); if (!vis) return; } @@ -40,7 +43,7 @@ public class SurfaceSpline implements Brush { final List nodes = new ArrayList<>(path.size()); final KochanekBartelsInterpolation interpol = new KochanekBartelsInterpolation(); - for (final Vector nodevector : path) { + for (final Vector3 nodevector : path) { final Node n = new Node(nodevector); n.setTension(tension); n.setBias(bias); @@ -50,14 +53,14 @@ public class SurfaceSpline implements Brush { interpol.setNodes(nodes); final double splinelength = interpol.arcLength(0, 1); for (double loop = 0; loop <= 1; loop += 1D / splinelength / quality) { - final Vector tipv = interpol.getPosition(loop); + final Vector3 tipv = interpol.getPosition(loop); final int tipx = MathMan.roundInt(tipv.getX()); 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 (radius == 0) { - Vector set = MutableBlockVector.get(tipx, tipy, tipz); + BlockVector3 set = MutableBlockVector3.get(tipx, tipy, tipz); try { pattern.apply(editSession, set, set); } catch (WorldEditException e) { @@ -71,7 +74,7 @@ public class SurfaceSpline implements Brush { double radius2 = (radius * radius); LocalBlockVectorSet newSet = new LocalBlockVectorSet(); final int ceilrad = (int) Math.ceil(radius); - for (final Vector v : vset) { + for (final BlockVector3 v : vset) { final int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ(); for (int loopx = tipx - ceilrad; loopx <= (tipx + ceilrad); loopx++) { for (int loopz = tipz - ceilrad; loopz <= (tipz + ceilrad); loopz++) { 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 61c7a1807..0e07d6eb6 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 @@ -4,9 +4,8 @@ import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.util.MainUtil; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.convolution.GaussianKernel; import com.sk89q.worldedit.math.convolution.HeightMapFilter; import com.sk89q.worldedit.regions.CuboidRegion; @@ -19,19 +18,19 @@ public interface HeightMap { public void setSize(int size); - default void perform(EditSession session, Mask mask, Vector pos, int size, int rotationMode, double yscale, boolean smooth, boolean towards, boolean layers) throws MaxChangedBlocksException { + default void perform(EditSession session, Mask mask, BlockVector3 pos, int size, int rotationMode, double yscale, boolean smooth, boolean towards, boolean layers) throws MaxChangedBlocksException { int[][] data = generateHeightData(session, mask, pos, size, rotationMode, yscale, smooth, towards, layers); applyHeightMapData(data, session, mask, pos, size, rotationMode, yscale, smooth, towards, layers); } - default void applyHeightMapData(int[][] data, EditSession session, Mask mask, Vector pos, int size, int rotationMode, double yscale, boolean smooth, boolean towards, boolean layers) throws MaxChangedBlocksException { - Vector top = session.getMaximumPoint(); + default void applyHeightMapData(int[][] data, EditSession session, Mask mask, BlockVector3 pos, int size, int rotationMode, double yscale, boolean smooth, boolean towards, boolean layers) throws MaxChangedBlocksException { + BlockVector3 top = session.getMaximumPoint(); int maxY = top.getBlockY(); int diameter = 2 * size + 1; int iterations = 1; - Location min = new Location(session.getWorld(), pos.subtract(size, maxY, size)); - Vector max = pos.add(size, maxY, size); - Region region = new CuboidRegion(session.getWorld(), min, max); + Location min = new Location(session.getWorld(), pos.subtract(size, maxY, size).toVector3()); + BlockVector3 max = pos.add(size, maxY, size); + Region region = new CuboidRegion(session.getWorld(), min.toBlockPoint(), max); com.sk89q.worldedit.math.convolution.HeightMap heightMap = new com.sk89q.worldedit.math.convolution.HeightMap(session, region, data[0], layers); if (smooth) { try { @@ -52,8 +51,8 @@ public interface HeightMap { } } - default int[][] generateHeightData(EditSession session, Mask mask, Vector pos, int size, final int rotationMode, double yscale, boolean smooth, boolean towards, final boolean layers) { - Vector top = session.getMaximumPoint(); + default int[][] generateHeightData(EditSession session, Mask mask, BlockVector3 pos, int size, final int rotationMode, double yscale, boolean smooth, boolean towards, final boolean layers) { + BlockVector3 top = session.getMaximumPoint(); int maxY = top.getBlockY(); int diameter = 2 * size + 1; int centerX = pos.getBlockX(); @@ -67,14 +66,14 @@ public interface HeightMap { centerY <<= 3; maxY <<= 3; } - Vector mutablePos = new Vector(0, 0, 0); +// Vector mutablePos = new Vector(0, 0, 0); if (towards) { double sizePowInv = 1d / Math.pow(size, yscale); int targetY = pos.getBlockY(); int tmpY = targetY; for (int x = -size; x <= size; x++) { int xx = centerX + x; - mutablePos.mutX(xx); +// mutablePos.mutX(xx); for (int z = -size; z <= size; z++) { int index = (z + size) * diameter + (x + size); int zz = centerZ + z; @@ -118,7 +117,7 @@ public interface HeightMap { int height = pos.getBlockY(); for (int x = -size; x <= size; x++) { int xx = centerX + x; - mutablePos.mutX(xx); +// mutablePos.mutX(xx); for (int z = -size; z <= size; z++) { int index = (z + size) * diameter + (x + size); int zz = centerZ + z; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/RotatableHeightMap.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/RotatableHeightMap.java index d6f1fca69..eff992937 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/RotatableHeightMap.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/RotatableHeightMap.java @@ -1,16 +1,16 @@ package com.boydti.fawe.object.brush.heightmap; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableVector3; import com.sk89q.worldedit.math.transform.AffineTransform; public class RotatableHeightMap extends AbstractDelegateHeightMap { private AffineTransform transform; - private MutableBlockVector mutable; + private MutableVector3 mutable; public RotatableHeightMap(HeightMap parent) { super(parent); - mutable = new MutableBlockVector(); + mutable = new MutableVector3(); this.transform = new AffineTransform(); } @@ -22,7 +22,7 @@ public class RotatableHeightMap extends AbstractDelegateHeightMap { public double getHeight(int x, int z) { mutable.mutX(x); mutable.mutZ(z); - Vector pos = transform.apply(mutable.setComponents(x, 0, z)); + BlockVector3 pos = transform.apply(mutable.setComponents(x, 0, z)).toBlockPoint(); return super.getHeight(pos.getBlockX(), pos.getBlockZ()); } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/ScalableHeightMap.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/ScalableHeightMap.java index cea5fdff5..68c200f8e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/ScalableHeightMap.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/heightmap/ScalableHeightMap.java @@ -3,10 +3,9 @@ package com.boydti.fawe.object.brush.heightmap; import com.boydti.fawe.object.IntegerPair; import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.MathMan; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import java.awt.image.BufferedImage; @@ -60,7 +59,7 @@ public class ScalableHeightMap implements com.boydti.fawe.object.brush.heightmap } public static ScalableHeightMap fromClipboard(Clipboard clipboard) { - Vector dim = clipboard.getDimensions(); + BlockVector3 dim = clipboard.getDimensions(); byte[][] heightArray = new byte[dim.getBlockX()][dim.getBlockZ()]; int minX = clipboard.getMinimumPoint().getBlockX(); int minZ = clipboard.getMinimumPoint().getBlockZ(); @@ -68,7 +67,7 @@ public class ScalableHeightMap implements com.boydti.fawe.object.brush.heightmap int maxY = clipboard.getMaximumPoint().getBlockY(); int clipHeight = maxY - minY + 1; HashSet visited = new HashSet<>(); - for (Vector pos : clipboard.getRegion()) { + for (BlockVector3 pos : clipboard.getRegion()) { IntegerPair pair = new IntegerPair(pos.getBlockX(), pos.getBlockZ()); if (visited.contains(pair)) { continue; @@ -77,9 +76,10 @@ public class ScalableHeightMap implements com.boydti.fawe.object.brush.heightmap int xx = pos.getBlockX(); int zz = pos.getBlockZ(); int highestY = minY; + MutableBlockVector3 bv = new MutableBlockVector3(pos); for (int y = minY; y <= maxY; y++) { - pos.mutY(y); - BlockStateHolder block = clipboard.getBlock(pos); + bv.mutY(y); + BlockStateHolder block = clipboard.getBlock(bv); if (!block.getBlockType().getMaterial().isAir()) { highestY = y + 1; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/ScrollAction.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/ScrollAction.java index 12ebb41dd..8a8677169 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/ScrollAction.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/scroll/ScrollAction.java @@ -10,6 +10,7 @@ import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.pattern.Pattern; import java.io.IOException; @@ -34,7 +35,7 @@ public abstract class ScrollAction implements ScrollTool { } String filename = split[1]; try { - MultiClipboardHolder multi = ClipboardFormat.SCHEMATIC.loadAllFromInput(player, filename, null, message); + MultiClipboardHolder multi = ClipboardFormats.loadAllFromInput(player, filename, null, message); if (multi == null) { return null; } 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 936338999..4dc8120ae 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 @@ -3,11 +3,11 @@ package com.boydti.fawe.object.brush.sweep; import com.boydti.fawe.object.collection.LocalBlockVectorSet; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.interpolation.Interpolation; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.math.transform.RoundedTransform; @@ -24,11 +24,11 @@ public class ClipboardSpline extends Spline { private final Transform transform; private ClipboardHolder clipboardHolder; - private Vector originalOrigin; + private BlockVector3 originalOrigin; private Transform originalTransform; - private Vector center; - private Vector centerOffset; + private BlockVector3 center; + private BlockVector3 centerOffset; private LocalBlockVectorSet buffer; /** @@ -70,8 +70,9 @@ public class ClipboardSpline extends Spline { this.originalOrigin = clipboard.getOrigin(); Region region = clipboard.getRegion(); - Vector origin = clipboard.getOrigin(); - center = region.getCenter().setY(origin.getY() - 1); + BlockVector3 origin = clipboard.getOrigin(); +// 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); this.transform = transform; @@ -79,7 +80,7 @@ public class ClipboardSpline extends Spline { } @Override - protected int pasteBlocks(Vector target, Vector offset, double angle) throws MaxChangedBlocksException { + protected int pasteBlocks(BlockVector3 target, BlockVector3 offset, double angle) throws MaxChangedBlocksException { RoundedTransform transform = new RoundedTransform(new AffineTransform() .translate(offset) .rotateY(angle)); @@ -95,7 +96,7 @@ public class ClipboardSpline extends Spline { clipboard.setOrigin(center.subtract(centerOffset).round()); clipboardHolder.setTransform(transform); - Vector functionOffset = target.subtract(clipboard.getOrigin()); + BlockVector3 functionOffset = target.subtract(clipboard.getOrigin()); final int offX = functionOffset.getBlockX(); final int offY = functionOffset.getBlockY(); final int offZ = functionOffset.getBlockZ(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/Spline.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/Spline.java index e04eb1933..68a3cee85 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/Spline.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/sweep/Spline.java @@ -3,8 +3,10 @@ package com.boydti.fawe.object.brush.sweep; import com.google.common.base.Preconditions; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector2; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.interpolation.Interpolation; import java.util.ArrayList; @@ -19,7 +21,7 @@ import java.util.List; */ public abstract class Spline { - private Vector2D direction = new Vector2D(1, 0); + private BlockVector2 direction = BlockVector2.at(1, 0); private final int nodeCount; protected EditSession editSession; @@ -77,7 +79,7 @@ public abstract class Spline { * The default direction is a (1;0) vector (pointing in the positive x-direction). * @param direction A normalized vector representing the horizontal forward direction of the clipboard content */ - public void setDirection(Vector2D direction) { + public void setDirection(BlockVector2 direction) { this.direction = direction; } @@ -91,7 +93,7 @@ public abstract class Spline { * The default direction is a (1;0) vector (pointing in the positive x-direction). * @return A vector representing the horizontal forward direction of the clipboard content */ - public Vector2D getDirection() { + public BlockVector2 getDirection() { return direction; } @@ -125,14 +127,14 @@ public abstract class Spline { Preconditions.checkArgument(position <= 1); // Calculate position from spline - Vector target = interpolation.getPosition(position); - Vector offset = target.subtract(target.round()); + BlockVector3 target = interpolation.getPosition(position).toBlockPoint(); + BlockVector3 offset = target.subtract(target.round()); target = target.subtract(offset); // Calculate rotation from spline - Vector deriv = interpolation.get1stDerivative(position); - Vector2D deriv2D = new Vector2D(deriv.getX(), deriv.getZ()).normalize(); + Vector3 deriv = interpolation.get1stDerivative(position); + Vector2 deriv2D = Vector2.at(deriv.getX(), deriv.getZ()).normalize(); double angle = Math.toDegrees( Math.atan2(direction.getZ(), direction.getX()) - Math.atan2(deriv2D.getZ(), deriv2D.getX()) ); @@ -140,7 +142,7 @@ public abstract class Spline { return pasteBlocks(target, offset, angle); } - protected abstract int pasteBlocks(Vector target, Vector offset, double angle) throws MaxChangedBlocksException; + protected abstract int pasteBlocks(BlockVector3 target, BlockVector3 offset, double angle) throws MaxChangedBlocksException; private void initSections() { int sectionCount = nodeCount - 1; 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 60063e6a7..707925c5e 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 @@ -9,10 +9,12 @@ import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EmptyClipboardException; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.brush.Brush; 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.Vector3; import com.sk89q.worldedit.math.interpolation.Interpolation; import com.sk89q.worldedit.math.interpolation.KochanekBartelsInterpolation; import com.sk89q.worldedit.math.interpolation.Node; @@ -23,8 +25,8 @@ import java.util.List; import java.util.stream.Collectors; public class SweepBrush implements Brush, ResettableTool { - private List positions; - private Vector position; + private List positions; + private BlockVector3 position; private int copies; private static final double tension = 0D; @@ -37,7 +39,7 @@ public class SweepBrush implements Brush, ResettableTool { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { boolean visualization = editSession.getExtent() instanceof VisualExtent; if (visualization && positions.isEmpty()) { return; @@ -59,7 +61,7 @@ public class SweepBrush implements Brush, ResettableTool { Interpolation interpol = new KochanekBartelsInterpolation(); List nodes = positions.stream().map(v -> { - Node n = new Node(v); + Node n = new Node(v.toVector3()); n.setTension(tension); n.setBias(bias); n.setContinuity(continuity); @@ -74,7 +76,7 @@ public class SweepBrush implements Brush, ResettableTool { } Clipboard clipboard = holder.getClipboard(); - Vector dimensions = clipboard.getDimensions(); + BlockVector3 dimensions = clipboard.getDimensions(); AffineTransform transform = new AffineTransform(); if (dimensions.getBlockX() > dimensions.getBlockZ()) { transform = transform.rotateY(90); @@ -93,10 +95,10 @@ public class SweepBrush implements Brush, ResettableTool { double blockDistance = 1d / splineLength; double step = blockDistance / quality; double accumulation = 0; - Vector last = null; + MutableVector3 last = new MutableVector3(0, 0, 0); for (double pos = 0D; pos <= 1D; pos += step) { - Vector gradient = interpol.get1stDerivative(pos); - if (last == null) last = new Vector(interpol.get1stDerivative(pos)); + Vector3 gradient = interpol.get1stDerivative(pos); + if (last == null) last = new MutableVector3(interpol.get1stDerivative(pos)); double dist = MathMan.sqrtApprox(last.distanceSq(gradient)); last.mutX(gradient.getX()); last.mutY(gradient.getY()); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/ImmutableVirtualWorld.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/ImmutableVirtualWorld.java index 13b12e9cc..6f993c316 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/ImmutableVirtualWorld.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/ImmutableVirtualWorld.java @@ -9,10 +9,12 @@ import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.util.SetQueue; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.world.World; @@ -59,7 +61,7 @@ public abstract class ImmutableVirtualWorld implements VirtualWorld { } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return FaweCache.getBiome(0); } @@ -185,27 +187,27 @@ public abstract class ImmutableVirtualWorld implements VirtualWorld { } @Override - public boolean setBlock(Vector position, BlockStateHolder block, boolean notifyAndLight) throws WorldEditException { + public boolean setBlock(BlockVector3 position, BlockStateHolder block, boolean notifyAndLight) throws WorldEditException { return setBlock(position, block); } @Override - public int getBlockLightLevel(Vector position) { + public int getBlockLightLevel(BlockVector3 position) { return 0; } @Override - public boolean clearContainerBlockContents(Vector position) { + public boolean clearContainerBlockContents(BlockVector3 position) { return unsupported(); } @Override - public void dropItem(Vector position, BaseItemStack item) { + public void dropItem(Vector3 position, BaseItemStack item) { unsupported(); } @Override - public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, Vector position) throws MaxChangedBlocksException { + public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) throws MaxChangedBlocksException { return unsupported(); } @@ -264,12 +266,12 @@ public abstract class ImmutableVirtualWorld implements VirtualWorld { } @Override - public boolean setBlock(Vector pt, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 pt, BlockStateHolder block) throws WorldEditException { return unsupported(); } @Override - public void simulateBlockMine(Vector position) { + public void simulateBlockMine(BlockVector3 position) { unsupported(); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VirtualWorld.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VirtualWorld.java index 53282be2a..4eb958fcb 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VirtualWorld.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VirtualWorld.java @@ -3,12 +3,14 @@ package com.boydti.fawe.object.brush.visualization; import com.boydti.fawe.object.FaweChunk; import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FaweQueue; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.platform.BlockInteractEvent; import com.sk89q.worldedit.event.platform.PlayerInputEvent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.world.SimpleWorld; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -16,28 +18,28 @@ import java.io.Closeable; import java.io.IOException; public interface VirtualWorld extends SimpleWorld, FaweQueue, Closeable { - Vector getOrigin(); + Vector3 getOrigin(); FaweChunk getSnapshot(int chunkX, int chunkZ); @Override - default BlockState getFullBlock(Vector position) { - return getLazyBlock(position); + default BaseBlock getFullBlock(BlockVector3 position) { + return getLazyBlock(position).toBaseBlock(); } @Override int getMaxY(); @Override - boolean setBlock(Vector pt, BlockStateHolder block) throws WorldEditException; + boolean setBlock(BlockVector3 pt, BlockStateHolder block) throws WorldEditException; @Override - default Vector getMaximumPoint() { + default BlockVector3 getMaximumPoint() { return FaweQueue.super.getMaximumPoint(); } @Override - default Vector getMinimumPoint() { + default BlockVector3 getMinimumPoint() { return FaweQueue.super.getMinimumPoint(); } @@ -52,7 +54,7 @@ public interface VirtualWorld extends SimpleWorld, FaweQueue, Closeable { void close(boolean update) throws IOException; - default void handleBlockInteract(Player player, Vector pos, BlockInteractEvent event) {} + default void handleBlockInteract(Player player, BlockVector3 pos, BlockInteractEvent event) {} default void handlePlayerInput(Player player, PlayerInputEvent event) {} } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualChunk.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualChunk.java index 4a6a8155d..3ab6dac36 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualChunk.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualChunk.java @@ -115,17 +115,12 @@ public class VisualChunk extends FaweChunk { public void setBlock(int x, int y, int z, int combinedId) { int index = getIndex(x, y, z); try { - switch (BlockTypes.getFromStateId(combinedId)) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - add.clear(index); - remove.set(index); - break; - default: - remove.clear(index); - add.set(index); - break; + if (BlockTypes.getFromStateId(combinedId).getMaterial().isAir()) { + add.clear(index); + remove.set(index); + } else { + remove.clear(index); + add.set(index); } } catch (Throwable e) { e.printStackTrace(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualExtent.java index c3c260366..b6bc008ff 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/visualization/VisualExtent.java @@ -7,13 +7,12 @@ import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.visitor.FaweChunkVisitor; import com.boydti.fawe.util.MathMan; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; @@ -31,7 +30,7 @@ public class VisualExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 location, BlockStateHolder block) throws WorldEditException { return setBlock(location.getBlockX(), location.getBlockY(), location.getBlockZ(), block); } @@ -62,7 +61,7 @@ public class VisualExtent extends AbstractDelegateExtent { } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { // Do nothing return false; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/change/MutableBiomeChange.java b/worldedit-core/src/main/java/com/boydti/fawe/object/change/MutableBiomeChange.java index 9aaef3ed4..f2a0cde4e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/change/MutableBiomeChange.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/change/MutableBiomeChange.java @@ -1,14 +1,14 @@ package com.boydti.fawe.object.change; -import com.sk89q.worldedit.MutableBlockVector2D; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.history.UndoContext; import com.sk89q.worldedit.history.change.Change; +import com.sk89q.worldedit.math.MutableBlockVector2; import com.sk89q.worldedit.world.biome.BaseBiome; public class MutableBiomeChange implements Change { - private MutableBlockVector2D mutable = new MutableBlockVector2D(); + private MutableBlockVector2 mutable = new MutableBlockVector2(); private BaseBiome from; private BaseBiome to; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/change/MutableFullBlockChange.java b/worldedit-core/src/main/java/com/boydti/fawe/object/change/MutableFullBlockChange.java index a74cec6fe..504af840a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/change/MutableFullBlockChange.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/change/MutableFullBlockChange.java @@ -11,6 +11,7 @@ import com.sk89q.worldedit.extent.inventory.BlockBagException; import com.sk89q.worldedit.history.UndoContext; import com.sk89q.worldedit.history.change.Change; import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; public class MutableFullBlockChange implements Change { @@ -60,9 +61,9 @@ public class MutableFullBlockChange implements Change { } public void perform(FaweQueue queue) { - BlockTypes idFrom = BlockTypes.getFromStateId(from); + BlockType idFrom = BlockTypes.getFromStateId(from); if (blockBag != null) { - BlockTypes idTo = BlockTypes.getFromStateId(to); + BlockType idTo = BlockTypes.getFromStateId(to); if (idFrom != idTo) { if (allowFetch && from != 0) { try { 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 f8b656eda..da005d865 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 @@ -4,14 +4,14 @@ import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FaweQueue; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.history.change.BlockChange; import com.sk89q.worldedit.history.change.Change; import com.sk89q.worldedit.history.change.EntityCreate; import com.sk89q.worldedit.history.change.EntityRemove; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -154,12 +154,12 @@ public class AbstractDelegateChangeSet extends FaweChangeSet { } @Override - public void add(Vector loc, BlockStateHolder from, BlockStateHolder to) { + public void add(BlockVector3 loc, BaseBlock from, BaseBlock to) { parent.add(loc, from, to); } @Override - public void add(int x, int y, int z, BlockStateHolder from, BlockStateHolder to) { + public void add(int x, int y, int z, BaseBlock from, BaseBlock to) { parent.add(x, y, z, from, to); } @@ -172,4 +172,16 @@ public class AbstractDelegateChangeSet extends FaweChangeSet { public void add(int x, int y, int z, int combinedFrom, BaseBlock to) { parent.add(x, y, z, combinedFrom, to); } + + @Override + public boolean isRecordingChanges() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void setRecordChanges(boolean recordChanges) { + // TODO Auto-generated method stub + + } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AnvilHistory.java b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AnvilHistory.java index 9391df381..59d05127f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AnvilHistory.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/AnvilHistory.java @@ -102,4 +102,16 @@ public class AnvilHistory extends FaweChangeSet implements IAnvilHistory { public int size() { return size == -1 ? folder.listFiles().length : size; } + + @Override + public boolean isRecordingChanges() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void setRecordChanges(boolean recordChanges) { + // TODO Auto-generated method stub + + } } 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 3a8665303..4e742229b 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 @@ -5,11 +5,11 @@ import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.util.ReflectionUtils; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.BlockBagException; import com.sk89q.worldedit.extent.inventory.UnplaceableBlockException; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; @@ -71,7 +71,7 @@ public class BlockBagChangeSet extends AbstractDelegateChangeSet { } @Override - public void add(Vector loc, BlockStateHolder from, BlockStateHolder to) { + public void add(BlockVector3 loc, BaseBlock from, BaseBlock to) { int x = loc.getBlockX(); int y = loc.getBlockY(); int z = loc.getBlockZ(); @@ -79,7 +79,7 @@ public class BlockBagChangeSet extends AbstractDelegateChangeSet { } @Override - public void add(int x, int y, int z, BlockStateHolder from, BlockStateHolder to) { + public void add(int x, int y, int z, BaseBlock from, BaseBlock to) { check(from.getBlockType(), to.getBlockType()); super.add(x, y, z, from, to); } 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 de448e6ed..ad9deebc2 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 @@ -78,4 +78,16 @@ public class CFIChangeSet extends FaweChangeSet { public int size() { return 1; } + + @Override + public boolean isRecordingChanges() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void setRecordChanges(boolean recordChanges) { + // TODO Auto-generated method stub + + } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/CPUOptimizedChangeSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/CPUOptimizedChangeSet.java index f0b32d627..3b293c0ea 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/CPUOptimizedChangeSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/CPUOptimizedChangeSet.java @@ -107,4 +107,16 @@ public class CPUOptimizedChangeSet extends FaweChangeSet { public int size() { return changes.size() * 65536; // num chunks * 65536 (guess of 65536 changes per chunk) } + + @Override + public boolean isRecordingChanges() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void setRecordChanges(boolean recordChanges) { + // TODO Auto-generated method stub + + } } 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 9ad52aec6..742aeb3be 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 @@ -491,7 +491,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet { public Map getPercents() { Map map = getBlocks(); int count = getSize(); - Int2ObjectOpenHashMap newMap = new Int2ObjectOpenHashMap(); + Int2ObjectOpenHashMap newMap = new Int2ObjectOpenHashMap<>(); for (Map.Entry entry : map.entrySet()) { int id = entry.getKey(); int changes = entry.getValue(); @@ -509,4 +509,16 @@ public class DiskStorageHistory extends FaweStreamChangeSet { return count; } } + + @Override + public boolean isRecordingChanges() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void setRecordChanges(boolean recordChanges) { + // TODO Auto-generated method stub + + } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweChangeSet.java b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweChangeSet.java index 1d2fe1afb..680b5f424 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweChangeSet.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/changeset/FaweChangeSet.java @@ -13,10 +13,8 @@ import com.boydti.fawe.util.EditSessionBuilder; import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.TaskManager; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.history.change.BlockChange; @@ -24,6 +22,7 @@ import com.sk89q.worldedit.history.change.Change; import com.sk89q.worldedit.history.change.EntityCreate; import com.sk89q.worldedit.history.change.EntityRemove; import com.sk89q.worldedit.history.changeset.ChangeSet; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BaseBiome; @@ -197,23 +196,23 @@ public abstract class FaweChangeSet implements ChangeSet { public void add(BlockChange change) { try { - BlockVector loc = change.getPosition(); - BlockStateHolder from = change.getPrevious(); - BlockStateHolder to = change.getCurrent(); + BlockVector3 loc = change.getPosition(); + BaseBlock from = change.getPrevious(); + BaseBlock to = change.getCurrent(); add(loc, from, to); } catch (Exception e) { MainUtil.handleError(e); } } - public void add(Vector loc, BlockStateHolder from, BlockStateHolder to) { + public void add(BlockVector3 loc, BaseBlock from, BaseBlock to) { int x = loc.getBlockX(); int y = loc.getBlockY(); int z = loc.getBlockZ(); add(x, y, z, from, to); } - public void add(int x, int y, int z, BlockStateHolder from, BlockStateHolder to) { + public void add(int x, int y, int z, BaseBlock from, BaseBlock to) { try { if (from.hasNbtData()) { CompoundTag nbt = from.getNbtData(); 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 2c530b064..f2f44f93a 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 @@ -238,4 +238,16 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet { public NBTInputStream getTileRemoveIS() throws IOException { return tileR == null ? null : new NBTInputStream(MainUtil.getCompressedIS(new FastByteArraysInputStream(tileR))); } + + @Override + public boolean isRecordingChanges() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void setRecordChanges(boolean recordChanges) { + // TODO Auto-generated method stub + + } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/AbstractDelegateFaweClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/AbstractDelegateFaweClipboard.java index 7ff4bb52c..4f39d2b66 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/AbstractDelegateFaweClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/AbstractDelegateFaweClipboard.java @@ -2,12 +2,12 @@ package com.boydti.fawe.object.clipboard; import com.boydti.fawe.jnbt.NBTStreamer; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -22,17 +22,17 @@ public class AbstractDelegateFaweClipboard extends FaweClipboard { } @Override - public BlockState getBlock(int x, int y, int z) { + public BaseBlock getBlock(int x, int y, int z) { return parent.getBlock(x, y, z); } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) { + public > boolean setBlock(int x, int y, int z, B block) { return parent.setBlock(x, y, z, block); } @Override - public boolean setBlock(int index, BlockStateHolder block) { + public > boolean setBlock(int index, B block) { return parent.setBlock(index, block); } @@ -57,7 +57,7 @@ public class AbstractDelegateFaweClipboard extends FaweClipboard { } @Override - public BlockState getBlock(int index) { + public BaseBlock getBlock(int index) { return parent.getBlock(index); } @@ -87,12 +87,12 @@ public class AbstractDelegateFaweClipboard extends FaweClipboard { } @Override - public void setOrigin(Vector offset) { + public void setOrigin(BlockVector3 offset) { parent.setOrigin(offset); } @Override - public void setDimensions(Vector dimensions) { + public void setDimensions(BlockVector3 dimensions) { parent.setDimensions(dimensions); } @@ -107,7 +107,7 @@ public class AbstractDelegateFaweClipboard extends FaweClipboard { } @Override - public Vector getDimensions() { + public BlockVector3 getDimensions() { return parent.getDimensions(); } 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 e9934cc73..fe51280d7 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 @@ -8,15 +8,16 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.IntTag; import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import java.util.ArrayList; @@ -112,7 +113,7 @@ public class CPUOptimizedClipboard extends FaweClipboard { } @Override - public void setDimensions(Vector dimensions) { + public void setDimensions(BlockVector3 dimensions) { width = dimensions.getBlockX(); height = dimensions.getBlockY(); length = dimensions.getBlockZ(); @@ -125,8 +126,8 @@ public class CPUOptimizedClipboard extends FaweClipboard { } @Override - public Vector getDimensions() { - return new Vector(width, height, length); + public BlockVector3 getDimensions() { + return BlockVector3.at(width, height, length); } private int ylast; @@ -139,23 +140,23 @@ public class CPUOptimizedClipboard extends FaweClipboard { } @Override - public BlockState getBlock(int x, int y, int z) { + public BaseBlock getBlock(int x, int y, int z) { int index = getIndex(x, y, z); return getBlock(index); } @Override - public BlockState getBlock(int index) { + public BaseBlock getBlock(int index) { int combinedId = states[index]; - BlockTypes type = BlockTypes.getFromStateId(combinedId); - BlockState state = type.withStateId(combinedId); + BlockType type = BlockTypes.getFromStateId(combinedId); + BaseBlock base = type.withStateId(combinedId).toBaseBlock(); if (type.getMaterial().hasContainer()) { CompoundTag nbt = getTag(index); if (nbt != null) { - return new BaseBlock(state, nbt); + return base.toBaseBlock(nbt); } } - return state; + return base; } @Override @@ -164,7 +165,7 @@ public class CPUOptimizedClipboard extends FaweClipboard { for (int y = 0, index = 0; y < height; y++) { for (int z = 0; z < length; z++) { for (int x = 0; x < width; x++, index++) { - BlockState block = getBlock(index); + BaseBlock block = getBlock(index); task.run(x, y, z, block); } } @@ -173,14 +174,9 @@ public class CPUOptimizedClipboard extends FaweClipboard { for (int y = 0, index = 0; y < height; y++) { for (int z = 0; z < length; z++) { for (int x = 0; x < width; x++, index++) { - BlockState block = getBlock(index); - switch (block.getBlockType()) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - continue; - default: - task.run(x, y, z, block); + BaseBlock block = getBlock(index); + if (!block.getMaterial().isAir()) { + task.run(x, y, z, block); } } } @@ -236,16 +232,16 @@ public class CPUOptimizedClipboard extends FaweClipboard { } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) { + public > boolean setBlock(int x, int y, int z, B block) { return setBlock(getIndex(x, y, z), block); } @Override - public boolean setBlock(int index, BlockStateHolder block) { + public > boolean setBlock(int index, B block) { states[index] = block.getInternalId(); - CompoundTag tile = block.getNbtData(); - if (tile != null) { - setTile(index, tile); + boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); + if (hasNbt) { + setTile(index, ((BaseBlock)block).getNbtData()); } return true; } 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 b74b0e977..ca74f0ab9 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 @@ -11,16 +11,17 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.IntTag; import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import java.io.Closeable; @@ -166,18 +167,18 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { } @Override - public Vector getDimensions() { - return new Vector(width, height, length); + public BlockVector3 getDimensions() { + return BlockVector3.at(width, height, length); } public BlockArrayClipboard toClipboard() { try { - CuboidRegion region = new CuboidRegion(new Vector(0, 0, 0), new Vector(width - 1, height - 1, length - 1)); + CuboidRegion region = new CuboidRegion(BlockVector3.at(0, 0, 0), BlockVector3.at(width - 1, height - 1, length - 1)); int ox = mbb.getShort(8); int oy = mbb.getShort(10); int oz = mbb.getShort(12); BlockArrayClipboard clipboard = new BlockArrayClipboard(region, this); - clipboard.setOrigin(new Vector(ox, oy, oz)); + clipboard.setOrigin(BlockVector3.at(ox, oy, oz)); return clipboard; } catch (Throwable e) { MainUtil.handleError(e); @@ -223,7 +224,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { } @Override - public void setOrigin(Vector offset) { + public void setOrigin(BlockVector3 offset) { try { mbb.putShort(8, (short) offset.getBlockX()); mbb.putShort(10, (short) offset.getBlockY()); @@ -234,7 +235,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { } @Override - public void setDimensions(Vector dimensions) { + public void setDimensions(BlockVector3 dimensions) { try { width = dimensions.getBlockX(); height = dimensions.getBlockY(); @@ -371,7 +372,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { for (int z = 0; z < length; z++) { for (int x = 0; x < width; x++, pos += 4) { int combinedId = mbb.getInt(pos); - BlockTypes type = BlockTypes.getFromStateId(combinedId); + BlockType type = BlockTypes.getFromStateId(combinedId); BlockState state = type.withStateId(combinedId); if (type.getMaterial().hasContainer()) { trio.set(x, y, z); @@ -402,24 +403,19 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { for (int z = 0; z < length; z++) { for (int x = 0; x < width; x++, pos += 4) { int combinedId = mbb.getInt(pos); - BlockTypes type = BlockTypes.getFromStateId(combinedId); - switch (type) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - continue; - default: - BlockState state = type.withStateId(combinedId); - if (type.getMaterial().hasContainer()) { - trio.set(x, y, z); - CompoundTag nbt = nbtMap.get(trio); - if (nbt != null) { - BaseBlock block = new BaseBlock(state, nbt); - task.run(x, y, z, block); - continue; - } + BlockType type = BlockTypes.getFromStateId(combinedId); + if (!type.getMaterial().isAir()) { + BlockState state = type.withStateId(combinedId); + if (type.getMaterial().hasContainer()) { + trio.set(x, y, z); + CompoundTag nbt = nbtMap.get(trio); + if (nbt != null) { + BaseBlock block = new BaseBlock(state, nbt); + task.run(x, y, z, block); + continue; } - task.run(x, y, z, state); + } + task.run(x, y, z, state); } } } @@ -432,34 +428,34 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { } @Override - public BlockState getBlock(int x, int y, int z) { + public BaseBlock getBlock(int x, int y, int z) { try { int index = HEADER_SIZE + (getIndex(x, y, z) << 2); int combinedId = mbb.getInt(index); - BlockTypes type = BlockTypes.getFromStateId(combinedId); - BlockState state = type.withStateId(combinedId); + BlockType type = BlockTypes.getFromStateId(combinedId); + BaseBlock base = type.withStateId(combinedId).toBaseBlock(); if (type.getMaterial().hasContainer() && !nbtMap.isEmpty()) { CompoundTag nbt = nbtMap.get(new IntegerTrio(x, y, z)); if (nbt != null) { - return new BaseBlock(state, nbt); + return base.toBaseBlock(nbt); } } - return state; + return base; } catch (IndexOutOfBoundsException ignore) { } catch (Exception e) { e.printStackTrace(); MainUtil.handleError(e); } - return EditSession.nullBlock; + return EditSession.nullBlock.toBaseBlock(); } @Override - public BlockState getBlock(int i) { + public BaseBlock getBlock(int i) { try { int diskIndex = (HEADER_SIZE) + (i << 2); int combinedId = mbb.getInt(diskIndex); - BlockTypes type = BlockTypes.getFromStateId(combinedId); - BlockState state = type.withStateId(combinedId); + BlockType type = BlockTypes.getFromStateId(combinedId); + BaseBlock base = type.withStateId(combinedId).toBaseBlock(); if (type.getMaterial().hasContainer() && !nbtMap.isEmpty()) { CompoundTag nbt; if (nbtMap.size() < 4) { @@ -481,15 +477,15 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { nbt = nbtMap.get(new IntegerTrio(x, y, z)); } if (nbt != null) { - return new BaseBlock(state, nbt); + return base.toBaseBlock(nbt); } } - return state; + return base; } catch (IndexOutOfBoundsException ignore) { } catch (Exception e) { MainUtil.handleError(e); } - return EditSession.nullBlock; + return EditSession.nullBlock.toBaseBlock(); } @Override @@ -503,14 +499,14 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) { + public > boolean setBlock(int x, int y, int z, B block) { try { int index = (HEADER_SIZE) + ((getIndex(x, y, z) << 2)); int combined = block.getInternalId(); mbb.putInt(index, combined); - CompoundTag tile = block.getNbtData(); - if (tile != null) { - setTile(x, y, z, tile); + boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); + if (hasNbt) { + setTile(x, y, z, ((BaseBlock)block).getNbtData()); } return true; } catch (Exception e) { @@ -520,18 +516,18 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable { } @Override - public boolean setBlock(int i, BlockStateHolder block) { + public > boolean setBlock(int i, B block) { try { int combined = block.getInternalId(); int index = (HEADER_SIZE) + (i << 2); mbb.putInt(index, combined); - CompoundTag tile = block.getNbtData(); - if (tile != null) { + boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); + if (hasNbt) { int y = i / area; int newI = (i - (y * area)); int z = newI / width; int x = newI - z * width; - setTile(x, y, z, tile); + setTile(x, y, z, ((BaseBlock)block).getNbtData()); } return true; } catch (Exception e) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/EmptyClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/EmptyClipboard.java index 1ea6bc0ff..c77892562 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/EmptyClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/EmptyClipboard.java @@ -1,15 +1,15 @@ package com.boydti.fawe.object.clipboard; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; @@ -30,31 +30,31 @@ public class EmptyClipboard implements Clipboard { @Override public Region getRegion() { - return new CuboidRegion(Vector.ZERO, Vector.ZERO); + return new CuboidRegion(BlockVector3.ZERO, BlockVector3.ZERO); } @Override - public Vector getDimensions() { - return Vector.ZERO; + public BlockVector3 getDimensions() { + return BlockVector3.ZERO; } @Override - public Vector getOrigin() { - return Vector.ZERO; + public BlockVector3 getOrigin() { + return BlockVector3.ZERO; } @Override - public void setOrigin(Vector origin) { + public void setOrigin(BlockVector3 origin) { } @Override - public Vector getMinimumPoint() { - return Vector.ZERO; + public BlockVector3 getMinimumPoint() { + return BlockVector3.ZERO; } @Override - public Vector getMaximumPoint() { - return Vector.ZERO; + public BlockVector3 getMaximumPoint() { + return BlockVector3.ZERO; } @Override @@ -74,27 +74,27 @@ public class EmptyClipboard implements Clipboard { } @Override - public BlockState getFullBlock(Vector position) { + public BaseBlock getFullBlock(BlockVector3 position) { + return EditSession.nullBlock.toBaseBlock(); + } + + @Override + public BlockState getLazyBlock(BlockVector3 position) { return EditSession.nullBlock; } @Override - public BlockState getLazyBlock(Vector position) { - return EditSession.nullBlock; - } - - @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return EditSession.nullBiome; } @Override - public boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 position, BlockStateHolder block) throws WorldEditException { return false; } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return false; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/FaweClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/FaweClipboard.java index c5431a081..bcf3fe4e2 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/FaweClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/FaweClipboard.java @@ -5,12 +5,12 @@ import com.boydti.fawe.util.ReflectionUtils; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.IntTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockState; @@ -25,11 +25,11 @@ import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; public abstract class FaweClipboard { - public abstract BlockState getBlock(int x, int y, int z); + public abstract BaseBlock getBlock(int x, int y, int z); - public abstract boolean setBlock(int index, BlockStateHolder block); + public abstract > boolean setBlock(int index, B block); - public abstract boolean setBlock(int x, int y, int z, BlockStateHolder block); + public abstract > boolean setBlock(int x, int y, int z, B block); public abstract boolean hasBiomes(); @@ -39,7 +39,7 @@ public abstract class FaweClipboard { public abstract BaseBiome getBiome(int index); - public abstract BlockState getBlock(int index); + public abstract BaseBlock getBlock(int index); public abstract void setBiome(int index, int biome); @@ -51,12 +51,12 @@ public abstract class FaweClipboard { public abstract boolean remove(ClipboardEntity clipboardEntity); - public void setOrigin(Vector offset) { + public void setOrigin(BlockVector3 offset) { } // Do nothing - public abstract void setDimensions(Vector dimensions); + public abstract void setDimensions(BlockVector3 dimensions); - public abstract Vector getDimensions(); + public abstract BlockVector3 getDimensions(); /** * The locations provided are relative to the clipboard min @@ -67,7 +67,7 @@ public abstract class FaweClipboard { public abstract void forEach(BlockReader task, boolean air); public static abstract class BlockReader { - public abstract void run(int x, int y, int z, BlockState block); + public abstract > void run(int x, int y, int z, B block); } public abstract void streamBiomes(final NBTStreamer.ByteReader task); @@ -77,7 +77,7 @@ public abstract class FaweClipboard { private int index = 0; @Override - public void run(int x, int y, int z, BlockState block) { + public > void run(int x, int y, int z, B block) { task.run(index++, block.getInternalId()); } }, true); @@ -89,8 +89,10 @@ public abstract class FaweClipboard { private int index = 0; @Override - public void run(int x, int y, int z, BlockState block) { - CompoundTag tag = block.getNbtData(); + public > void run(int x, int y, int z, B block) { + if(!(block instanceof BaseBlock)) return; + BaseBlock base = (BaseBlock)block; + CompoundTag tag = base.getNbtData(); if (tag != null) { Map values = ReflectionUtils.getMap(tag.getValue()); values.put("x", new IntTag(x)); @@ -162,5 +164,11 @@ public abstract class FaweClipboard { public Extent getExtent() { return world; } + + @Override + public boolean setLocation(Location location) { + //Should not be teleporting this entity + return false; + } } } 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 ba81a3b07..4b44692a8 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 @@ -10,14 +10,15 @@ import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.IntTag; import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import net.jpountz.util.SafeUtils; @@ -159,7 +160,7 @@ public class MemoryOptimizedClipboard extends FaweClipboard { } @Override - public void setDimensions(Vector dimensions) { + public void setDimensions(BlockVector3 dimensions) { width = dimensions.getBlockX(); height = dimensions.getBlockY(); length = dimensions.getBlockZ(); @@ -174,8 +175,8 @@ public class MemoryOptimizedClipboard extends FaweClipboard { } @Override - public Vector getDimensions() { - return new Vector(width, height, length); + public BlockVector3 getDimensions() { + return BlockVector3.at(width, height, length); } private int lastI; @@ -203,11 +204,9 @@ public class MemoryOptimizedClipboard extends FaweClipboard { } } if (lastCombinedIds == null) { - switch (BlockTypes.getFromStateId(v)) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - return; + BlockType bt = BlockTypes.getFromStateId(v); + if (bt.getMaterial().isAir()) { + return; } lastCombinedIds = new byte[BLOCK_SIZE]; } @@ -262,23 +261,23 @@ public class MemoryOptimizedClipboard extends FaweClipboard { } @Override - public BlockState getBlock(int x, int y, int z) { + public BaseBlock getBlock(int x, int y, int z) { int index = getIndex(x, y, z); return getBlock(index); } @Override - public BlockState getBlock(int index) { + public BaseBlock getBlock(int index) { int combinedId = getCombinedId(index); - BlockTypes type = BlockTypes.getFromStateId(combinedId); - BlockState state = type.withStateId(combinedId); + BlockType type = BlockTypes.getFromStateId(combinedId); + BaseBlock base = type.withStateId(combinedId).toBaseBlock(); if (type.getMaterial().hasContainer()) { CompoundTag nbt = getTag(index); if (nbt != null) { - return new BaseBlock(state, nbt); + return base.toBaseBlock(nbt); } } - return state; + return base; } @Override @@ -287,7 +286,7 @@ public class MemoryOptimizedClipboard extends FaweClipboard { for (int y = 0, index = 0; y < height; y++) { for (int z = 0; z < length; z++) { for (int x = 0; x < width; x++, index++) { - BlockState block = getBlock(index); + BaseBlock block = getBlock(index); task.run(x, y, z, block); } } @@ -296,14 +295,9 @@ public class MemoryOptimizedClipboard extends FaweClipboard { for (int y = 0, index = 0; y < height; y++) { for (int z = 0; z < length; z++) { for (int x = 0; x < width; x++, index++) { - BlockState block = getBlock(index); - switch (block.getBlockType()) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - continue; - default: - task.run(x, y, z, block); + BaseBlock block = getBlock(index); + if (!block.getMaterial().isAir()) { + task.run(x, y, z, block); } } } @@ -338,17 +332,17 @@ public class MemoryOptimizedClipboard extends FaweClipboard { } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) { + public > boolean setBlock(int x, int y, int z, B block) { return setBlock(getIndex(x, y, z), block); } @Override - public boolean setBlock(int index, BlockStateHolder block) { + public > boolean setBlock(int index, B block) { int combinedId = block.getInternalId(); setCombinedId(index, combinedId); - CompoundTag tile = block.getNbtData(); - if (tile != null) { - setTile(index, tile); + boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); + if (hasNbt) { + setTile(index, ((BaseBlock)block).getNbtData()); } return true; } 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 891c22f41..1238f3f91 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 @@ -1,11 +1,11 @@ package com.boydti.fawe.object.clipboard; -import com.boydti.fawe.object.PseudoRandom; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.session.ClipboardHolder; import java.net.URI; import java.util.*; +import java.util.concurrent.ThreadLocalRandom; import static com.google.common.base.Preconditions.checkNotNull; @@ -144,7 +144,7 @@ public class MultiClipboardHolder extends URIClipboardHolder { case 1: return available[0]; } - int index = PseudoRandom.random.nextInt(available.length); + int index = ThreadLocalRandom.current().nextInt(available.length); return available[index]; } @@ -167,4 +167,4 @@ public class MultiClipboardHolder extends URIClipboardHolder { holder.close(); } } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/OffsetFaweClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/OffsetFaweClipboard.java index abdaf65c1..e349e0991 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/OffsetFaweClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/OffsetFaweClipboard.java @@ -2,6 +2,7 @@ package com.boydti.fawe.object.clipboard; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -20,12 +21,12 @@ public class OffsetFaweClipboard extends AbstractDelegateFaweClipboard { } @Override - public BlockState getBlock(int x, int y, int z) { + public BaseBlock getBlock(int x, int y, int z) { return super.getBlock(x + ox, y + oy, z + oz); } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) { + public > boolean setBlock(int x, int y, int z, B block) { return super.setBlock(ox + x, oy + y, oz + z, block); } @@ -48,7 +49,7 @@ public class OffsetFaweClipboard extends AbstractDelegateFaweClipboard { public void forEach(final BlockReader task, boolean air) { super.forEach(new BlockReader() { @Override - public void run(int x, int y, int z, BlockState block) { + public > void run(int x, int y, int z, B block) { task.run(x - ox, y - oy, z - oz, block); } }, air); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ReadOnlyClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ReadOnlyClipboard.java index 7792c9652..8b5b85a47 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ReadOnlyClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ReadOnlyClipboard.java @@ -3,12 +3,12 @@ package com.boydti.fawe.object.clipboard; import com.boydti.fawe.jnbt.NBTStreamer; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockState; @@ -36,17 +36,17 @@ public abstract class ReadOnlyClipboard extends FaweClipboard { } @Override - public Vector getDimensions() { + public BlockVector3 getDimensions() { return region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); } @Override - public void setDimensions(Vector dimensions) { + public void setDimensions(BlockVector3 dimensions) { throw new UnsupportedOperationException("Clipboard is immutable"); } @Override - public BlockState getBlock(int index) { + public BaseBlock getBlock(int index) { throw new UnsupportedOperationException("World based clipboards do not provide index access"); } @@ -67,7 +67,7 @@ public abstract class ReadOnlyClipboard extends FaweClipboard { @Override public void streamBiomes(NBTStreamer.ByteReader task) { - Vector dim = getDimensions(); + BlockVector3 dim = getDimensions(); int index = 0; for (int z = 0; z <= dim.getBlockZ(); z++) { for (int x = 0; x <= dim.getBlockX(); x++, index++) { @@ -77,7 +77,7 @@ public abstract class ReadOnlyClipboard extends FaweClipboard { } @Override - public abstract BlockState getBlock(int x, int y, int z); + public abstract BaseBlock getBlock(int x, int y, int z); @Override public abstract BaseBiome getBiome(int x, int z); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ResizableClipboardBuilder.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ResizableClipboardBuilder.java index f50625963..6c7dfa4fc 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ResizableClipboardBuilder.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/ResizableClipboardBuilder.java @@ -3,12 +3,12 @@ package com.boydti.fawe.object.clipboard; import com.boydti.fawe.object.change.MutableBlockChange; import com.boydti.fawe.object.change.MutableTileChange; import com.boydti.fawe.object.changeset.MemoryOptimizedHistory; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.history.change.Change; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -60,8 +60,8 @@ public class ResizableClipboardBuilder extends MemoryOptimizedHistory { } public Clipboard build() { - Vector pos1 = new Vector(minX, minY, minZ); - Vector pos2 = new Vector(maxX, maxY, maxZ); + BlockVector3 pos1 = BlockVector3.at(minX, minY, minZ); + BlockVector3 pos2 = BlockVector3.at(maxX, maxY, maxZ); CuboidRegion region = new CuboidRegion(pos1, pos2); BlockArrayClipboard clipboard = new BlockArrayClipboard(region); Iterator iter = getIterator(true); 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 1c30b0f60..43a59a2e6 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 @@ -1,19 +1,19 @@ package com.boydti.fawe.object.clipboard; import com.boydti.fawe.util.ReflectionUtils; -import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.IntTag; import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.MutableBlockVector2D; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.visitor.RegionVisitor; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector2; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.biome.BaseBiome; @@ -27,7 +27,7 @@ public class WorldCopyClipboard extends ReadOnlyClipboard { public final int mx, my, mz; private final boolean hasBiomes; private final boolean hasEntities; - private MutableBlockVector2D mutableBlockVector2D = new MutableBlockVector2D(); + private MutableBlockVector2 MutableBlockVector2 = new MutableBlockVector2(); public final Extent extent; public WorldCopyClipboard(Extent editSession, Region region) { @@ -38,7 +38,7 @@ public class WorldCopyClipboard extends ReadOnlyClipboard { super(region); this.hasBiomes = hasBiomes; this.hasEntities = hasEntities; - final Vector origin = region.getMinimumPoint(); + final BlockVector3 origin = region.getMinimumPoint(); this.mx = origin.getBlockX(); this.my = origin.getBlockY(); this.mz = origin.getBlockZ(); @@ -46,17 +46,17 @@ public class WorldCopyClipboard extends ReadOnlyClipboard { } @Override - public BlockState getBlock(int x, int y, int z) { - return extent.getLazyBlock(mx + x, my + y, mz + z); + public BaseBlock getBlock(int x, int y, int z) { + return extent.getFullBlock(BlockVector3.at(mx + x, my + y, mz + z)); } - public BlockState getBlockAbs(int x, int y, int z) { - return extent.getLazyBlock(x, y, z); + public BaseBlock getBlockAbs(int x, int y, int z) { + return extent.getFullBlock(BlockVector3.at(x, y, z)); } @Override public BaseBiome getBiome(int x, int z) { - return extent.getBiome(mutableBlockVector2D.setComponents(mx + x, mz + z)); + return extent.getBiome(MutableBlockVector2.setComponents(mx + x, mz + z)); } @Override @@ -72,22 +72,21 @@ public class WorldCopyClipboard extends ReadOnlyClipboard { @Override public void forEach(BlockReader task, boolean air) { - Vector min = region.getMinimumPoint(); - Vector max = region.getMaximumPoint(); - final Vector pos = new Vector(); + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); + MutableBlockVector3 pos = new MutableBlockVector3(); if (region instanceof CuboidRegion) { if (air) { ((CuboidRegion) region).setUseOldIterator(true); RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { @Override - public boolean apply(Vector pos) throws WorldEditException { - BlockState block = getBlockAbs(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); + public boolean apply(BlockVector3 pos) throws WorldEditException { + BaseBlock block = getBlockAbs(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); int x = pos.getBlockX() - mx; int y = pos.getBlockY() - my; int z = pos.getBlockZ() - mz; - CompoundTag tag = block.getNbtData(); - if (tag != null) { - Map values = ReflectionUtils.getMap(tag.getValue()); + if (block.hasNbtData()) { + Map values = ReflectionUtils.getMap(block.getNbtData().getValue()); values.put("x", new IntTag(x)); values.put("y", new IntTag(y)); values.put("z", new IntTag(z)); @@ -102,15 +101,15 @@ public class WorldCopyClipboard extends ReadOnlyClipboard { cuboidEquivalent.setUseOldIterator(true); RegionVisitor visitor = new RegionVisitor(cuboidEquivalent, new RegionFunction() { @Override - public boolean apply(Vector pos) throws WorldEditException { + public boolean apply(BlockVector3 pos) throws WorldEditException { int x = pos.getBlockX() - mx; int y = pos.getBlockY() - my; int z = pos.getBlockZ() - mz; if (region.contains(pos)) { - BlockState block = getBlockAbs(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); - CompoundTag tag = block.getNbtData(); - if (tag != null) { - Map values = ReflectionUtils.getMap(tag.getValue()); +// BlockState block = getBlockAbs(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); + BaseBlock block = extent.getFullBlock(pos); + if (block.hasNbtData()) { + Map values = ReflectionUtils.getMap(block.getNbtData().getValue()); values.put("x", new IntTag(x)); values.put("y", new IntTag(y)); values.put("z", new IntTag(z)); @@ -137,13 +136,13 @@ public class WorldCopyClipboard extends ReadOnlyClipboard { pos.mutX(x); int xx = pos.getBlockX() - mx; if (region.contains(pos)) { - BlockState block = getBlockAbs(x, y, z); +// BlockState block = getBlockAbs(x, y, z); + BaseBlock block = extent.getFullBlock(pos); if (!air && block.getBlockType().getMaterial().isAir()) { continue; } - CompoundTag tag = block.getNbtData(); - if (tag != null) { - Map values = ReflectionUtils.getMap(tag.getValue()); + if (block.hasNbtData()) { + Map values = ReflectionUtils.getMap(block.getNbtData().getValue()); values.put("x", new IntTag(xx)); values.put("y", new IntTag(yy)); values.put("z", new IntTag(zz)); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/WorldCutClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/WorldCutClipboard.java index f77c2bf65..242c6bc52 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/WorldCutClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/WorldCutClipboard.java @@ -1,6 +1,8 @@ package com.boydti.fawe.object.clipboard; import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.regions.Region; @@ -14,17 +16,17 @@ public class WorldCutClipboard extends WorldCopyClipboard { } @Override - public BlockState getBlock(int x, int y, int z) { + public BaseBlock getBlock(int x, int y, int z) { int xx = mx + x; int yy = my + y; int zz = mz + z; - BlockState block = extent.getLazyBlock(xx, yy, zz); + BaseBlock block = extent.getFullBlock(BlockVector3.at(xx, yy, zz)); extent.setBlock(xx, yy, zz, EditSession.nullBlock); return block; } - public BlockState getBlockAbs(int x, int y, int z) { - BlockState block = extent.getLazyBlock(x, y, z); + public BaseBlock getBlockAbs(int x, int y, int z) { + BaseBlock block = extent.getFullBlock(BlockVector3.at(x, y, z)); extent.setBlock(x, y, z, EditSession.nullBlock); return block; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/remap/ClipboardRemapper.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/remap/ClipboardRemapper.java index 31a0bb9e8..b48c55f6e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/remap/ClipboardRemapper.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/remap/ClipboardRemapper.java @@ -1,29 +1,18 @@ package com.boydti.fawe.object.clipboard.remap; -import com.boydti.fawe.FaweCache; import com.google.common.io.Resources; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import com.intellectualcrafters.plot.util.MathMan; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.blocks.BaseItem; -import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; -import com.sk89q.worldedit.regions.Region; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.item.ItemTypes; -import com.sk89q.worldedit.world.registry.BundledBlockData; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -504,7 +493,7 @@ public class ClipboardRemapper { // } } - public BlockStateHolder remap(BlockStateHolder block) { + public > B remap(B block) { // int combined = block.getCombined(); // if (remap[combined]) { // char value = remapCombined[combined]; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/remap/RemappedClipboard.java b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/remap/RemappedClipboard.java index 165258f27..3f6fb01ab 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/remap/RemappedClipboard.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/clipboard/remap/RemappedClipboard.java @@ -3,6 +3,7 @@ package com.boydti.fawe.object.clipboard.remap; import com.boydti.fawe.jnbt.NBTStreamer; import com.boydti.fawe.object.clipboard.AbstractDelegateFaweClipboard; import com.boydti.fawe.object.clipboard.FaweClipboard; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -16,21 +17,21 @@ public class RemappedClipboard extends AbstractDelegateFaweClipboard { } @Override - public BlockState getBlock(int x, int y, int z) { - return (BlockState) remapper.remap(super.getBlock(x, y, z)); + public BaseBlock getBlock(int x, int y, int z) { + return remapper.remap(super.getBlock(x, y, z)); } @Override - public BlockState getBlock(int index) { - return (BlockState) remapper.remap(super.getBlock(index)); + public BaseBlock getBlock(int index) { + return remapper.remap(super.getBlock(index)); } @Override public void forEach(BlockReader task, boolean air) { super.forEach(new BlockReader() { @Override - public void run(int x, int y, int z, BlockState block) { - task.run(x, y, z, (BlockState) remapper.remap(block)); + public > void run(int x, int y, int z, B block) { + task.run(x, y, z, remapper.remap(block)); } }, air); } 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 fa4054394..a16f43a9d 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 @@ -1,8 +1,9 @@ package com.boydti.fawe.object.collection; import com.boydti.fawe.util.MathMan; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; + import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectIterator; @@ -20,7 +21,7 @@ import java.util.Set; * - 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) */ -public class BlockVectorSet extends AbstractCollection implements Set { +public class BlockVectorSet extends AbstractCollection implements Set { private Int2ObjectMap localSets = new Int2ObjectOpenHashMap<>(); @Override @@ -32,7 +33,7 @@ public class BlockVectorSet extends AbstractCollection implements Set> iter = localSets.int2ObjectEntrySet().iterator(); while (iter.hasNext()) { @@ -42,7 +43,7 @@ public class BlockVectorSet extends AbstractCollection implements Set index) { int localIndex = index - count; - Vector pos = set.getIndex(localIndex); + MutableBlockVector3 pos = new MutableBlockVector3(set.getIndex(localIndex)); if (pos != null) { int pair = entry.getIntKey(); int cx = MathMan.unpairX(pair); @@ -75,23 +76,23 @@ public class BlockVectorSet extends AbstractCollection implements Set iterator() { + public Iterator iterator() { final ObjectIterator> entries = localSets.int2ObjectEntrySet().iterator(); if (!entries.hasNext()) { - return new ArrayList().iterator(); + return new ArrayList().iterator(); } - return new Iterator() { + return new Iterator() { Int2ObjectMap.Entry entry = entries.next(); - Iterator entryIter = entry.getValue().iterator(); - MutableBlockVector mutable = new MutableBlockVector(); + Iterator entryIter = entry.getValue().iterator(); + MutableBlockVector3 mutable = new MutableBlockVector3(); @Override public void remove() { @@ -104,7 +105,7 @@ public class BlockVectorSet extends AbstractCollection implements Set implements Set implements Set implements Set implements Set c) { + public boolean addAll(Collection c) { boolean result = false; - for (Vector v : c) { + for (BlockVector3 v : c) { result |= add(v); } return result; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/IterableThreadLocal.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/IterableThreadLocal.java index 031f903ce..c31704c8d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/IterableThreadLocal.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/IterableThreadLocal.java @@ -12,7 +12,7 @@ import java.util.concurrent.ConcurrentLinkedDeque; public abstract class IterableThreadLocal extends ThreadLocal implements Iterable { private ThreadLocal flag; - private ConcurrentLinkedDeque allValues = new ConcurrentLinkedDeque(); + private ConcurrentLinkedDeque allValues = new ConcurrentLinkedDeque<>(); public IterableThreadLocal() { } 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 bd0a4b9df..47b2f9749 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 @@ -1,9 +1,9 @@ package com.boydti.fawe.object.collection; import com.boydti.fawe.util.MathMan; -import com.sk89q.worldedit.BlockVector2D; -import com.sk89q.worldedit.MutableBlockVector2D; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.MutableBlockVector2; + import java.util.Collection; import java.util.Iterator; import java.util.Set; @@ -13,9 +13,9 @@ import java.util.Set; * - All Vector2Ds must be within x[0,32768), y[0,32768) * - This will use 8 bytes for every 64 Vector2Ds (about 800x less than a HashSet) */ -public class LocalBlockVector2DSet implements Set { +public class LocalBlockVector2DSet implements Set { private final SparseBitSet set; - private final MutableBlockVector2D mutable = new MutableBlockVector2D(); + private final MutableBlockVector2 mutable = new MutableBlockVector2(); public LocalBlockVector2DSet() { this.set = new SparseBitSet(); @@ -41,8 +41,8 @@ public class LocalBlockVector2DSet implements Set { @Override public boolean contains(Object o) { - if (o instanceof Vector2D) { - Vector2D v = (Vector2D) o; + if (o instanceof BlockVector2) { + BlockVector2 v = (BlockVector2) o; return contains(v.getBlockX(), v.getBlockZ()); } return false; @@ -90,7 +90,7 @@ public class LocalBlockVector2DSet implements Set { return false; } - public Vector2D getIndex(int getIndex) { + public BlockVector2 getIndex(int getIndex) { int size = size(); if (getIndex > size) { return null; @@ -108,8 +108,8 @@ public class LocalBlockVector2DSet implements Set { } @Override - public Iterator iterator() { - return new Iterator() { + public Iterator iterator() { + return new Iterator() { int index = set.nextSetBit(0); int previous = -1; @@ -124,7 +124,7 @@ public class LocalBlockVector2DSet implements Set { } @Override - public Vector2D next() { + public BlockVector2 next() { if (index != -1) { int x = MathMan.unpairSearchCoordsX(index); int y = MathMan.unpairSearchCoordsY(index); @@ -147,14 +147,14 @@ public class LocalBlockVector2DSet implements Set { public T[] toArray(T[] array) { int size = size(); if (array == null || array.length < size) { - array = (T[]) new BlockVector2D[size]; + array = (T[]) new BlockVector2[size]; } int index = 0; for (int i = 0; i < size; i++) { index = set.nextSetBit(index); int x = MathMan.unpairSearchCoordsX(index); int y = MathMan.unpairSearchCoordsY(index); - array[i] = (T) new BlockVector2D(x, y); + array[i] = (T) BlockVector2.at(x, y); index++; } return array; @@ -174,11 +174,11 @@ public class LocalBlockVector2DSet implements Set { } @Override - public boolean add(Vector2D vector) { + public boolean add(BlockVector2 vector) { return add(vector.getBlockX(), vector.getBlockZ()); } - private int getIndex(Vector2D vector) { + private int getIndex(BlockVector2 vector) { return MathMan.pairSearchCoords(vector.getBlockX(), vector.getBlockZ()); } @@ -200,8 +200,8 @@ public class LocalBlockVector2DSet implements Set { @Override public boolean remove(Object o) { - if (o instanceof Vector2D) { - Vector2D v = (Vector2D) o; + if (o instanceof BlockVector2) { + BlockVector2 v = (BlockVector2) o; return remove(v.getBlockX(), v.getBlockZ()); } return false; @@ -218,9 +218,9 @@ public class LocalBlockVector2DSet implements Set { } @Override - public boolean addAll(Collection c) { + public boolean addAll(Collection c) { boolean result = false; - for (Vector2D v : c) { + for (BlockVector2 v : c) { result |= add(v); } return result; 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 35fab081f..863de2781 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 @@ -1,9 +1,9 @@ package com.boydti.fawe.object.collection; import com.boydti.fawe.util.MathMan; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; + import java.util.Collection; import java.util.Iterator; import java.util.Set; @@ -13,7 +13,7 @@ import java.util.Set; * - All vectors must be in a 2048 * 2048 area centered around the first entry * - This will use 8 bytes for every 64 BlockVectors (about 800x less than a HashSet) */ -public class LocalBlockVectorSet implements Set { +public class LocalBlockVectorSet implements Set { private int offsetX, offsetZ; private final SparseBitSet set; @@ -48,8 +48,8 @@ public class LocalBlockVectorSet implements Set { @Override public boolean contains(Object o) { - if (o instanceof Vector) { - Vector v = (Vector) o; + if (o instanceof BlockVector3) { + BlockVector3 v = (BlockVector3) o; return contains(v.getBlockX(), v.getBlockY(), v.getBlockZ()); } return false; @@ -100,7 +100,7 @@ public class LocalBlockVectorSet implements Set { this.offsetZ = z; } - public Vector getIndex(int getIndex) { + public BlockVector3 getIndex(int getIndex) { int size = size(); if (getIndex > size) { return null; @@ -117,17 +117,17 @@ public class LocalBlockVectorSet implements Set { int x = offsetX + (((b3 + ((MathMan.unpair8x(b2)) << 8)) << 21) >> 21); int y = b1; int z = offsetZ + (((b4 + ((MathMan.unpair8y(b2)) << 8)) << 21) >> 21); - return MutableBlockVector.get(x, y, z); + return MutableBlockVector3.get(x, y, z); } return null; } @Override - public Iterator iterator() { - return new Iterator() { + public Iterator iterator() { + return new Iterator() { int index = set.nextSetBit(0); int previous = -1; - MutableBlockVector mutable = new MutableBlockVector(0, 0, 0); + MutableBlockVector3 mutable = new MutableBlockVector3(0, 0, 0); @Override public void remove() { @@ -140,7 +140,7 @@ public class LocalBlockVectorSet implements Set { } @Override - public BlockVector next() { + public BlockVector3 next() { if (index != -1) { int b1 = (index & 0xFF); int b2 = ((byte) (index >> 8)) & 0x7F; @@ -167,7 +167,7 @@ public class LocalBlockVectorSet implements Set { public T[] toArray(T[] array) { int size = size(); if (array == null || array.length < size) { - array = (T[]) new BlockVector[size]; + array = (T[]) new BlockVector3[size]; } int index = 0; for (int i = 0; i < size; i++) { @@ -179,7 +179,7 @@ public class LocalBlockVectorSet implements Set { int x = offsetX + (((b3 + ((MathMan.unpair8x(b2)) << 8)) << 21) >> 21); int y = b1; int z = offsetZ + (((b4 + ((MathMan.unpair8y(b2)) << 8)) << 21) >> 21); - array[i] = (T) new BlockVector(x, y, z); + array[i] = (T) BlockVector3.at(x, y, z); index++; } return array; @@ -223,11 +223,11 @@ public class LocalBlockVectorSet implements Set { } @Override - public boolean add(Vector vector) { + public boolean add(BlockVector3 vector) { return add(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ()); } - private int getIndex(Vector vector) { + private int getIndex(BlockVector3 vector) { return MathMan.tripleSearchCoords(vector.getBlockX() - offsetX, vector.getBlockY(), vector.getBlockZ() - offsetZ); } @@ -249,8 +249,8 @@ public class LocalBlockVectorSet implements Set { @Override public boolean remove(Object o) { - if (o instanceof Vector) { - Vector v = (Vector) o; + if (o instanceof BlockVector3) { + BlockVector3 v = (BlockVector3) o; return remove(v.getBlockX(), v.getBlockY(), v.getBlockZ()); } return false; @@ -267,9 +267,9 @@ public class LocalBlockVectorSet implements Set { } @Override - public boolean addAll(Collection c) { + public boolean addAll(Collection c) { boolean result = false; - for (Vector v : c) { + for (BlockVector3 v : c) { result |= add(v); } return result; @@ -280,7 +280,7 @@ public class LocalBlockVectorSet implements Set { boolean result = false; int size = size(); int index = -1; - Vector mVec = MutableBlockVector.get(0, 0, 0); + MutableBlockVector3 mVec = MutableBlockVector3.get(0, 0, 0); for (int i = 0; i < size; i++) { index = set.nextSetBit(index + 1); int b1 = (index & 0xFF); @@ -310,7 +310,7 @@ public class LocalBlockVectorSet implements Set { public void forEach(BlockVectorSetVisitor visitor) { int size = size(); int index = -1; - Vector mVec = MutableBlockVector.get(0, 0, 0); + BlockVector3 mVec = MutableBlockVector3.get(0, 0, 0); for (int i = 0; i < size; i++) { index = set.nextSetBit(index + 1); int b1 = (index & 0xFF); 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 55e15b63c..aaa450f49 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 @@ -7,7 +7,7 @@ import java.util.TreeMap; public class SimpleRandomCollection extends RandomCollection { - private final NavigableMap map = new TreeMap(); + private final NavigableMap map = new TreeMap<>(); private double total = 0; public SimpleRandomCollection(Map weights, SimpleRandom random) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SoftHashMap.java b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SoftHashMap.java index 4bc0875dd..883d4d235 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SoftHashMap.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/collection/SoftHashMap.java @@ -93,10 +93,10 @@ public class SoftHashMap implements Map { public SoftHashMap(int retentionSize) { super(); RETENTION_SIZE = Math.max(0, retentionSize); - queue = new ReferenceQueue(); + queue = new ReferenceQueue<>(); strongReferencesLock = new ReentrantLock(); - map = new ConcurrentHashMap>(); - strongReferences = new ConcurrentLinkedQueue(); + map = new ConcurrentHashMap<>(); + strongReferences = new ConcurrentLinkedQueue<>(); } /** @@ -223,7 +223,7 @@ public class SoftHashMap implements Map { //noinspection unchecked return Collections.EMPTY_SET; } - Collection values = new ArrayList(keys.size()); + Collection values = new ArrayList<>(keys.size()); for (K key : keys) { V v = get(key); if (v != null) { @@ -238,7 +238,7 @@ public class SoftHashMap implements Map { */ public V put(K key, V value) { processQueue(); // throw out garbage collected values first - SoftValue sv = new SoftValue(value, key, queue); + SoftValue sv = new SoftValue<>(value, key, queue); SoftValue previous = map.put(key, sv); addToStrongReferences(value); return previous != null ? previous.get() : null; @@ -274,7 +274,7 @@ public class SoftHashMap implements Map { return Collections.EMPTY_SET; } - Map kvPairs = new HashMap(keys.size()); + Map kvPairs = new HashMap<>(keys.size()); for (K key : keys) { V v = get(key); if (v != null) { @@ -307,4 +307,4 @@ public class SoftHashMap implements Map { } } -} \ No newline at end of file +} 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 8339719e4..268bdf211 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 @@ -1,20 +1,19 @@ package com.boydti.fawe.object.extent; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.biome.BaseBiome; -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 MutableBlockVector mutable = new MutableBlockVector(); + private MutableBlockVector3 mutable = new MutableBlockVector3(); public BlockTranslateExtent(Extent extent, int dx, int dy, int dz) { super(extent); @@ -24,7 +23,7 @@ public class BlockTranslateExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, T block) throws WorldEditException { mutable.mutX((location.getX() + dx)); mutable.mutY((location.getY() + dy)); mutable.mutZ((location.getZ() + dz)); @@ -32,15 +31,12 @@ public class BlockTranslateExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { - mutable.mutX(x + dx); - mutable.mutY(y + dy); - mutable.mutZ(z + dz); - return getExtent().setBlock(mutable, block); + public > boolean setBlock(int x, int y, int z, T block) throws WorldEditException { + return this.setBlock(BlockVector3.at(x, y, z), block); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return super.setBiome(position.add(dx, dz), biome); } @@ -50,17 +46,17 @@ public class BlockTranslateExtent extends AbstractDelegateExtent { } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return super.getBiome(position.add(dx, dz)); } @Override - public BlockState getBlock(Vector location) { + public BlockState getBlock(BlockVector3 location) { return getLazyBlock(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Override - public BlockState getLazyBlock(Vector location) { + public BlockState getLazyBlock(BlockVector3 location) { return getLazyBlock(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @@ -68,4 +64,9 @@ public class BlockTranslateExtent extends AbstractDelegateExtent { public BlockState getLazyBlock(int x, int y, int z) { return super.getLazyBlock(x + dx, y + dy, z + dz); } + + @Override + public BaseBlock getFullBlock(BlockVector3 pos) { + return super.getFullBlock(pos.add(dx, dy, dz)); + } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/EmptyExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/EmptyExtent.java index 1a774746f..123b12387 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/EmptyExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/EmptyExtent.java @@ -1,15 +1,15 @@ package com.boydti.fawe.object.extent; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; @@ -23,12 +23,12 @@ public class EmptyExtent implements Extent { public EmptyExtent() { } - public Vector getMinimumPoint() { - return Vector.ZERO; + public BlockVector3 getMinimumPoint() { + return BlockVector3.ZERO; } - public Vector getMaximumPoint() { - return Vector.ZERO; + public BlockVector3 getMaximumPoint() { + return BlockVector3.ZERO; } public List getEntities(Region region) { @@ -45,27 +45,27 @@ public class EmptyExtent implements Extent { } @Override - public BlockState getFullBlock(Vector position) { - return EditSession.nullBlock; + public BaseBlock getFullBlock(BlockVector3 position) { + return EditSession.nullBlock.toBaseBlock(); } @Override - public BlockState getLazyBlock(Vector position) { + public BlockState getLazyBlock(BlockVector3 position) { return EditSession.nullBlock; } @Nullable - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return null; } @Override - public boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 position, BlockStateHolder block) throws WorldEditException { return false; } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return false; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/FastWorldEditExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/FastWorldEditExtent.java index cc5d2a69e..3db2fe41a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/FastWorldEditExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/FastWorldEditExtent.java @@ -6,14 +6,14 @@ import com.boydti.fawe.object.HasFaweQueue; import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.ReflectionUtils; import com.sk89q.jnbt.*; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.AbstractDelegateExtent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; @@ -106,32 +106,47 @@ public class FastWorldEditExtent extends AbstractDelegateExtent implements HasFa } @Override - public BaseBiome getBiome(final Vector2D position) { + public BaseBiome getBiome(final BlockVector2 position) { return FaweCache.CACHE_BIOME[queue.getBiomeId(position.getBlockX(), position.getBlockZ())]; } @Override - public boolean setBlock(final Vector location, final BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(final BlockVector3 location, final B block) throws WorldEditException { return setBlock(location.getBlockX(), location.getBlockY(), location.getBlockZ(), block); } + + + + @Override + public > boolean setBlock(int x, int y, int z, final B block) throws WorldEditException { + return queue.setBlock(x, y, z, block); + } @Override - public BlockState getLazyBlock(Vector location) { + public BlockState getLazyBlock(BlockVector3 location) { return getLazyBlock(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Override public BlockState getLazyBlock(int x, int y, int z) { int combinedId4Data = queue.getCombinedId4Data(x, y, z, 0); - BlockTypes type = BlockTypes.getFromStateId(combinedId4Data); + BlockType type = BlockTypes.getFromStateId(combinedId4Data); BlockState state = type.withStateId(combinedId4Data); + return state; + } + + @Override + public BaseBlock getFullBlock(BlockVector3 pos) { + int combinedId4Data = queue.getCombinedId4Data(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ(), 0); + BlockType type = BlockTypes.getFromStateId(combinedId4Data); + BaseBlock base = type.withStateId(combinedId4Data).toBaseBlock(); if (type.getMaterial().hasContainer()) { - CompoundTag tile = queue.getTileEntity(x, y, z); + CompoundTag tile = queue.getTileEntity(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); if (tile != null) { - return new BaseBlock(state, tile); + return base.toBaseBlock(tile); } } - return state; + return base; } @Override @@ -145,18 +160,13 @@ public class FastWorldEditExtent extends AbstractDelegateExtent implements HasFa } @Override - public BlockState getBlock(final Vector position) { + public BlockState getBlock(final BlockVector3 position) { return this.getLazyBlock(position); } @Override - public boolean setBiome(final Vector2D position, final BaseBiome biome) { + public boolean setBiome(final BlockVector2 position, final BaseBiome biome) { queue.setBiome(position.getBlockX(), position.getBlockZ(), biome); return true; } - - @Override - public boolean setBlock(int x, int y, int z, final BlockStateHolder block) throws WorldEditException { - return queue.setBlock(x, y, z, block); - } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/FaweRegionExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/FaweRegionExtent.java index 04f8323f3..c0e4477b8 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/FaweRegionExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/FaweRegionExtent.java @@ -4,14 +4,14 @@ import com.boydti.fawe.config.BBC; import com.boydti.fawe.object.FaweLimit; import com.boydti.fawe.util.WEManager; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; @@ -48,16 +48,16 @@ public abstract class FaweRegionExtent extends ResettableExtent { return false; } - public final boolean contains(Vector p) { + public final boolean contains(BlockVector3 p) { return contains(p.getBlockX(), p.getBlockY(), p.getBlockZ()); } - public final boolean contains(Vector2D p) { + public final boolean contains(BlockVector2 p) { return contains(p.getBlockX(), p.getBlockZ()); } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { if (!contains(location)) { if (!limit.MAX_FAILS()) { WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION); @@ -68,7 +68,7 @@ public abstract class FaweRegionExtent extends ResettableExtent { } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { if (!contains(x, y, z)) { if (!limit.MAX_FAILS()) { WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION); @@ -79,7 +79,7 @@ public abstract class FaweRegionExtent extends ResettableExtent { } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { if (!contains(position)) { if (!limit.MAX_FAILS()) { WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION); @@ -101,7 +101,7 @@ public abstract class FaweRegionExtent extends ResettableExtent { } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { if (!contains(position)) { if (!limit.MAX_FAILS()) { WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION); @@ -110,9 +110,20 @@ public abstract class FaweRegionExtent extends ResettableExtent { } return super.getBiome(position); } + + @Override + public BaseBlock getFullBlock(BlockVector3 position) { + if (!contains(position)) { + if (!limit.MAX_FAILS()) { + WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION); + } + return EditSession.nullBlock.toBaseBlock(); + } + return super.getFullBlock(position); + } @Override - public BlockState getBlock(Vector position) { + public BlockState getBlock(BlockVector3 position) { if (!contains(position)) { if (!limit.MAX_FAILS()) { WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION); @@ -123,7 +134,7 @@ public abstract class FaweRegionExtent extends ResettableExtent { } @Override - public BlockState getLazyBlock(Vector position) { + public BlockState getLazyBlock(BlockVector3 position) { if (!contains(position)) { if (!limit.MAX_FAILS()) { WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/MemoryCheckingExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/MemoryCheckingExtent.java index c0e68f856..9503ade76 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/MemoryCheckingExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/MemoryCheckingExtent.java @@ -5,12 +5,11 @@ import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.util.MemUtil; import com.boydti.fawe.util.Perm; import com.boydti.fawe.util.WEManager; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; public class MemoryCheckingExtent extends AbstractDelegateExtent { @@ -22,7 +21,7 @@ public class MemoryCheckingExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(final Vector location, final BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(final BlockVector3 location, final B block) throws WorldEditException { if (super.setBlock(location, block)) { if (MemUtil.isMemoryLimited()) { if (this.player != null) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/MultiTransform.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/MultiTransform.java index f5aa12ac1..57883fddd 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/MultiTransform.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/MultiTransform.java @@ -1,13 +1,12 @@ package com.boydti.fawe.object.extent; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.AbstractDelegateExtent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -40,14 +39,14 @@ public class MultiTransform extends RandomTransform { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 location, BlockStateHolder block) throws WorldEditException { boolean result = false; for (AbstractDelegateExtent extent : extents) result |= extent.setBlock(location, block); return result; } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { boolean result = false; for (AbstractDelegateExtent extent : extents) result |= extent.setBiome(position, biome); return result; 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 610068303..1f851b178 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 @@ -3,15 +3,15 @@ package com.boydti.fawe.object.extent; import com.boydti.fawe.config.BBC; import com.boydti.fawe.object.FaweLimit; import com.boydti.fawe.object.exception.FaweException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; @@ -41,50 +41,82 @@ public class NullExtent extends FaweRegionExtent { super(new com.sk89q.worldedit.extent.NullExtent(), FaweLimit.MAX); this.reason = BBC.WORLDEDIT_CANCEL_REASON_MANUAL; } - + @Override public ResettableExtent setExtent(Extent extent) { return this; } @Override - public BaseBiome getBiome(final Vector2D arg0) { - throw new FaweException(reason); + public BaseBiome getBiome(final BlockVector2 arg0) { + if(reason != null) { + throw new FaweException(reason); + }else { + return null; + } } @Override - public BaseBlock getBlock(final Vector arg0) { - throw new FaweException(reason); + public BlockState getBlock(final BlockVector3 arg0) { + if(reason != null) { + throw new FaweException(reason); + }else { + return null; + } } @Override - public BaseBlock getLazyBlock(final Vector arg0) { - throw new FaweException(reason); + public BlockState getLazyBlock(final BlockVector3 arg0) { + if(reason != null) { + throw new FaweException(reason); + }else { + return null; + } } @Override - public boolean setBiome(final Vector2D arg0, final BaseBiome arg1) { - throw new FaweException(reason); + public boolean setBiome(final BlockVector2 arg0, final BaseBiome arg1) { + if(reason != null) { + throw new FaweException(reason); + }else { + return false; + } } @Override - public boolean setBlock(final Vector arg0, final BlockStateHolder arg1) throws WorldEditException { - throw new FaweException(reason); + public boolean setBlock(final BlockVector3 arg0, final BlockStateHolder arg1) throws WorldEditException { + if(reason != null) { + throw new FaweException(reason); + }else { + return false; + } } @Override public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { - throw new FaweException(reason); + if(reason != null) { + throw new FaweException(reason); + }else { + return false; + } } @Override - public BaseBlock getLazyBlock(int x, int y, int z) { - throw new FaweException(reason); + public BlockState getLazyBlock(int x, int y, int z) { + if(reason != null) { + throw new FaweException(reason); + }else { + return null; + } } @Override public Entity createEntity(final Location arg0, final BaseEntity arg1) { - throw new FaweException(reason); + if(reason != null) { + throw new FaweException(reason); + }else { + return null; + } } @Override @@ -98,23 +130,31 @@ public class NullExtent extends FaweRegionExtent { } @Override - public Vector getMaximumPoint() { - return new Vector(0, 0, 0); + public BlockVector3 getMaximumPoint() { + return BlockVector3.at(0, 0, 0); } @Override - public Vector getMinimumPoint() { - return new Vector(0, 0, 0); + public BlockVector3 getMinimumPoint() { + return BlockVector3.at(0, 0, 0); } @Override public boolean contains(int x, int z) { - throw new FaweException(reason); + if(reason != null) { + throw new FaweException(reason); + }else { + return false; + } } @Override public boolean contains(int x, int y, int z) { - throw new FaweException(reason); + if(reason != null) { + throw new FaweException(reason); + }else { + return false; + } } @Override @@ -135,17 +175,29 @@ public class NullExtent extends FaweRegionExtent { @Override public int getNearestSurfaceLayer(int x, int z, int y, int minY, int maxY) { - throw new FaweException(reason); + if(reason != null) { + throw new FaweException(reason); + }else { + return -1; + } } @Override public int getNearestSurfaceTerrainBlock(int x, int z, int y, int minY, int maxY) { - throw new FaweException(reason); + if(reason != null) { + throw new FaweException(reason); + }else { + return -1; + } } @Override public int getNearestSurfaceTerrainBlock(int x, int z, int y, int minY, int maxY, int failedMin, int failedMax) { - throw new FaweException(reason); + if(reason != null) { + throw new FaweException(reason); + }else { + return -1; + } } @Override 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 7225fe9c0..c8d05b9d7 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 @@ -1,18 +1,16 @@ package com.boydti.fawe.object.extent; -import com.sk89q.worldedit.MutableBlockVector2D; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector2; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; public class OffsetExtent extends ResettableExtent { private final int dx, dy, dz; - private transient MutableBlockVector2D mutable = new MutableBlockVector2D(); + private transient MutableBlockVector2 mutable = new MutableBlockVector2(); public OffsetExtent(Extent parent, int dx, int dy, int dz) { super(parent); @@ -22,7 +20,7 @@ public class OffsetExtent extends ResettableExtent { } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return getExtent().setBiome(mutable.setComponents(position.getBlockX() + dx, position.getBlockZ() + dz), biome); } @@ -32,7 +30,7 @@ public class OffsetExtent extends ResettableExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 location, BlockStateHolder block) throws WorldEditException { return getExtent().setBlock(location.getBlockX() + dx, location.getBlockY() + dy, location.getBlockZ() + dz, block); } @@ -43,7 +41,7 @@ public class OffsetExtent extends ResettableExtent { @Override public ResettableExtent setExtent(Extent extent) { - mutable = new MutableBlockVector2D(); + mutable = new MutableBlockVector2(); return super.setExtent(extent); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/PatternTransform.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/PatternTransform.java index 977db3092..ba546238d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/PatternTransform.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/PatternTransform.java @@ -1,11 +1,11 @@ package com.boydti.fawe.object.extent; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; public class PatternTransform extends ResettableExtent { @@ -17,7 +17,7 @@ public class PatternTransform extends ResettableExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 location, BlockStateHolder block) throws WorldEditException { return pattern.apply(getExtent(), location, location); } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/PositionTransformExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/PositionTransformExtent.java index 0b9f69e1a..93616d458 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/PositionTransformExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/PositionTransformExtent.java @@ -1,20 +1,21 @@ package com.boydti.fawe.object.extent; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; +import com.sk89q.worldedit.math.MutableVector3; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; public class PositionTransformExtent extends ResettableExtent { - private transient MutableBlockVector mutable = new MutableBlockVector(); - private transient Vector min; + private transient MutableBlockVector3 mutable = new MutableBlockVector3(); + private transient BlockVector3 min; private Transform transform; public PositionTransformExtent(Extent parent, Transform transform) { @@ -24,83 +25,72 @@ public class PositionTransformExtent extends ResettableExtent { @Override public ResettableExtent setExtent(Extent extent) { - mutable = new MutableBlockVector(); + mutable = new MutableBlockVector3(); min = null; return super.setExtent(extent); } - public void setOrigin(Vector pos) { + public void setOrigin(BlockVector3 pos) { this.min = pos; } - private Vector getPos(Vector pos) { + private BlockVector3 getPos(BlockVector3 pos) { if (min == null) { - min = new Vector(pos); + min = pos; } mutable.mutX(((pos.getX() - min.getX()))); mutable.mutY(((pos.getY() - min.getY()))); mutable.mutZ(((pos.getZ() - min.getZ()))); - Vector tmp = transform.apply(mutable); - tmp.mutX((tmp.getX() + min.getX())); - tmp.mutY((tmp.getY() + min.getY())); - tmp.mutZ((tmp.getZ() + min.getZ())); - return tmp; - } - - private Vector getPos(int x, int y, int z) { - if (min == null) { - min = new Vector(x, y, z); - } - mutable.mutX(((x - min.getX()))); - mutable.mutY(((y - min.getY()))); - mutable.mutZ(((z - min.getZ()))); - Vector tmp = transform.apply(mutable); - tmp.mutX((tmp.getX() + min.getX())); - tmp.mutY((tmp.getY() + min.getY())); - tmp.mutZ((tmp.getZ() + min.getZ())); - return tmp; + MutableVector3 tmp = new MutableVector3(transform.apply(mutable.toVector3())); + BlockVector3 result = min.add(tmp.toBlockPoint()); + return result; } @Override public BlockState getLazyBlock(int x, int y, int z) { - return super.getLazyBlock(getPos(x, y, z)); + return super.getLazyBlock(getPos(BlockVector3.at(x, y, z))); } @Override - public BlockState getLazyBlock(Vector position) { + public BlockState getLazyBlock(BlockVector3 position) { return super.getLazyBlock(getPos(position)); } @Override - public BlockState getBlock(Vector position) { + public BlockState getBlock(BlockVector3 position) { return super.getBlock(getPos(position)); } + + @Override + public BaseBlock getFullBlock(BlockVector3 position) { + return super.getFullBlock(getPos(position)); + } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { mutable.mutX(position.getBlockX()); mutable.mutZ(position.getBlockZ()); mutable.mutY(0); - return super.getBiome(getPos(mutable).toVector2D()); + return super.getBiome(getPos(mutable).toBlockVector2()); } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { - return super.setBlock(getPos(x, y, z), block); + public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { + return this.setBlock(getPos(BlockVector3.at(x, y, z)), block); } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { return super.setBlock(getPos(location), block); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { mutable.mutX(position.getBlockX()); mutable.mutZ(position.getBlockZ()); mutable.mutY(0); - return super.setBiome(getPos(mutable).toVector2D(), biome); + return super.setBiome(getPos(mutable).toBlockVector2(), biome); } public void setTransform(Transform transform) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ProcessedWEExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ProcessedWEExtent.java index 59d7b6ad5..7593d0b2d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ProcessedWEExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ProcessedWEExtent.java @@ -5,15 +5,15 @@ import com.boydti.fawe.object.FaweLimit; import com.boydti.fawe.util.WEManager; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; @@ -48,7 +48,7 @@ public class ProcessedWEExtent extends AbstractDelegateExtent { } @Override - public BaseBiome getBiome(final Vector2D position) { + public BaseBiome getBiome(final BlockVector2 position) { return super.getBiome(position); } @@ -71,21 +71,31 @@ public class ProcessedWEExtent extends AbstractDelegateExtent { return extent.getLazyBlock(x, y, z); } } + + @Override + public BaseBlock getFullBlock(BlockVector3 pos) { + if (!limit.MAX_CHECKS()) { + WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_MAX_CHECKS); + return EditSession.nullBlock.toBaseBlock(); + } else { + return extent.getFullBlock(pos); + } + } @Override - public boolean setBlock(final Vector location, final BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(final BlockVector3 location, final B block) throws WorldEditException { return setBlock(location.getBlockX(), location.getBlockY(), location.getBlockZ(), block); } @Override - public BlockState getLazyBlock(Vector location) { + public BlockState getLazyBlock(BlockVector3 location) { return getLazyBlock(location.getBlockX(), location.getBlockY(), location.getBlockZ()); } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { - CompoundTag nbt = block.getNbtData(); - if (nbt != null) { + public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { + boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); + if (hasNbt) { if (!limit.MAX_BLOCKSTATES()) { WEManager.IMP.cancelEdit(this, BBC.WORLDEDIT_CANCEL_REASON_MAX_TILES); return false; @@ -106,7 +116,7 @@ public class ProcessedWEExtent extends AbstractDelegateExtent { } @Override - public boolean setBiome(final Vector2D position, final BaseBiome biome) { + public boolean setBiome(final BlockVector2 position, final BaseBiome biome) { if (!limit.MAX_CHANGES()) { WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_MAX_CHANGES); return false; 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 17c2d6193..b57b73acd 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 @@ -1,12 +1,11 @@ package com.boydti.fawe.object.extent; -import com.sk89q.worldedit.MutableBlockVector2D; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; + import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector2; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -14,7 +13,7 @@ import java.util.SplittableRandom; public class RandomOffsetTransform extends ResettableExtent { private transient SplittableRandom random; - private transient MutableBlockVector2D mutable = new MutableBlockVector2D(); + private transient MutableBlockVector2 mutable = new MutableBlockVector2(); private final int dx, dy, dz; @@ -27,14 +26,14 @@ public class RandomOffsetTransform extends ResettableExtent { } @Override - public boolean setBiome(Vector2D pos, BaseBiome biome) { + public boolean setBiome(BlockVector2 pos, BaseBiome biome) { int x = pos.getBlockX() + random.nextInt(1 + (dx << 1)) - dx; int z = pos.getBlockZ() + random.nextInt(1 + (dz << 1)) - dz; return getExtent().setBiome(mutable.setComponents(x, z), biome); } @Override - public boolean setBlock(Vector pos, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 pos, BlockStateHolder block) throws WorldEditException { int x = pos.getBlockX() + random.nextInt(1 + (dx << 1)) - dx; int y = pos.getBlockY() + random.nextInt(1 + (dy << 1)) - dy; int z = pos.getBlockZ() + random.nextInt(1 + (dz << 1)) - dz; @@ -52,7 +51,7 @@ public class RandomOffsetTransform extends ResettableExtent { @Override public ResettableExtent setExtent(Extent extent) { random = new SplittableRandom(); - mutable = new MutableBlockVector2D(); + mutable = new MutableBlockVector2(); return super.setExtent(extent); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ResettableExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ResettableExtent.java index ac96e0904..bee31b63d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ResettableExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/ResettableExtent.java @@ -2,9 +2,9 @@ package com.boydti.fawe.object.extent; import com.boydti.fawe.util.ExtentTraverser; import com.boydti.fawe.util.ReflectionUtils; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.World; import java.io.IOException; import java.io.Serializable; @@ -18,7 +18,7 @@ public class ResettableExtent extends AbstractDelegateExtent implements Serializ super(parent); } - public final void init(Vector pos) { + public final void init(BlockVector3 pos) { Extent extent = getExtent(); if (extent instanceof ResettableExtent && extent != this) { ((ResettableExtent) extent).init(pos); @@ -26,7 +26,7 @@ public class ResettableExtent extends AbstractDelegateExtent implements Serializ setOrigin(pos); } - protected void setOrigin(Vector pos) { + protected void setOrigin(BlockVector3 pos) { } 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 4543a551f..3cd8ec8a7 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 @@ -1,14 +1,13 @@ package com.boydti.fawe.object.extent; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; + import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -16,9 +15,9 @@ import com.sk89q.worldedit.world.block.BlockStateHolder; import javax.annotation.Nullable; public class ScaleTransform extends ResettableExtent { - private transient MutableBlockVector mutable = new MutableBlockVector(); + private transient MutableBlockVector3 mutable = new MutableBlockVector3(); private transient int maxy; - private transient Vector min; + private transient BlockVector3 min; private final double dx, dy, dz; @@ -35,13 +34,13 @@ public class ScaleTransform extends ResettableExtent { public ResettableExtent setExtent(Extent extent) { min = null; maxy = extent.getMaximumPoint().getBlockY(); - mutable = new MutableBlockVector(); + mutable = new MutableBlockVector3(); return super.setExtent(extent); } - private Vector getPos(Vector pos) { + private BlockVector3 getPos(BlockVector3 pos) { if (min == null) { - min = new Vector(pos); + min = pos; } mutable.mutX((min.getX() + (pos.getX() - min.getX()) * dx)); mutable.mutY((min.getY() + (pos.getY() - min.getY()) * dy)); @@ -49,9 +48,9 @@ public class ScaleTransform extends ResettableExtent { return mutable; } - private Vector getPos(int x, int y, int z) { + private BlockVector3 getPos(int x, int y, int z) { if (min == null) { - min = new Vector(x, y, z); + min = BlockVector3.at(x, y, z); } mutable.mutX((min.getX() + (x - min.getX()) * dx)); mutable.mutY((min.getY() + (y - min.getY()) * dy)); @@ -61,9 +60,9 @@ public class ScaleTransform extends ResettableExtent { @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 location, BlockStateHolder block) throws WorldEditException { boolean result = false; - Vector pos = getPos(location); + MutableBlockVector3 pos = new MutableBlockVector3(getPos(location)); double sx = pos.getX(); double sy = pos.getY(); double sz = pos.getZ(); @@ -81,16 +80,16 @@ public class ScaleTransform extends ResettableExtent { } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { boolean result = false; - Vector pos = getPos(position.getBlockX(), 0, position.getBlockZ()); + MutableBlockVector3 pos = new MutableBlockVector3(getPos(position.getBlockX(), 0, position.getBlockZ())); double sx = pos.getX(); double sz = pos.getZ(); double ex = pos.getX() + dx; double ez = pos.getZ() + dz; for (pos.mutZ(sz); pos.getZ() < ez; pos.mutZ(pos.getZ() + 1)) { for (pos.mutX(sx); pos.getX() < ex; pos.mutX(pos.getX() + 1)) { - result |= super.setBiome(pos.toVector2D(), biome); + result |= super.setBiome(pos.toBlockVector2(), biome); } } return result; @@ -99,7 +98,7 @@ public class ScaleTransform extends ResettableExtent { @Override public boolean setBlock(int x1, int y1, int z1, BlockStateHolder block) throws WorldEditException { boolean result = false; - Vector pos = getPos(x1, y1, z1); + MutableBlockVector3 pos = new MutableBlockVector3(getPos(x1, y1, z1)); double sx = pos.getX(); double sy = pos.getY(); double sz = pos.getZ(); @@ -119,7 +118,7 @@ public class ScaleTransform extends ResettableExtent { @Nullable @Override public Entity createEntity(Location location, BaseEntity entity) { - Location newLoc = new Location(location.getExtent(), getPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()), location.getYaw(), location.getPitch()); + Location newLoc = new Location(location.getExtent(), getPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()).toVector3(), location.getYaw(), location.getPitch()); return super.createEntity(newLoc, entity); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SelectTransform.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SelectTransform.java index 543cac3f3..7466eb3e7 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SelectTransform.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SelectTransform.java @@ -1,15 +1,15 @@ package com.boydti.fawe.object.extent; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.NullExtent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -25,11 +25,11 @@ public abstract class SelectTransform extends ResettableExtent { public abstract AbstractDelegateExtent getExtent(int x, int z); - public Extent getExtent(Vector pos) { + public Extent getExtent(BlockVector3 pos) { return getExtent(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); } - public Extent getExtent(Vector2D pos) { + public Extent getExtent(BlockVector2 pos) { return getExtent(pos.getBlockX(), pos.getBlockZ()); } @@ -39,7 +39,7 @@ public abstract class SelectTransform extends ResettableExtent { } @Override - public boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 position, BlockStateHolder block) throws WorldEditException { return getExtent(position).setBlock(position, block); } @@ -50,7 +50,7 @@ public abstract class SelectTransform extends ResettableExtent { } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return getExtent(position).setBiome(position, biome); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SlowExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SlowExtent.java index 423fd51c5..05679c565 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SlowExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SlowExtent.java @@ -1,12 +1,12 @@ package com.boydti.fawe.object.extent; import com.boydti.fawe.Fawe; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; public class SlowExtent extends AbstractDelegateExtent { @@ -18,7 +18,7 @@ public class SlowExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { if (!Fawe.isMainThread()) try { Thread.sleep(sleep); } catch (InterruptedException e) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SourceMaskExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SourceMaskExtent.java index 7cd046493..d706294f0 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SourceMaskExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/SourceMaskExtent.java @@ -1,12 +1,11 @@ package com.boydti.fawe.object.extent; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; + import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -14,7 +13,7 @@ import static com.google.common.base.Preconditions.checkNotNull; public class SourceMaskExtent extends TemporalExtent { private Mask mask; - private MutableBlockVector mutable = new MutableBlockVector(); + private MutableBlockVector3 mutable = new MutableBlockVector3(); /** @@ -43,7 +42,7 @@ public class SourceMaskExtent extends TemporalExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 location, BlockStateHolder block) throws WorldEditException { set(location.getBlockX(), location.getBlockY(), location.getBlockZ(), block); return mask.test(location) && super.setBlock(location, block); } 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 b2db133a4..0d69f4259 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 @@ -3,14 +3,14 @@ package com.boydti.fawe.object.extent; import com.boydti.fawe.util.ReflectionUtils; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.NbtValued; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -34,28 +34,40 @@ public class StripNBTExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { - return super.setBlock(location, stripNBT(block)); + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { + return super.setBlock(location, stripBlockNBT(block)); } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { - return super.setBlock(x, y, z, stripNBT(block)); + public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { + return super.setBlock(x, y, z, stripBlockNBT(block)); } @Nullable @Override public Entity createEntity(Location location, BaseEntity entity) { - return super.createEntity(location, stripNBT(entity)); + return super.createEntity(location, stripEntityNBT(entity)); } - public T stripNBT(T block) { - if (!block.hasNbtData()) return block; - CompoundTag nbt = block.getNbtData(); + public > B stripBlockNBT(B 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) { value.remove(key); } - return block; + return (B) localBlock; + } + + public T stripEntityNBT(T entity) { + if (!entity.hasNbtData()) return entity; + CompoundTag nbt = entity.getNbtData(); + Map value = nbt.getValue(); + for (String key : strip) { + value.remove(key); + } + return entity; } } 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 33f0a4170..b6f1cd552 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 @@ -1,20 +1,19 @@ package com.boydti.fawe.object.extent; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.blocks.BlockMaterial; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.registry.BundledBlockData; public class TemporalExtent extends AbstractDelegateExtent { private int x, y, z = Integer.MAX_VALUE; - private BlockState block = EditSession.nullBlock; + private BlockStateHolder block = EditSession.nullBlock; private int bx, bz = Integer.MAX_VALUE; private BaseBiome biome = EditSession.nullBiome; @@ -29,11 +28,11 @@ public class TemporalExtent extends AbstractDelegateExtent { } - public void set(int x, int y, int z, BlockStateHolder block) { + public > void set(int x, int y, int z, B block) { this.x = x; this.y = y; this.z = z; - this.block = (BlockState) block; + this.block = block; } public void set(int x, int z, BaseBiome biome) { @@ -51,17 +50,17 @@ public class TemporalExtent extends AbstractDelegateExtent { } @Override - public BlockState getBlock(Vector position) { + public BlockState getBlock(BlockVector3 position) { if (position.getX() == x && position.getY() == y && position.getZ() == z) { - return block; + return block.toImmutableState(); } return super.getBlock(position); } @Override - public BlockState getLazyBlock(Vector position) { + public BlockState getLazyBlock(BlockVector3 position) { if (position.getX() == x && position.getY() == y && position.getZ() == z) { - return block; + return block.toImmutableState(); } return super.getLazyBlock(position); } @@ -69,13 +68,25 @@ public class TemporalExtent extends AbstractDelegateExtent { @Override public BlockState getLazyBlock(int x, int y, int z) { if (this.x == x && this.y == y && this.z == z) { - return block; + return block.toImmutableState(); } return super.getLazyBlock(x, y, z); } + + @Override + public BaseBlock getFullBlock(BlockVector3 position) { + if (position.getX() == x && position.getY() == y && position.getZ() == z) { + if(block instanceof BaseBlock) { + return (BaseBlock)block; + }else { + return block.toBaseBlock(); + } + } + return super.getFullBlock(position); + } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { if (position.getX() == bx && position.getZ() == bz) { return biome; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/TransformExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/TransformExtent.java index a5e32f5fc..128577f74 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/extent/TransformExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/extent/TransformExtent.java @@ -1,22 +1,21 @@ package com.boydti.fawe.object.extent; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.transform.BlockTransformExtent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; +import com.sk89q.worldedit.math.MutableVector3; import com.sk89q.worldedit.world.biome.BaseBiome; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.registry.BlockRegistry; public class TransformExtent extends BlockTransformExtent { - private final MutableBlockVector mutable = new MutableBlockVector(); - private Vector min; + private final MutableBlockVector3 mutable = new MutableBlockVector3(); + private BlockVector3 min; private int maxy; public TransformExtent(Extent parent) { @@ -32,91 +31,96 @@ public class TransformExtent extends BlockTransformExtent { } @Override - public Vector getMinimumPoint() { - Vector pos1 = new MutableBlockVector(getPos(super.getMinimumPoint())); - Vector pos2 = new MutableBlockVector(getPos(super.getMaximumPoint())); - return Vector.getMinimum(pos1, pos2); + public BlockVector3 getMinimumPoint() { + BlockVector3 pos1 = getPos(super.getMinimumPoint()); + BlockVector3 pos2 = getPos(super.getMaximumPoint()); + return pos1.getMinimum(pos2); } @Override - public Vector getMaximumPoint() { - Vector pos1 = new MutableBlockVector(getPos(super.getMinimumPoint())); - Vector pos2 = new MutableBlockVector(getPos(super.getMaximumPoint())); - return Vector.getMaximum(pos1, pos2); + public BlockVector3 getMaximumPoint() { + BlockVector3 pos1 = getPos(super.getMinimumPoint()); + BlockVector3 pos2 = getPos(super.getMaximumPoint()); + return pos1.getMaximum(pos2); } @Override - public void setOrigin(Vector pos) { + public void setOrigin(BlockVector3 pos) { this.min = pos; } - public Vector getPos(Vector pos) { + public BlockVector3 getPos(BlockVector3 pos) { if (min == null) { - min = new Vector(pos); + min = pos; } mutable.mutX(((pos.getX() - min.getX()))); mutable.mutY(((pos.getY() - min.getY()))); mutable.mutZ(((pos.getZ() - min.getZ()))); - Vector tmp = getTransform().apply(mutable); + MutableVector3 tmp = new MutableVector3(getTransform().apply(mutable.toVector3())); tmp.mutX((tmp.getX() + min.getX())); tmp.mutY((tmp.getY() + min.getY())); tmp.mutZ((tmp.getZ() + min.getZ())); - return tmp; + return tmp.toBlockPoint(); } - public Vector getPos(int x, int y, int z) { + public BlockVector3 getPos(int x, int y, int z) { if (min == null) { - min = new Vector(x, y, z); + min = BlockVector3.at(x, y, z); } mutable.mutX(((x - min.getX()))); mutable.mutY(((y - min.getY()))); mutable.mutZ(((z - min.getZ()))); - Vector tmp = getTransform().apply(mutable); + MutableVector3 tmp = new MutableVector3(getTransform().apply(mutable.toVector3())); tmp.mutX((tmp.getX() + min.getX())); tmp.mutY((tmp.getY() + min.getY())); tmp.mutZ((tmp.getZ() + min.getZ())); - return tmp; + return tmp.toBlockPoint(); } @Override public BlockState getLazyBlock(int x, int y, int z) { - return transformFast(super.getLazyBlock(getPos(x, y, z))); + return transformBlock(super.getLazyBlock(getPos(x, y, z)), false).toImmutableState(); } @Override - public BlockState getLazyBlock(Vector position) { - return transformFast(super.getLazyBlock(getPos(position))); + public BlockState getLazyBlock(BlockVector3 position) { + return transformBlock(super.getLazyBlock(getPos(position)), false).toImmutableState(); } @Override - public BlockState getBlock(Vector position) { - return transformFast(super.getBlock(getPos(position))); + public BlockState getBlock(BlockVector3 position) { + return transformBlock(super.getBlock(getPos(position)), false).toImmutableState(); + } + + @Override + public BaseBlock getFullBlock(BlockVector3 position) { + return transformBlock(super.getFullBlock(getPos(position)), false); } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { mutable.mutX(position.getBlockX()); mutable.mutZ(position.getBlockZ()); mutable.mutY(0); - return super.getBiome(getPos(mutable).toVector2D()); + return super.getBiome(getPos(mutable).toBlockVector2()); } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { - return super.setBlock(getPos(x, y, z), transformFastInverse((BlockState) block)); + public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { + return super.setBlock(getPos(x, y, z), transformBlock((BlockState)block, false)); } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { - return super.setBlock(getPos(location), transformFastInverse((BlockState) block)); + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { + return super.setBlock(getPos(location), transformBlock((BlockState)block, false)); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { mutable.mutX(position.getBlockX()); mutable.mutZ(position.getBlockZ()); mutable.mutY(0); - return super.setBiome(getPos(mutable).toVector2D(), biome); + return super.setBiome(getPos(mutable).toBlockVector2(), biome); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/function/NullRegionFunction.java b/worldedit-core/src/main/java/com/boydti/fawe/object/function/NullRegionFunction.java index 2bed14216..48db35e5c 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/function/NullRegionFunction.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/function/NullRegionFunction.java @@ -1,12 +1,12 @@ package com.boydti.fawe.object.function; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.math.BlockVector3; public class NullRegionFunction implements RegionFunction { @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { return false; } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/function/SurfaceRegionFunction.java b/worldedit-core/src/main/java/com/boydti/fawe/object/function/SurfaceRegionFunction.java index 8858d302f..7b6aea4be 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/function/SurfaceRegionFunction.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/function/SurfaceRegionFunction.java @@ -1,11 +1,11 @@ package com.boydti.fawe.object.function; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.FlatRegionFunction; import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.MutableBlockVector3; public class SurfaceRegionFunction implements FlatRegionFunction { private final Extent extent; @@ -13,7 +13,7 @@ public class SurfaceRegionFunction implements FlatRegionFunction { private final int minY; private final int maxY; private int lastY; - private MutableBlockVector mutable = new MutableBlockVector(); + private MutableBlockVector3 mutable = new MutableBlockVector3(); public SurfaceRegionFunction(Extent extent, RegionFunction function, int minY, int maxY) { this.extent = extent; @@ -24,7 +24,7 @@ public class SurfaceRegionFunction implements FlatRegionFunction { } @Override - public boolean apply(Vector2D position) throws WorldEditException { + public boolean apply(BlockVector2 position) throws WorldEditException { int x = position.getBlockX(); int z = position.getBlockZ(); int layer = extent.getNearestSurfaceTerrainBlock(x, z, lastY, minY, maxY, false); 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 8ffdb6de3..87f533798 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 @@ -1,30 +1,32 @@ package com.boydti.fawe.object.function.block; -import com.sk89q.worldedit.MutableBlockVector2D; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector2; public class BiomeCopy implements RegionFunction { protected final Extent source; protected final Extent destination; - private final MutableBlockVector2D mPos2d; + private final MutableBlockVector2 mPos2d; public BiomeCopy(Extent source, Extent destination) { this.source = source; this.destination = destination; - this.mPos2d = new MutableBlockVector2D(); + this.mPos2d = new MutableBlockVector2(); this.mPos2d.setComponents(Integer.MIN_VALUE, Integer.MIN_VALUE); } @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { int x = position.getBlockX(); int z = position.getBlockZ(); if (x != mPos2d.getBlockX() || z != mPos2d.getBlockZ()) { mPos2d.setComponents(x, z); - return destination.setBiome(mPos2d, source.getBiome(mPos2d)); + BlockVector2 bv = mPos2d; + return destination.setBiome( bv, source.getBiome(bv)); } return false; } 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 cdb30b465..767538a6e 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 @@ -1,11 +1,11 @@ package com.boydti.fawe.object.function.block; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; public class CombinedBlockCopy implements RegionFunction { @@ -21,8 +21,9 @@ public class CombinedBlockCopy implements RegionFunction { } @Override - public boolean apply(Vector position) throws WorldEditException { - BlockStateHolder block = source.getBlock(position); + public boolean apply(BlockVector3 position) throws WorldEditException { +// 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/function/block/SimpleBlockCopy.java b/worldedit-core/src/main/java/com/boydti/fawe/object/function/block/SimpleBlockCopy.java index a50c3c2af..9f3e40af5 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/function/block/SimpleBlockCopy.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/function/block/SimpleBlockCopy.java @@ -1,9 +1,9 @@ package com.boydti.fawe.object.function.block; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.math.BlockVector3; public class SimpleBlockCopy implements RegionFunction { @@ -16,7 +16,7 @@ public class SimpleBlockCopy implements RegionFunction { } @Override - public boolean apply(Vector position) throws WorldEditException { - return destination.setBlock(position, source.getBlock(position)); + public boolean apply(BlockVector3 position) throws WorldEditException { + return destination.setBlock(position, source.getFullBlock(position)); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/function/mask/AbstractDelegateMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/function/mask/AbstractDelegateMask.java index 6adcc0a05..fd6e472fe 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/function/mask/AbstractDelegateMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/function/mask/AbstractDelegateMask.java @@ -1,9 +1,10 @@ package com.boydti.fawe.object.function.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.AbstractMask; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; public class AbstractDelegateMask extends AbstractMask { @@ -19,7 +20,7 @@ public class AbstractDelegateMask extends AbstractMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return mask.test(vector); } 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 2eedcd140..89eaea7ea 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 @@ -39,7 +39,7 @@ public class PGZIPOutputStream extends FilterOutputStream { // todo: remove after block guessing is implemented // array list that contains the block sizes - ArrayList blockSizes = new ArrayList(); + ArrayList blockSizes = new ArrayList<>(); private int level = Deflater.DEFAULT_COMPRESSION; private int strategy = Deflater.DEFAULT_STRATEGY; @@ -80,7 +80,7 @@ public class PGZIPOutputStream extends FilterOutputStream { super(out); this.executor = executor; this.nthreads = nthreads; - this.emitQueue = new ArrayBlockingQueue>(nthreads); + this.emitQueue = new ArrayBlockingQueue<>(nthreads); writeHeader(); } @@ -246,4 +246,4 @@ public class PGZIPOutputStream extends FilterOutputStream { // LOG.warn("Already closed."); } } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AdjacentAnyMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AdjacentAnyMask.java index 0996fac9d..b5f384f88 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AdjacentAnyMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AdjacentAnyMask.java @@ -1,9 +1,9 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.AbstractMask; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; /** * Just an optimized version of the Adjacent Mask for single adjacency @@ -11,16 +11,16 @@ import com.sk89q.worldedit.function.mask.Mask; public class AdjacentAnyMask extends AbstractMask implements ResettableMask { private final CachedMask mask; - private transient MutableBlockVector mutable = new MutableBlockVector(); + private transient MutableBlockVector3 mutable = new MutableBlockVector3(); public AdjacentAnyMask(Mask mask) { this.mask = CachedMask.cache(mask); - mutable = new MutableBlockVector(); + mutable = new MutableBlockVector3(); } @Override public void reset() { - mutable = new MutableBlockVector(); + mutable = new MutableBlockVector3(); } public CachedMask getParentMask() { @@ -28,7 +28,7 @@ public class AdjacentAnyMask extends AbstractMask implements ResettableMask { } @Override - public boolean test(Vector v) { + public boolean test(BlockVector3 v) { int x = v.getBlockX(); int y = v.getBlockY(); int z = v.getBlockZ(); @@ -53,28 +53,28 @@ public class AdjacentAnyMask extends AbstractMask implements ResettableMask { return false; } - public Vector direction(Vector v) { + public BlockVector3 direction(BlockVector3 v) { int x = v.getBlockX(); int y = v.getBlockY(); int z = v.getBlockZ(); if (mask.test(x + 1, y, z)) { - return mutable.setComponents(1, 0, 0); - } + mutable.setComponents(1, 0, 0); + }else if (mask.test(x - 1, y, z)) { - return mutable.setComponents(-1, 0, 0); - } + mutable.setComponents(-1, 0, 0); + }else if (mask.test(x, y, z + 1)) { - return mutable.setComponents(0, 0, 1); - } + mutable.setComponents(0, 0, 1); + }else if (mask.test(x, y, z - 1)) { - return mutable.setComponents(0, 0, -1); - } - if (y < 256 && mask.test(x, y + 1, z)) { - return mutable.setComponents(0, 1, 0); - } - if (y > 0 && mask.test(x, y - 1, z)) { - return mutable.setComponents(0, -1, 0); - } - return null; + mutable.setComponents(0, 0, -1); + }else + if (y < 256 && mask.test(x, y + 1, z)) { + mutable.setComponents(0, 1, 0); + }else + if (y > 0 && mask.test(x, y - 1, z)) { + mutable.setComponents(0, -1, 0); + } + return (mutable.getX() == 0 && mutable.getY() == 0 && mutable.getZ() == 0) ? null : mutable; } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AdjacentMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AdjacentMask.java index eca8d4faf..9fa0259b3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AdjacentMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AdjacentMask.java @@ -1,25 +1,29 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.AbstractMask; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; public class AdjacentMask extends AbstractMask { private final int min, max; private final Mask mask; + private MutableBlockVector3 v; public AdjacentMask(Mask mask, int requiredMin, int requiredMax) { this.mask = mask; this.min = requiredMin; this.max = requiredMax; + this.v = new MutableBlockVector3(); } @Override - public boolean test(Vector v) { + public boolean test(BlockVector3 bv) { + v.setComponents(bv); int count = 0; - double x = v.getX(); - double y = v.getY(); - double z = v.getZ(); + double x = bv.getX(); + double y = bv.getY(); + double z = bv.getZ(); v.mutX(x + 1); if (mask.test(v) && ++count == min && max >= 8) { v.mutX(x); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AngleMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AngleMask.java index 872732b8a..b1f00b91c 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AngleMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/AngleMask.java @@ -1,10 +1,11 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.Mask2D; import com.sk89q.worldedit.function.mask.SolidBlockMask; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; + import java.util.Arrays; import javax.annotation.Nullable; @@ -20,7 +21,7 @@ public class AngleMask extends SolidBlockMask implements ResettableMask { protected final int maxY; protected final int distance; - protected transient MutableBlockVector mutable = new MutableBlockVector(); + protected transient MutableBlockVector3 mutable = new MutableBlockVector3(); public AngleMask(Extent extent, double min, double max, boolean overlay, int distance) { super(extent); @@ -35,7 +36,7 @@ public class AngleMask extends SolidBlockMask implements ResettableMask { @Override public void reset() { - mutable = new MutableBlockVector(); + mutable = new MutableBlockVector3(); cacheBotX = Integer.MIN_VALUE; cacheBotZ = Integer.MIN_VALUE; lastX = Integer.MIN_VALUE; @@ -112,7 +113,7 @@ public class AngleMask extends SolidBlockMask implements ResettableMask { } } - public boolean adjacentAir(Vector v) { + public boolean adjacentAir(BlockVector3 v) { int x = v.getBlockX(); int y = v.getBlockY(); int z = v.getBlockZ(); @@ -138,7 +139,7 @@ public class AngleMask extends SolidBlockMask implements ResettableMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { int x = vector.getBlockX(); int y = vector.getBlockY(); int z = vector.getBlockZ(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BiomeMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BiomeMask.java index 424b78823..71aac1181 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BiomeMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BiomeMask.java @@ -1,15 +1,15 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.MutableBlockVector2D; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.AbstractExtentMask; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector2; import com.sk89q.worldedit.world.biome.BaseBiome; public class BiomeMask extends AbstractExtentMask implements ResettableMask { private final BaseBiome biome; - private transient MutableBlockVector2D mutable = new MutableBlockVector2D(); + private transient MutableBlockVector2 mutable = new MutableBlockVector2(); public BiomeMask(Extent extent, BaseBiome biome) { super(extent); @@ -18,12 +18,12 @@ public class BiomeMask extends AbstractExtentMask implements ResettableMask { @Override public void reset() { - mutable = new MutableBlockVector2D(); + mutable = new MutableBlockVector2(); } @Override - public boolean test(Vector vector) { - Vector2D pos = mutable.setComponents(vector.getBlockX(), vector.getBlockZ()); + public boolean test(BlockVector3 vector) { + BlockVector2 pos = mutable.setComponents(vector.getBlockX(), vector.getBlockZ()); return getExtent().getBiome(pos).getId() == biome.getId(); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BlockLightMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BlockLightMask.java index fb217d5b7..dfab059a2 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BlockLightMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BlockLightMask.java @@ -1,10 +1,11 @@ package com.boydti.fawe.object.mask; import com.boydti.fawe.object.extent.LightingExtent; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.AbstractExtentMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; public class BlockLightMask extends AbstractExtentMask { @@ -18,7 +19,7 @@ public class BlockLightMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { Extent extent = getExtent(); if (extent instanceof LightingExtent) { int light = ((LightingExtent) extent).getBlockLight(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ()); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BrightnessMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BrightnessMask.java index 1153aad21..099a47b2f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BrightnessMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/BrightnessMask.java @@ -1,10 +1,11 @@ package com.boydti.fawe.object.mask; import com.boydti.fawe.object.extent.LightingExtent; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.AbstractExtentMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; public class BrightnessMask extends AbstractExtentMask { @@ -18,7 +19,7 @@ public class BrightnessMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { Extent extent = getExtent(); if (extent instanceof LightingExtent) { int light = ((LightingExtent) extent).getBrightness(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ()); 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 05da2402c..9c2160604 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 @@ -2,13 +2,13 @@ package com.boydti.fawe.object.mask; import com.boydti.fawe.object.collection.LocalBlockVectorSet; import com.boydti.fawe.object.function.mask.AbstractDelegateMask; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; public class CachedMask extends AbstractDelegateMask implements ResettableMask { - private transient MutableBlockVector mutable = new MutableBlockVector(); + private transient MutableBlockVector3 mutable = new MutableBlockVector3(); private transient LocalBlockVectorSet cache_checked = new LocalBlockVectorSet(); private transient LocalBlockVectorSet cache_results = new LocalBlockVectorSet(); @@ -27,7 +27,7 @@ public class CachedMask extends AbstractDelegateMask implements ResettableMask { @Override public void reset() { - mutable = new MutableBlockVector(); + mutable = new MutableBlockVector3(); cache_checked = new LocalBlockVectorSet(); cache_results = new LocalBlockVectorSet(); resetCache(); @@ -41,7 +41,7 @@ public class CachedMask extends AbstractDelegateMask implements ResettableMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return test(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ()); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/DataMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/DataMask.java index b0bd2254e..01afbac85 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/DataMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/DataMask.java @@ -1,9 +1,10 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.AbstractExtentMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; public class DataMask extends AbstractExtentMask implements ResettableMask { @@ -15,7 +16,7 @@ public class DataMask extends AbstractExtentMask implements ResettableMask { private transient int data = -1; @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { Extent extent = getExtent(); if (data != -1) { return extent.getLazyBlock(vector).getInternalPropertiesId() == data; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/FaweBlockMatcher.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/FaweBlockMatcher.java index 96925bc58..a2c768b35 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/FaweBlockMatcher.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/FaweBlockMatcher.java @@ -2,7 +2,7 @@ package com.boydti.fawe.object.mask; import com.boydti.fawe.FaweCache; import com.boydti.fawe.object.PseudoRandom; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import java.util.Set; @@ -63,7 +63,6 @@ public abstract class FaweBlockMatcher { // return setBlock(blocks.iterator().next()); // } // final BaseBlock[] array = blocks.toArray(new BaseBlock[blocks.size()]); -// final PseudoRandom random = new PseudoRandom(System.nanoTime()); // final int size = array.length; // return new FaweBlockMatcher() { // @Override diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/IdDataMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/IdDataMask.java index 35d23c15f..7b7705172 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/IdDataMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/IdDataMask.java @@ -1,10 +1,11 @@ package com.boydti.fawe.object.mask; import com.boydti.fawe.FaweCache; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.AbstractExtentMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; public class IdDataMask extends AbstractExtentMask implements ResettableMask { @@ -15,7 +16,7 @@ public class IdDataMask extends AbstractExtentMask implements ResettableMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { Extent extent = getExtent(); if (combined != -1) { return extent.getLazyBlock(vector).getInternalId() == combined; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/IdMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/IdMask.java index 0f8ff0f3b..e9b36b365 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/IdMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/IdMask.java @@ -1,9 +1,10 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.AbstractExtentMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; public class IdMask extends AbstractExtentMask implements ResettableMask { @@ -15,7 +16,7 @@ public class IdMask extends AbstractExtentMask implements ResettableMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { Extent extent = getExtent(); if (id != -1) { return extent.getLazyBlock(vector).getInternalBlockTypeId() == id; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/LightMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/LightMask.java index 703a0b398..1ebbfbce1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/LightMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/LightMask.java @@ -1,10 +1,11 @@ package com.boydti.fawe.object.mask; import com.boydti.fawe.object.extent.LightingExtent; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.AbstractExtentMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; public class LightMask extends AbstractExtentMask { @@ -18,7 +19,7 @@ public class LightMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { if (getExtent() instanceof LightingExtent) { int light = ((LightingExtent) getExtent()).getLight(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ()); return light >= min && light <= max; 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 06d47f22b..8735343fd 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 @@ -21,7 +21,7 @@ public class MaskedTargetBlock extends TargetBlock { Location lastBlock = null; while (getNextBlock() != null) { Location current = getCurrentBlock(); - if (!mask.test(current.toVector())) { + if (!mask.test(current.toBlockPoint())) { if (searchForLastBlock) { lastBlock = current; if (lastBlock.getBlockY() <= 0 || lastBlock.getBlockY() >= world.getMaxY()) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/OpacityMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/OpacityMask.java index a9411a34e..7279b8b1a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/OpacityMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/OpacityMask.java @@ -1,10 +1,11 @@ package com.boydti.fawe.object.mask; import com.boydti.fawe.object.extent.LightingExtent; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.AbstractExtentMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; public class OpacityMask extends AbstractExtentMask { @@ -18,7 +19,7 @@ public class OpacityMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { if (getExtent() instanceof LightingExtent) { int light = ((LightingExtent) getExtent()).getOpacity(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ()); return light >= min && light <= max; 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 011b3ce7d..f0f9c3fe1 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 @@ -1,8 +1,9 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.AbstractMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; /** @@ -14,7 +15,7 @@ public class PlaneMask extends AbstractMask implements ResettableMask { private transient int originX = Integer.MAX_VALUE, originY = Integer.MAX_VALUE, originZ = Integer.MAX_VALUE; @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { switch (mode) { case -1: originX = vector.getBlockX(); 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 e7b791e18..5759aabba 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 @@ -1,14 +1,14 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.AbstractMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; public class RadiusMask extends AbstractMask implements ResettableMask { - private transient Vector pos; + private transient BlockVector3 pos; private final int minSqr, maxSqr; public RadiusMask(int min, int max) { @@ -22,9 +22,9 @@ public class RadiusMask extends AbstractMask implements ResettableMask { } @Override - public boolean test(Vector to) { + public boolean test(BlockVector3 to) { if (pos == null) { - pos = new MutableBlockVector(to); + pos = to; } int dx = pos.getBlockX() - to.getBlockX(); int d = dx * dx; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/RandomMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/RandomMask.java index e7cf15492..265184db9 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/RandomMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/RandomMask.java @@ -1,7 +1,8 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.AbstractMask; +import com.sk89q.worldedit.math.BlockVector3; + import java.util.SplittableRandom; public class RandomMask extends AbstractMask implements ResettableMask { @@ -14,7 +15,7 @@ public class RandomMask extends AbstractMask implements ResettableMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return random.nextInt() <= threshold; } 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 ea62394ae..9358552ca 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 @@ -1,8 +1,8 @@ package com.boydti.fawe.object.mask; import com.boydti.fawe.object.random.SimplexNoise; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.AbstractMask; +import com.sk89q.worldedit.math.BlockVector3; public class SimplexMask extends AbstractMask { private final double min, max, scale; @@ -14,7 +14,7 @@ public class SimplexMask extends AbstractMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { double value = SimplexNoise.noise(vector.getBlockX() * scale, vector.getBlockY() * scale, vector.getBlockZ() * scale); return value >= min && value <= max; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SkyLightMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SkyLightMask.java index dbb2985d5..8b796d3ac 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SkyLightMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SkyLightMask.java @@ -1,10 +1,11 @@ package com.boydti.fawe.object.mask; import com.boydti.fawe.object.extent.LightingExtent; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.AbstractExtentMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; public class SkyLightMask extends AbstractExtentMask { @@ -18,7 +19,7 @@ public class SkyLightMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { if (getExtent() instanceof LightingExtent) { int light = ((LightingExtent) getExtent()).getSkyLight(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ()); return light >= min && light <= max; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SolidPlaneMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SolidPlaneMask.java index 4baeb9a2d..04baace03 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SolidPlaneMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SolidPlaneMask.java @@ -1,10 +1,11 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.Mask2D; import com.sk89q.worldedit.function.mask.SolidBlockMask; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; + import javax.annotation.Nullable; /** @@ -13,7 +14,7 @@ import javax.annotation.Nullable; public class SolidPlaneMask extends SolidBlockMask implements ResettableMask { private transient int mode = -1; - private transient MutableBlockVector mutable = new MutableBlockVector(); + private transient MutableBlockVector3 mutable = new MutableBlockVector3(); private int originX = Integer.MAX_VALUE, originY = Integer.MAX_VALUE, originZ = Integer.MAX_VALUE; @@ -22,7 +23,7 @@ public class SolidPlaneMask extends SolidBlockMask implements ResettableMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { switch (mode) { case -1: if (!super.test(vector)) { @@ -84,7 +85,7 @@ public class SolidPlaneMask extends SolidBlockMask implements ResettableMask { @Override public void reset() { mode = -1; - mutable = new MutableBlockVector(); + mutable = new MutableBlockVector3(); } @Nullable diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SurfaceMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SurfaceMask.java index 5330d8ceb..cd740f93f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SurfaceMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/SurfaceMask.java @@ -1,9 +1,9 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.BlockMaskBuilder; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockTypes; public class SurfaceMask extends AdjacentAnyMask { @@ -22,7 +22,7 @@ public class SurfaceMask extends AdjacentAnyMask { } @Override - public boolean test(Vector v) { + public boolean test(BlockVector3 v) { return !getParentMask().test(v.getBlockX(), v.getBlockY(), v.getBlockZ()) && super.test(v); } } \ No newline at end of file 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 5975be2d5..7e5d84f03 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 @@ -1,21 +1,25 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.AbstractMask; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; public class WallMask extends AbstractMask { private final int min, max; private final Mask mask; + private MutableBlockVector3 v; public WallMask(Mask mask, int requiredMin, int requiredMax) { this.mask = mask; this.min = requiredMin; this.max = requiredMax; + this.v = new MutableBlockVector3(); } @Override - public boolean test(Vector v) { + public boolean test(BlockVector3 bv) { + v.setComponents(bv); int count = 0; double x = v.getX(); double y = v.getY(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/XAxisMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/XAxisMask.java index b74b970b6..44e1a3263 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/XAxisMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/XAxisMask.java @@ -1,8 +1,9 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.AbstractMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; /** @@ -13,7 +14,7 @@ public class XAxisMask extends AbstractMask implements ResettableMask { private transient int layer = -1; @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { if (layer == -1) { layer = vector.getBlockX(); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/YAxisMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/YAxisMask.java index cd4746363..2d333cb5f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/YAxisMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/YAxisMask.java @@ -1,8 +1,9 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.AbstractMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; /** @@ -13,7 +14,7 @@ public class YAxisMask extends AbstractMask implements ResettableMask { private transient int layer = -1; @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { if (layer == -1) { layer = vector.getBlockY(); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ZAxisMask.java b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ZAxisMask.java index 15215e157..15dd3cb36 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ZAxisMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/mask/ZAxisMask.java @@ -1,8 +1,9 @@ package com.boydti.fawe.object.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.mask.AbstractMask; import com.sk89q.worldedit.function.mask.Mask2D; +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; /** @@ -13,7 +14,7 @@ public class ZAxisMask extends AbstractMask implements ResettableMask { private transient int layer = -1; @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { if (layer == -1) { layer = vector.getBlockZ(); } 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 d377a706c..f11fc4896 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 @@ -4,11 +4,11 @@ import com.boydti.fawe.Fawe; import com.boydti.fawe.FaweCache; import com.boydti.fawe.object.DataAnglePattern; import com.boydti.fawe.util.TextureHolder; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; @@ -32,18 +32,18 @@ public class AngleColorPattern extends DataAnglePattern { } @Override - public BlockStateHolder apply(Vector position) { - BlockStateHolder block = extent.getBlock(position); + public BaseBlock apply(BlockVector3 position) { + BaseBlock block = extent.getFullBlock(position); int slope = getSlope(block, position); if (slope == -1) return block; int color = util.getTextureUtil().getColor(block.getBlockType()); if (color == 0) return block; int newColor = getColor(color, slope); - return util.getTextureUtil().getNearestBlock(newColor).getDefaultState(); + return util.getTextureUtil().getNearestBlock(newColor).getDefaultState().toBaseBlock(); } @Override - public int getSlope(BlockStateHolder block, Vector vector) { + public int getSlope(BlockStateHolder block, BlockVector3 vector) { int slope = super.getSlope(block, vector); if (slope != -1) { int x = vector.getBlockX(); @@ -61,7 +61,7 @@ public class AngleColorPattern extends DataAnglePattern { } @Override - public boolean apply(Extent extent, Vector setPosition, Vector getPosition) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { BlockStateHolder block = extent.getBlock(getPosition); int slope = getSlope(block, getPosition); if (slope == -1) return false; 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 fee5e8187..bb8395a8c 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 @@ -3,11 +3,11 @@ package com.boydti.fawe.object.pattern; import com.boydti.fawe.Fawe; import com.boydti.fawe.util.TextureHolder; import com.boydti.fawe.util.TextureUtil; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; @@ -26,16 +26,16 @@ public class AverageColorPattern extends AbstractExtentPattern { } @Override - public BlockStateHolder apply(Vector position) { - BlockStateHolder block = getExtent().getBlock(position); + public BaseBlock apply(BlockVector3 position) { + BaseBlock block = getExtent().getFullBlock(position); TextureUtil util = holder.getTextureUtil(); int currentColor = util.getColor(block.getBlockType()); int newColor = util.averageColor(currentColor, color); - return util.getNearestBlock(newColor).getDefaultState(); + return util.getNearestBlock(newColor).getDefaultState().toBaseBlock(); } @Override - public boolean apply(Extent extent, Vector setPosition, Vector getPosition) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { BlockType blockType = extent.getBlockType(getPosition); TextureUtil util = holder.getTextureUtil(); int currentColor = util.getColor(blockType); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BiomePattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BiomePattern.java index dbfbf85bd..f62926afc 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BiomePattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BiomePattern.java @@ -1,16 +1,16 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.MutableBlockVector2D; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector2; import com.sk89q.worldedit.world.biome.BaseBiome; import java.io.IOException; public class BiomePattern extends ExistingPattern { - private transient MutableBlockVector2D mutable = new MutableBlockVector2D(); + private transient MutableBlockVector2 mutable = new MutableBlockVector2(); private final BaseBiome biome; public BiomePattern(Extent extent, BaseBiome biome) { @@ -19,12 +19,12 @@ public class BiomePattern extends ExistingPattern { } @Override - public BaseBlock apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { throw new BiomePatternException(); } @Override - public boolean apply(Extent extent, Vector set, Vector getPosition) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 getPosition) throws WorldEditException { return extent.setBiome(set.getBlockX(), set.getBlockY(), set.getBlockZ(), biome); } @@ -48,6 +48,6 @@ public class BiomePattern extends ExistingPattern { private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - mutable = new MutableBlockVector2D(); + mutable = new MutableBlockVector2(); } } 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 bb0a9900e..a9b9a5148 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 @@ -4,13 +4,13 @@ import com.boydti.fawe.Fawe; import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.collection.LocalBlockVectorSet; import com.boydti.fawe.util.FaweTimer; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import java.io.IOException; @@ -33,12 +33,12 @@ public class BufferedPattern extends AbstractPattern implements ResettablePatter } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { return pattern.apply(position); } @Override - public boolean apply(Extent extent, Vector setPosition, Vector getPosition) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { long now = timer.getTick(); try { if (!set(setPosition)) { @@ -50,7 +50,7 @@ public class BufferedPattern extends AbstractPattern implements ResettablePatter return false; } - public boolean set(Vector pos) { + public boolean set(BlockVector3 pos) { return set.add(pos); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BufferedPattern2D.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BufferedPattern2D.java index 359388c1c..154538ee4 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BufferedPattern2D.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/BufferedPattern2D.java @@ -1,8 +1,8 @@ package com.boydti.fawe.object.pattern; import com.boydti.fawe.object.FawePlayer; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; public class BufferedPattern2D extends BufferedPattern { @@ -11,7 +11,7 @@ public class BufferedPattern2D extends BufferedPattern { } @Override - public boolean set(Vector pos) { + public boolean set(BlockVector3 pos) { return set.add(pos.getBlockX(), 0, pos.getBlockY()); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/DataPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/DataPattern.java index 609696538..30c7d85f4 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/DataPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/DataPattern.java @@ -1,11 +1,11 @@ package com.boydti.fawe.object.pattern; import com.boydti.fawe.FaweCache; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; @@ -22,9 +22,9 @@ public class DataPattern extends AbstractExtentPattern { } @Override - public BlockStateHolder apply(Vector position) { - BlockStateHolder oldBlock = getExtent().getBlock(position); - BlockStateHolder newBlock = pattern.apply(position); - return oldBlock.withPropertyId(newBlock.getInternalPropertiesId()); + public BaseBlock apply(BlockVector3 position) { + BaseBlock oldBlock = getExtent().getFullBlock(position); + BaseBlock newBlock = pattern.apply(position); + return oldBlock.withPropertyId(newBlock.getInternalPropertiesId()).toBaseBlock(); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/DesaturatePattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/DesaturatePattern.java index 3b18e4056..1647b3662 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/DesaturatePattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/DesaturatePattern.java @@ -3,12 +3,12 @@ package com.boydti.fawe.object.pattern; import com.boydti.fawe.Fawe; import com.boydti.fawe.util.TextureHolder; import com.boydti.fawe.util.TextureUtil; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; @@ -26,7 +26,7 @@ public class DesaturatePattern extends AbstractPattern { } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { BlockType block = extent.getBlockType(position); TextureUtil util = holder.getTextureUtil(); int color = util.getColor(block); @@ -39,11 +39,11 @@ public class DesaturatePattern extends AbstractPattern { int green = (int) (g + value * (l - g)); int blue = (int) (b + value * (l - b)); int newColor = (alpha << 24) + (red << 16) + (green << 8) + (blue << 0); - return util.getNearestBlock(newColor).getDefaultState(); + return util.getNearestBlock(newColor).getDefaultState().toBaseBlock(); } @Override - public boolean apply(Extent extent, Vector setPosition, Vector getPosition) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { BlockType block = extent.getBlockType(getPosition); TextureUtil util = holder.getTextureUtil(); int color = util.getColor(block); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ExistingPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ExistingPattern.java index 2acb45d6c..e345a1705 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ExistingPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ExistingPattern.java @@ -1,10 +1,10 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; @@ -14,12 +14,12 @@ public class ExistingPattern extends AbstractExtentPattern { } @Override - public BlockStateHolder apply(Vector position) { - return getExtent().getBlock(position); + public BaseBlock apply(BlockVector3 position) { + return getExtent().getFullBlock(position); } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { if (set.equals(get)) { return false; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ExpressionPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ExpressionPattern.java index 8109513c8..c023f4ff3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ExpressionPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ExpressionPattern.java @@ -1,12 +1,13 @@ package com.boydti.fawe.object.pattern; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.ExpressionException; import com.sk89q.worldedit.internal.expression.runtime.EvaluationException; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -49,16 +50,16 @@ public class ExpressionPattern extends AbstractPattern { } @Override - public BlockStateHolder apply(Vector vector) { + public BaseBlock apply(BlockVector3 vector) { try { if (expression.getEnvironment() instanceof WorldEditExpressionEnvironment) { - ((WorldEditExpressionEnvironment) expression.getEnvironment()).setCurrentBlock(vector); + ((WorldEditExpressionEnvironment) expression.getEnvironment()).setCurrentBlock(vector.toVector3()); } double combined = expression.evaluate(vector.getX(), vector.getY(), vector.getZ()); - return BlockState.getFromInternalId((int) combined); + return BlockState.getFromInternalId((int) combined).toBaseBlock(); } catch (EvaluationException e) { e.printStackTrace(); - return EditSession.nullBlock; + return EditSession.nullBlock.toBaseBlock(); } catch (Throwable e) { e.printStackTrace(); throw e; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/FullClipboardPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/FullClipboardPattern.java index c90284863..015eb990d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/FullClipboardPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/FullClipboardPattern.java @@ -1,15 +1,15 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.mask.ExistingBlockMask; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operations; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.regions.Region; import java.io.IOException; import java.io.NotSerializableException; @@ -22,7 +22,7 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class FullClipboardPattern extends AbstractExtentPattern { private final Clipboard clipboard; - private final MutableBlockVector mutable = new MutableBlockVector(); + private final MutableBlockVector3 mutable = new MutableBlockVector3(); /** * Create a new clipboard pattern. @@ -36,7 +36,7 @@ public class FullClipboardPattern extends AbstractExtentPattern { } @Override - public boolean apply(Extent extent, Vector setPosition, Vector getPosition) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { Region region = clipboard.getRegion(); ForwardExtentCopy copy = new ForwardExtentCopy(clipboard, clipboard.getRegion(), clipboard.getOrigin(), extent, setPosition); copy.setSourceMask(new ExistingBlockMask(clipboard)); @@ -45,7 +45,7 @@ public class FullClipboardPattern extends AbstractExtentPattern { } @Override - public BaseBlock apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { throw new IllegalStateException("Incorrect use. This pattern can only be applied to an extent!"); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/IdDataMaskPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/IdDataMaskPattern.java index e1b52d3a4..2ad33fe3a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/IdDataMaskPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/IdDataMaskPattern.java @@ -1,11 +1,11 @@ package com.boydti.fawe.object.pattern; import com.boydti.fawe.FaweCache; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; @@ -21,11 +21,11 @@ public class IdDataMaskPattern extends AbstractExtentPattern { } @Override - public BlockStateHolder apply(Vector position) { - BlockStateHolder oldBlock = getExtent().getBlock(position); - BlockStateHolder newBlock = pattern.apply(position); + public BaseBlock apply(BlockVector3 position) { + BaseBlock oldBlock = getExtent().getFullBlock(position); + BaseBlock newBlock = pattern.apply(position); int oldData = oldBlock.getInternalPropertiesId(); int newData = newBlock.getInternalPropertiesId() + oldData - (oldData & bitMask); - return newBlock.withPropertyId(newData); + return newBlock.withPropertyId(newData).toBaseBlock(); } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/IdPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/IdPattern.java index 9634eb862..9b05385d9 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/IdPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/IdPattern.java @@ -1,8 +1,9 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockStateHolder; import static com.google.common.base.Preconditions.checkNotNull; @@ -17,9 +18,9 @@ public class IdPattern extends AbstractExtentPattern { } @Override - public BlockStateHolder apply(Vector position) { - BlockStateHolder oldBlock = getExtent().getBlock(position); - BlockStateHolder newBlock = pattern.apply(position); - return newBlock.withPropertyId(oldBlock.getInternalPropertiesId()); + public BaseBlock apply(BlockVector3 position) { + BaseBlock oldBlock = getExtent().getFullBlock(position); + BaseBlock newBlock = pattern.apply(position); + return newBlock.withPropertyId(oldBlock.getInternalPropertiesId()).toBaseBlock(); } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/Linear2DBlockPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/Linear2DBlockPattern.java index e8610191a..2e2826525 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/Linear2DBlockPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/Linear2DBlockPattern.java @@ -1,12 +1,12 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; public class Linear2DBlockPattern extends AbstractPattern { @@ -18,7 +18,7 @@ public class Linear2DBlockPattern extends AbstractPattern { } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { int index = (position.getBlockX() + position.getBlockZ()) % patternsArray.length; if (index < 0) { index += patternsArray.length; @@ -27,7 +27,7 @@ public class Linear2DBlockPattern extends AbstractPattern { } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { int index = (get.getBlockX() + get.getBlockZ()) % patternsArray.length; if (index < 0) { index += patternsArray.length; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/Linear3DBlockPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/Linear3DBlockPattern.java index d9332a994..c52c349e9 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/Linear3DBlockPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/Linear3DBlockPattern.java @@ -1,12 +1,12 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; public class Linear3DBlockPattern extends AbstractPattern { @@ -18,7 +18,7 @@ public class Linear3DBlockPattern extends AbstractPattern { } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { int index = (position.getBlockX() + position.getBlockY() + position.getBlockZ()) % patternsArray.length; if (index < 0) { index += patternsArray.length; @@ -27,7 +27,7 @@ public class Linear3DBlockPattern extends AbstractPattern { } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { int index = (get.getBlockX() + get.getBlockY() + get.getBlockZ()) % patternsArray.length; if (index < 0) { index += patternsArray.length; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/LinearBlockPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/LinearBlockPattern.java index 65e94e68d..2614dde7a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/LinearBlockPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/LinearBlockPattern.java @@ -1,12 +1,12 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; public class LinearBlockPattern extends AbstractPattern implements ResettablePattern { @@ -19,7 +19,7 @@ public class LinearBlockPattern extends AbstractPattern implements ResettablePat } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { if (index == patternsArray.length) { index = 0; } @@ -27,7 +27,7 @@ public class LinearBlockPattern extends AbstractPattern implements ResettablePat } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { if (index == patternsArray.length) { index = 0; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/MaskedPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/MaskedPattern.java index 6f2712685..8f9f72550 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/MaskedPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/MaskedPattern.java @@ -1,13 +1,13 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; public class MaskedPattern extends AbstractPattern { @@ -24,16 +24,16 @@ public class MaskedPattern extends AbstractPattern { @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { patternExtent.setTarget(position); if (mask.test(position)) { - return patternExtent.getAndResetTarget(); + return patternExtent.getAndResetTarget().toBaseBlock(); } return secondaryPattern.apply(position); } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { patternExtent.setTarget(get); if (mask.test(get)) { return patternExtent.getAndResetTarget(extent, set, get); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoXPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoXPattern.java index 4147a90fb..3accfc1e9 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoXPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoXPattern.java @@ -1,13 +1,13 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import java.io.IOException; @@ -15,28 +15,29 @@ import java.io.IOException; public class NoXPattern extends AbstractPattern { private final Pattern pattern; - private transient MutableBlockVector mutable = new MutableBlockVector(); +// private transient MutableBlockVector3 mutable = new MutableBlockVector3(); public NoXPattern(Pattern pattern) { this.pattern = pattern; } @Override - public BlockStateHolder apply(Vector pos) { - mutable.mutY((pos.getY())); - mutable.mutZ((pos.getZ())); - return pattern.apply(mutable); + public BaseBlock apply(BlockVector3 pos) { +// mutable.mutY((pos.getY())); +// mutable.mutZ((pos.getZ())); +// return pattern.apply(mutable); + return pattern.apply(pos); } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { - mutable.mutY((get.getY())); - mutable.mutZ((get.getZ())); - return pattern.apply(extent, set, mutable); + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { +// mutable.mutY((get.getY())); +// mutable.mutZ((get.getZ())); + return pattern.apply(extent, set, get); } private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - mutable = new MutableBlockVector(); +// mutable = new MutableBlockVector3(); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoYPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoYPattern.java index 38caadf7a..6c8303cff 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoYPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoYPattern.java @@ -1,13 +1,13 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import java.io.IOException; @@ -20,24 +20,24 @@ public class NoYPattern extends AbstractPattern { this.pattern = pattern; } - private transient MutableBlockVector mutable = new MutableBlockVector(); +// private transient MutableBlockVector3 mutable = new MutableBlockVector3(); @Override - public BlockStateHolder apply(Vector pos) { - mutable.mutX((pos.getX())); - mutable.mutZ((pos.getZ())); - return pattern.apply(mutable); + public BaseBlock apply(BlockVector3 pos) { +// mutable.mutX((pos.getX())); +// mutable.mutZ((pos.getZ())); + return pattern.apply(pos); } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { - mutable.mutX((get.getX())); - mutable.mutZ((get.getZ())); - return pattern.apply(extent, set, mutable); + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { +// mutable.mutX((get.getX())); +// mutable.mutZ((get.getZ())); + return pattern.apply(extent, set, get); } private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - mutable = new MutableBlockVector(); +// mutable = new MutableBlockVector3(); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoZPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoZPattern.java index e81f9a5a1..2a4e3f362 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoZPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/NoZPattern.java @@ -1,13 +1,13 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import java.io.IOException; @@ -20,24 +20,24 @@ public class NoZPattern extends AbstractPattern { this.pattern = pattern; } - private transient MutableBlockVector mutable = new MutableBlockVector(); +// private transient MutableBlockVector3 mutable = new MutableBlockVector3(); @Override - public BlockStateHolder apply(Vector pos) { - mutable.mutX((pos.getX())); - mutable.mutY((pos.getY())); - return pattern.apply(mutable); + public BaseBlock apply(BlockVector3 pos) { +// mutable.mutX((pos.getX())); +// mutable.mutY((pos.getY())); + return pattern.apply(pos); } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { - mutable.mutX((get.getX())); - mutable.mutY((get.getY())); - return pattern.apply(extent, set, mutable); + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { +// mutable.mutX((get.getX())); +// mutable.mutY((get.getY())); + return pattern.apply(extent, set, get); } private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - mutable = new MutableBlockVector(); +// mutable = new MutableBlockVector3(); } } 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 5886f35d8..fd34ba1eb 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 @@ -1,13 +1,13 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import java.io.IOException; @@ -15,7 +15,7 @@ import java.io.IOException; public class OffsetPattern extends AbstractPattern { private final int dx, dy, dz; - private transient MutableBlockVector mutable = new MutableBlockVector(); +// private transient MutableBlockVector3 mutable = new MutableBlockVector3(); private final Pattern pattern; public OffsetPattern(Pattern pattern, int dx, int dy, int dz) { @@ -26,23 +26,25 @@ public class OffsetPattern extends AbstractPattern { } @Override - public BlockStateHolder apply(Vector position) { - mutable.mutX((position.getX() + dx)); - mutable.mutY((position.getY() + dy)); - mutable.mutZ((position.getZ() + dz)); - return pattern.apply(mutable); + public BaseBlock apply(BlockVector3 position) { +// mutable.mutX((position.getX() + dx)); +// mutable.mutY((position.getY() + dy)); +// mutable.mutZ((position.getZ() + dz)); +// return pattern.apply(mutable); + return pattern.apply(BlockVector3.at(position.getX() + dx, position.getY() + dy, position.getZ() + dz)); } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { - mutable.mutX((get.getX() + dx)); - mutable.mutY((get.getY() + dy)); - mutable.mutZ((get.getZ() + dz)); - return pattern.apply(extent, set, mutable); + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { +// mutable.mutX((get.getX() + dx)); +// mutable.mutY((get.getY() + dy)); +// mutable.mutZ((get.getZ() + dz)); +// return pattern.apply(extent, set, mutable); + return pattern.apply(extent, set, BlockVector3.at(get.getX() + dx, get.getY() + dy, get.getZ() + dz)); } private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - mutable = new MutableBlockVector(); +// mutable = new MutableBlockVector3(); } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PatternExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PatternExtent.java index 31a8369e1..90fe4bde8 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PatternExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/PatternExtent.java @@ -1,9 +1,7 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; @@ -11,6 +9,8 @@ import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; @@ -24,7 +24,7 @@ import javax.annotation.Nullable; public class PatternExtent extends AbstractPattern implements Extent { private final Pattern pattern; private transient BlockStateHolder block; - private transient Vector target = new Vector(); + private transient BlockVector3 target = BlockVector3.at(0, 0, 0); public PatternExtent(Pattern pattern) { this.pattern = pattern; @@ -32,17 +32,17 @@ public class PatternExtent extends AbstractPattern implements Extent { private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - target = new Vector(); + target = BlockVector3.at(0, 0, 0); } @Override - public Vector getMinimumPoint() { - return new Vector(Integer.MIN_VALUE, 0, Integer.MIN_VALUE); + public BlockVector3 getMinimumPoint() { + return BlockVector3.at(Integer.MIN_VALUE, 0, Integer.MIN_VALUE); } @Override - public Vector getMaximumPoint() { - return new Vector(Integer.MAX_VALUE, 255, Integer.MAX_VALUE); + public BlockVector3 getMaximumPoint() { + return BlockVector3.at(Integer.MAX_VALUE, 255, Integer.MAX_VALUE); } @Override @@ -62,7 +62,7 @@ public class PatternExtent extends AbstractPattern implements Extent { } @Override - public BlockState getBlock(Vector position) { + public BlockState getBlock(BlockVector3 position) { BlockStateHolder tmp = pattern.apply(position); if (position == target || (position.getX() == target.getX() && position.getY() == target.getY() && position.getZ() == target.getZ())) { block = tmp; @@ -72,11 +72,11 @@ public class PatternExtent extends AbstractPattern implements Extent { return (BlockState) tmp; } - public void setTarget(Vector vector) { + public void setTarget(BlockVector3 vector) { this.target = vector; } - public boolean getAndResetTarget(Extent extent, Vector set, Vector get) throws WorldEditException { + public boolean getAndResetTarget(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { BlockStateHolder result = block; if (result != null) { block = null; @@ -97,22 +97,22 @@ public class PatternExtent extends AbstractPattern implements Extent { } @Override - public BlockState getFullBlock(Vector position) { - return getBlock(position); + public BaseBlock getFullBlock(BlockVector3 position) { + return getBlock(position).toBaseBlock(); } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return new BaseBiome(0); } @Override - public boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 position, BlockStateHolder block) throws WorldEditException { return false; } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return false; } @@ -123,12 +123,12 @@ public class PatternExtent extends AbstractPattern implements Extent { } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { return pattern.apply(position); } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { return pattern.apply(extent, set, get); } } 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 2a0888640..def48ef7c 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 @@ -4,14 +4,15 @@ import com.boydti.fawe.object.string.MutableCharSequence; import com.boydti.fawe.util.MathMan; import com.boydti.fawe.util.StringMan; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.registry.state.AbstractProperty; import com.sk89q.worldedit.registry.state.IntegerProperty; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.registry.state.PropertyKey; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; @@ -61,7 +62,7 @@ public class PropertyPattern extends AbstractExtentPattern { } } - private void add(BlockTypes type, PropertyKey key, Operator operator, MutableCharSequence value, boolean wrap) { + private void add(BlockType type, PropertyKey key, Operator operator, MutableCharSequence value, boolean wrap) { if (!type.hasProperty(key)) return; AbstractProperty property = (AbstractProperty) type.getProperty(key); BlockState defaultState = type.getDefaultState(); @@ -128,14 +129,14 @@ public class PropertyPattern extends AbstractExtentPattern { charSequence.setString(input); charSequence.setSubstring(0, propStart); - BlockTypes type = null; - List blockTypeList = null; + BlockType type = null; + List blockTypeList = null; if (StringMan.isAlphanumericUnd(charSequence)) { type = BlockTypes.get(charSequence); } else { String regex = charSequence.toString(); blockTypeList = new ArrayList<>(); - for (BlockTypes myType : BlockTypes.values) { + for (BlockType myType : BlockTypes.values) { if (myType.getId().matches(regex)) { blockTypeList.add(myType); } @@ -163,7 +164,7 @@ public class PropertyPattern extends AbstractExtentPattern { char firstChar = input.charAt(last + 1); if (type != null) add(type, key, operator, charSequence, wrap); else { - for (BlockTypes myType : blockTypeList) { + for (BlockType myType : blockTypeList) { add(myType, key, operator, charSequence, wrap); } } @@ -191,25 +192,25 @@ public class PropertyPattern extends AbstractExtentPattern { } @Override - public BlockStateHolder apply(Vector position) { - BlockState block = getExtent().getBlock(position); + public BaseBlock apply(BlockVector3 position) { + BaseBlock block = getExtent().getFullBlock(position); return apply(block, block); } - public BlockState apply(BlockState block, BlockState orDefault) { + public BaseBlock apply(BaseBlock block, BaseBlock orDefault) { int ordinal = block.getOrdinal(); int newOrdinal = transformed[ordinal]; if (newOrdinal != ordinal) { CompoundTag nbt = block.getNbtData(); BlockState newState = BlockState.getFromOrdinal(newOrdinal); - return nbt != null ? new BaseBlock(newState, nbt) : newState; + return nbt != null ? new BaseBlock(newState, nbt) : newState.toBaseBlock(); } return orDefault; } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { - BlockState block = getExtent().getBlock(get); + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { + BaseBlock block = getExtent().getFullBlock(get); block = apply(block, null); if (block != null) { return extent.setBlock(set, block); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomFullClipboardPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomFullClipboardPattern.java index 4a0059635..36c3eb08c 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomFullClipboardPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RandomFullClipboardPattern.java @@ -2,14 +2,15 @@ package com.boydti.fawe.object.pattern; import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.schematic.Schematic; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.pattern.AbstractPattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.session.ClipboardHolder; @@ -22,7 +23,7 @@ import static com.google.common.base.Preconditions.checkNotNull; public class RandomFullClipboardPattern extends AbstractPattern { private final Extent extent; - private final MutableBlockVector mutable = new MutableBlockVector(); + private final MutableBlockVector3 mutable = new MutableBlockVector3(); private final List clipboards; private boolean randomRotate; private boolean randomFlip; @@ -35,7 +36,7 @@ public class RandomFullClipboardPattern extends AbstractPattern { } @Override - public boolean apply(Extent extent, Vector setPosition, Vector getPosition) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { ClipboardHolder holder = clipboards.get(PseudoRandom.random.random(clipboards.size())); AffineTransform transform = new AffineTransform(); if (randomRotate) { @@ -43,7 +44,7 @@ public class RandomFullClipboardPattern extends AbstractPattern { holder.setTransform(new AffineTransform().rotateY(PseudoRandom.random.random(4) * 90)); } if (randomFlip) { - transform = transform.scale(new Vector(1, 0, 0).multiply(-2).add(1, 1, 1)); + transform = transform.scale(Vector3.at(1, 0, 0).multiply(-2).add(1, 1, 1)); } if (!transform.isIdentity()) { holder.setTransform(transform); @@ -60,7 +61,7 @@ public class RandomFullClipboardPattern extends AbstractPattern { } @Override - public BaseBlock apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { throw new IllegalStateException("Incorrect use. This pattern can only be applied to an extent!"); } 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 b292a9351..904364739 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 @@ -1,14 +1,12 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import java.io.IOException; import java.util.SplittableRandom; @@ -18,7 +16,7 @@ public class RandomOffsetPattern extends AbstractPattern { private final Pattern pattern; private transient int dx2, dy2, dz2; - private transient MutableBlockVector mutable = new MutableBlockVector(); + private transient MutableBlockVector3 mutable = new MutableBlockVector3(); private transient SplittableRandom r; public RandomOffsetPattern(Pattern pattern, int dx, int dy, int dz) { @@ -34,7 +32,7 @@ public class RandomOffsetPattern extends AbstractPattern { } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { mutable.mutX((position.getX() + r.nextInt(dx2) - dx)); mutable.mutY((position.getY() + r.nextInt(dy2) - dy)); mutable.mutZ((position.getZ() + r.nextInt(dz2) - dz)); @@ -42,7 +40,7 @@ public class RandomOffsetPattern extends AbstractPattern { } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { mutable.mutX((get.getX() + r.nextInt(dx2) - dx)); mutable.mutY((get.getY() + r.nextInt(dy2) - dy)); mutable.mutZ((get.getZ() + r.nextInt(dz2) - dz)); @@ -55,6 +53,6 @@ public class RandomOffsetPattern extends AbstractPattern { this.dy2 = dy * 2 + 1; this.dz2 = dz * 2 + 1; this.r = new SplittableRandom(); - this.mutable = new MutableBlockVector(); + this.mutable = new MutableBlockVector3(); } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RelativePattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RelativePattern.java index db7a8d786..e8f3f56ea 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RelativePattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/RelativePattern.java @@ -1,31 +1,29 @@ package com.boydti.fawe.object.pattern; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import java.io.IOException; public class RelativePattern extends AbstractPattern implements ResettablePattern { private final Pattern pattern; - private transient Vector origin; - private transient MutableBlockVector mutable = new MutableBlockVector(); + private transient BlockVector3 origin; + private transient MutableBlockVector3 mutable = new MutableBlockVector3(); public RelativePattern(Pattern pattern) { this.pattern = pattern; } @Override - public BlockStateHolder apply(Vector pos) { + public BaseBlock apply(BlockVector3 pos) { if (origin == null) { - origin = new Vector(pos); + origin = pos; } mutable.mutX((pos.getX() - origin.getX())); mutable.mutY((pos.getY() - origin.getY())); @@ -34,9 +32,9 @@ public class RelativePattern extends AbstractPattern implements ResettablePatter } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { if (origin == null) { - origin = new Vector(get); + origin = get; } mutable.mutX((get.getX() - origin.getX())); mutable.mutY((get.getY() - origin.getY())); @@ -46,7 +44,7 @@ public class RelativePattern extends AbstractPattern implements ResettablePatter private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - mutable = new MutableBlockVector(); + mutable = new MutableBlockVector3(); } @Override 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 ea5208de6..5499b1507 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 @@ -3,12 +3,12 @@ package com.boydti.fawe.object.pattern; import com.boydti.fawe.Fawe; import com.boydti.fawe.util.TextureHolder; import com.boydti.fawe.util.TextureUtil; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; @@ -28,16 +28,16 @@ public class SaturatePattern extends AbstractPattern { } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { BlockType block = extent.getBlockType(position); TextureUtil util = holder.getTextureUtil(); int currentColor = util.getColor(block); int newColor = util.multiplyColor(currentColor, color); - return util.getNearestBlock(newColor).getDefaultState(); + return util.getNearestBlock(newColor).getDefaultState().toBaseBlock(); } @Override - public boolean apply(Extent extent, Vector setPosition, Vector getPosition) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { BlockType block = extent.getBlockType(getPosition); TextureUtil util = holder.getTextureUtil(); int currentColor = util.getColor(block); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ShadePattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ShadePattern.java index e68cbb6a4..5c8a910f2 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ShadePattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/ShadePattern.java @@ -2,11 +2,11 @@ package com.boydti.fawe.object.pattern; import com.boydti.fawe.Fawe; import com.boydti.fawe.util.TextureUtil; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.pattern.AbstractPattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; @@ -28,9 +28,9 @@ public class ShadePattern extends AbstractPattern { } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { BlockType block = extent.getBlockType(position); - return (darken ? util.getDarkerBlock(block) : util.getLighterBlock(block)).getDefaultState(); + return (darken ? util.getDarkerBlock(block) : util.getLighterBlock(block)).getDefaultState().toBaseBlock(); } private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { 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 b0589232e..3ac516bc7 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 @@ -1,16 +1,13 @@ package com.boydti.fawe.object.pattern; -import com.boydti.fawe.FaweCache; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.blocks.BlockType; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.SolidBlockMask; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import java.io.IOException; @@ -21,7 +18,7 @@ public class SolidRandomOffsetPattern extends AbstractPattern { private final Pattern pattern; private transient int dx2, dy2, dz2; - private transient MutableBlockVector mutable; + private transient MutableBlockVector3 mutable; private transient boolean[] solid; private SplittableRandom r; @@ -40,15 +37,15 @@ public class SolidRandomOffsetPattern extends AbstractPattern { this.dz2 = dz * 2 + 1; solid = SolidBlockMask.getTypes(); this.r = new SplittableRandom(); - this.mutable = new MutableBlockVector(); + this.mutable = new MutableBlockVector3(); } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { mutable.mutX((position.getX() + r.nextInt(dx2) - dx)); mutable.mutY((position.getY() + r.nextInt(dy2) - dy)); mutable.mutZ((position.getZ() + r.nextInt(dz2) - dz)); - BlockStateHolder block = pattern.apply(mutable); + BaseBlock block = pattern.apply(mutable); if (solid[block.getInternalBlockTypeId()]) { return block; } else { @@ -57,7 +54,7 @@ public class SolidRandomOffsetPattern extends AbstractPattern { } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { mutable.mutX((get.getX() + r.nextInt(dx2) - dx)); mutable.mutY((get.getY() + r.nextInt(dy2) - dy)); mutable.mutZ((get.getZ() + r.nextInt(dz2) - dz)); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SurfaceRandomOffsetPattern.java b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SurfaceRandomOffsetPattern.java index ea44edb1d..92020ef76 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SurfaceRandomOffsetPattern.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/pattern/SurfaceRandomOffsetPattern.java @@ -1,26 +1,24 @@ package com.boydti.fawe.object.pattern; -import com.boydti.fawe.FaweCache; -import com.boydti.fawe.object.PseudoRandom; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.visitor.BreadthFirstSearch; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import java.io.IOException; +import java.util.concurrent.ThreadLocalRandom; public class SurfaceRandomOffsetPattern extends AbstractPattern { private final Pattern pattern; private int moves; - private transient MutableBlockVector cur; - private transient MutableBlockVector[] buffer; - private transient MutableBlockVector[] allowed; - private transient MutableBlockVector next; + private transient MutableBlockVector3 cur; + private transient MutableBlockVector3[] buffer; + private transient MutableBlockVector3[] allowed; + private transient MutableBlockVector3 next; public SurfaceRandomOffsetPattern(Pattern pattern, int distance) { this.pattern = pattern; @@ -29,26 +27,26 @@ public class SurfaceRandomOffsetPattern extends AbstractPattern { } private void init() { - cur = new MutableBlockVector(); - this.buffer = new MutableBlockVector[BreadthFirstSearch.DIAGONAL_DIRECTIONS.length]; + cur = new MutableBlockVector3(); + this.buffer = new MutableBlockVector3[BreadthFirstSearch.DIAGONAL_DIRECTIONS.length]; for (int i = 0; i < buffer.length; i++) { - buffer[i] = new MutableBlockVector(); + buffer[i] = new MutableBlockVector3(); } - allowed = new MutableBlockVector[buffer.length]; + allowed = new MutableBlockVector3[buffer.length]; } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { return pattern.apply(travel(position)); } - private Vector travel(Vector pos) { + private BlockVector3 travel(BlockVector3 pos) { cur.setComponents(pos); for (int move = 0; move < moves; move++) { int index = 0; for (int i = 0; i < allowed.length; i++) { next = buffer[i]; - Vector dir = BreadthFirstSearch.DIAGONAL_DIRECTIONS[i]; + BlockVector3 dir = BreadthFirstSearch.DIAGONAL_DIRECTIONS[i]; next.setComponents(cur.getBlockX() + dir.getBlockX(), cur.getBlockY() + dir.getBlockY(), cur.getBlockZ() + dir.getBlockZ()); if (allowed(next)) { allowed[index++] = next; @@ -57,14 +55,15 @@ public class SurfaceRandomOffsetPattern extends AbstractPattern { if (index == 0) { return cur; } - next = allowed[PseudoRandom.random.nextInt(index)]; + next = allowed[ThreadLocalRandom.current().nextInt(index)]; cur.setComponents(next.getBlockX(), next.getBlockY(), next.getBlockZ()); } return cur; } - private boolean allowed(Vector v) { - BlockStateHolder block = pattern.apply(v); + private boolean allowed(BlockVector3 bv) { + MutableBlockVector3 v = new MutableBlockVector3(bv); + BlockStateHolder block = pattern.apply(bv); if (!block.getBlockType().getMaterial().isMovementBlocker()) { return false; } @@ -107,7 +106,7 @@ public class SurfaceRandomOffsetPattern extends AbstractPattern { return false; } - private boolean canPassthrough(Vector v) { + private boolean canPassthrough(BlockVector3 v) { BlockStateHolder block = pattern.apply(v); return !block.getBlockType().getMaterial().isMovementBlocker(); } @@ -116,4 +115,4 @@ public class SurfaceRandomOffsetPattern extends AbstractPattern { stream.defaultReadObject(); init(); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/queue/FaweQueueDelegateExtent.java b/worldedit-core/src/main/java/com/boydti/fawe/object/queue/FaweQueueDelegateExtent.java index d3455cf64..36e8535f8 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/queue/FaweQueueDelegateExtent.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/queue/FaweQueueDelegateExtent.java @@ -3,13 +3,14 @@ package com.boydti.fawe.object.queue; import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.exception.FaweException; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.MutableBlockVector2D; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector2; import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -18,7 +19,7 @@ import static com.google.common.base.Preconditions.checkNotNull; public class FaweQueueDelegateExtent extends DelegateFaweQueue { private final FaweQueue parentQueue; private final Extent parentExtent; - private final MutableBlockVector2D mutable2d = new MutableBlockVector2D(); +// private final MutableBlockVector2 mutable2d = new MutableBlockVector2(); public FaweQueueDelegateExtent(FaweQueue parentQueue, Extent parentExtent) { super(parentQueue); @@ -53,31 +54,31 @@ public class FaweQueueDelegateExtent extends DelegateFaweQueue { @Override public CompoundTag getTileEntity(int x, int y, int z) throws FaweException.FaweChunkLoadException { - return getLazyBlock(x, y, z).getNbtData(); + return getFullBlock(BlockVector3.at(x, y, z)).getNbtData(); } @Override public int getBiomeId(int x, int z) throws FaweException.FaweChunkLoadException { - return parentExtent.getBiome(mutable2d.setComponents(x, z)).getId(); + return parentExtent.getBiome(BlockVector2.at(x, z)).getId(); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return parentExtent.setBiome(position, biome); } @Override - public BlockState getBlock(Vector position) { + public BlockState getBlock(BlockVector3 position) { return parentExtent.getBlock(position); } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return parentExtent.getBiome(position); } @Override - public boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + public boolean setBlock(BlockVector3 position, BlockStateHolder block) throws WorldEditException { return parentExtent.setBlock(position, block); } @@ -87,7 +88,7 @@ public class FaweQueueDelegateExtent extends DelegateFaweQueue { } @Override - public BlockState getLazyBlock(Vector position) { + public BlockState getLazyBlock(BlockVector3 position) { return parentExtent.getLazyBlock(position); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/queue/IDelegateFaweQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/object/queue/IDelegateFaweQueue.java index 84dfc08da..f80bcc89e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/queue/IDelegateFaweQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/queue/IDelegateFaweQueue.java @@ -13,16 +13,16 @@ import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.util.SetQueue; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.session.ClipboardHolder; @@ -51,12 +51,12 @@ public interface IDelegateFaweQueue extends FaweQueue { } @Override - default Vector getMinimumPoint() { + default BlockVector3 getMinimumPoint() { return getQueue().getMinimumPoint(); } @Override - default Vector getMaximumPoint() { + default BlockVector3 getMaximumPoint() { return getQueue().getMaximumPoint(); } @@ -66,27 +66,27 @@ public interface IDelegateFaweQueue extends FaweQueue { } @Override - default boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { + default > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { return getQueue().setBlock(x, y, z, block); } @Override - default BlockState getBlock(Vector position) { + default BlockState getBlock(BlockVector3 position) { return getQueue().getBlock(position); } @Override - default BaseBiome getBiome(Vector2D position) { + default BaseBiome getBiome(BlockVector2 position) { return getQueue().getBiome(position); } @Override - default boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + default > boolean setBlock(BlockVector3 position, B block) throws WorldEditException { return getQueue().setBlock(position, block); } @Override - default boolean setBiome(Vector2D position, BaseBiome biome) { + default boolean setBiome(BlockVector2 position, BaseBiome biome) { return getQueue().setBiome(position, biome); } @@ -261,12 +261,12 @@ public interface IDelegateFaweQueue extends FaweQueue { } @Override - default void forEachBlockInChunk(int cx, int cz, RunnableVal2 onEach) { + default void forEachBlockInChunk(int cx, int cz, RunnableVal2 onEach) { getQueue().forEachBlockInChunk(cx, cz, onEach); } @Override - default void forEachTileInChunk(int cx, int cz, RunnableVal2 onEach) { + default void forEachTileInChunk(int cx, int cz, RunnableVal2 onEach) { getQueue().forEachTileInChunk(cx, cz, onEach); } @@ -459,7 +459,7 @@ public interface IDelegateFaweQueue extends FaweQueue { } @Override - default BlockState getLazyBlock(Vector position) { + default BlockState getLazyBlock(BlockVector3 position) { return getQueue().getLazyBlock(position); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/queue/LazyFaweChunk.java b/worldedit-core/src/main/java/com/boydti/fawe/object/queue/LazyFaweChunk.java index 4b60a6921..937e07d6a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/queue/LazyFaweChunk.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/queue/LazyFaweChunk.java @@ -4,7 +4,7 @@ import com.boydti.fawe.object.FaweChunk; import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.visitor.FaweChunkVisitor; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/queue/NullFaweQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/object/queue/NullFaweQueue.java index 41576b36e..154bc92da 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/queue/NullFaweQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/queue/NullFaweQueue.java @@ -7,7 +7,7 @@ import com.boydti.fawe.object.RunnableVal2; import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.util.SetQueue; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockState; @@ -188,7 +188,7 @@ public class NullFaweQueue implements FaweQueue { } @Override - public BlockState getBlock(Vector position) { + public BlockState getBlock(BlockVector3 position) { return state; } 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 5e1771cfe..3abaa65cf 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 @@ -2,15 +2,14 @@ package com.boydti.fawe.object.regions; import com.boydti.fawe.object.HasFaweQueue; import com.boydti.fawe.object.collection.BlockVectorSet; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.AbstractRegion; import com.sk89q.worldedit.regions.RegionOperationException; import com.sk89q.worldedit.world.World; @@ -48,18 +47,18 @@ public class FuzzyRegion extends AbstractRegion { public void select(int x, int y, int z) { RecursiveVisitor search = new RecursiveVisitor(mask, new RegionFunction() { @Override - public boolean apply(Vector p) throws WorldEditException { + public boolean apply(BlockVector3 p) throws WorldEditException { setMinMax(p.getBlockX(), p.getBlockY(), p.getBlockZ()); return true; } }, 256, extent instanceof HasFaweQueue ? (HasFaweQueue) extent : null); search.setVisited(set); - search.visit(new Vector(x, y, z)); + search.visit(BlockVector3.at(x, y, z)); Operations.completeBlindly(search); } @Override - public Iterator iterator() { + public Iterator iterator() { return (Iterator) set.iterator(); } @@ -94,32 +93,32 @@ public class FuzzyRegion extends AbstractRegion { } @Override - public Vector getMinimumPoint() { - return new Vector(minX, minY, minZ); + public BlockVector3 getMinimumPoint() { + return BlockVector3.at(minX, minY, minZ); } @Override - public Vector getMaximumPoint() { - return new Vector(maxX, maxY, maxZ); + public BlockVector3 getMaximumPoint() { + return BlockVector3.at(maxX, maxY, maxZ); } @Override - public void expand(Vector... changes) throws RegionOperationException { + public void expand(BlockVector3... changes) throws RegionOperationException { throw new RegionOperationException("Selection cannot expand"); } @Override - public void contract(Vector... changes) throws RegionOperationException { + public void contract(BlockVector3... changes) throws RegionOperationException { throw new RegionOperationException("Selection cannot contract"); } @Override - public boolean contains(Vector position) { + public boolean contains(BlockVector3 position) { return contains(position.getBlockX(), position.getBlockY(), position.getBlockZ()); } @Override - public void shift(Vector change) throws RegionOperationException { + public void shift(BlockVector3 change) throws RegionOperationException { throw new RegionOperationException("Selection cannot be shifted"); } 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 197324020..28ec2681b 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 @@ -19,8 +19,10 @@ package com.boydti.fawe.object.regions; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; +import com.sk89q.worldedit.math.MutableVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.AbstractRegion; import com.sk89q.worldedit.regions.RegionOperationException; import com.sk89q.worldedit.regions.polyhedron.Edge; @@ -36,32 +38,32 @@ public class PolyhedralRegion extends AbstractRegion { /** * Vertices that are contained in the convex hull. */ - private final Set vertices = new LinkedHashSet(); + private final Set vertices = new LinkedHashSet<>(); /** * Triangles that form the convex hull. */ - private final List triangles = new ArrayList(); + private final List triangles = new ArrayList<>(); /** * Vertices that are coplanar to the first 3 vertices. */ - private final Set vertexBacklog = new LinkedHashSet(); + private final Set vertexBacklog = new LinkedHashSet<>(); /** * Minimum point of the axis-aligned bounding box. */ - private Vector minimumPoint; + private BlockVector3 minimumPoint; /** * Maximum point of the axis-aligned bounding box. */ - private Vector maximumPoint; + private BlockVector3 maximumPoint; /** * Accumulator for the barycenter of the polyhedron. Divide by vertices.size() to get the actual center. */ - private Vector centerAccum = Vector.ZERO; + private BlockVector3 centerAccum = BlockVector3.ZERO; /** * The last triangle that caused a {@link #contains(Vector)} to classify a point as "outside". Used for optimization. @@ -104,7 +106,7 @@ public class PolyhedralRegion extends AbstractRegion { minimumPoint = null; maximumPoint = null; - centerAccum = Vector.ZERO; + centerAccum = BlockVector3.ZERO; lastTriangle = null; } @@ -115,7 +117,7 @@ public class PolyhedralRegion extends AbstractRegion { * @param vertex the vertex * @return true, if something changed. */ - public boolean addVertex(Vector vertex) { + public boolean addVertex(BlockVector3 vertex) { checkNotNull(vertex); lastTriangle = null; // Probably not necessary @@ -141,8 +143,10 @@ public class PolyhedralRegion extends AbstractRegion { if (minimumPoint == null) { minimumPoint = maximumPoint = vertex; } else { - minimumPoint = new MutableBlockVector(Vector.getMinimum(minimumPoint, vertex)); - maximumPoint = new MutableBlockVector(Vector.getMaximum(maximumPoint, vertex)); +// minimumPoint = new MutableBlockVector3(minimumPoint.getMinimum(vertex)); +// maximumPoint = new MutableBlockVector3(maximumPoint.getMaximum(vertex)); + minimumPoint = minimumPoint.getMinimum(vertex); + maximumPoint = maximumPoint.getMaximum(vertex); } int size = vertices.size(); @@ -155,13 +159,13 @@ public class PolyhedralRegion extends AbstractRegion { case 3: // Generate minimal mesh to start from - final Vector[] v = vertices.toArray(new Vector[vertices.size()]); + final BlockVector3[] v = vertices.toArray(new BlockVector3[vertices.size()]); triangles.add((new Triangle(v[0], v[size - 2], v[size - 1]))); triangles.add((new Triangle(v[0], v[size - 1], v[size - 2]))); return true; } - final Set borderEdges = new LinkedHashSet(); + final Set borderEdges = new LinkedHashSet<>(); for (Iterator it = triangles.iterator(); it.hasNext(); ) { final Triangle triangle = it.next(); @@ -186,8 +190,8 @@ public class PolyhedralRegion extends AbstractRegion { // Add triangles between the remembered edges and the new vertex. for (Edge edge : borderEdges) { - com.sk89q.worldedit.regions.polyhedron.Triangle triangle = edge.createTriangle(vertex); - Triangle fTria = new Triangle(triangle.getVertex(0), triangle.getVertex(1), triangle.getVertex(2)); + com.sk89q.worldedit.regions.polyhedron.Triangle triangle = edge.createTriangle(vertex.toVector3()); + Triangle fTria = new Triangle(triangle.getVertex(0).toBlockPoint(), triangle.getVertex(1).toBlockPoint(), triangle.getVertex(2).toBlockPoint()); triangles.add(fTria); } @@ -196,9 +200,9 @@ public class PolyhedralRegion extends AbstractRegion { vertices.remove(vertex); // Clone, clear and work through the backlog - final List vertexBacklog2 = new ArrayList(vertexBacklog); + final List vertexBacklog2 = new ArrayList<>(vertexBacklog); vertexBacklog.clear(); - for (Vector vertex2 : vertexBacklog2) { + for (BlockVector3 vertex2 : vertexBacklog2) { addVertex(vertex2); } @@ -213,39 +217,39 @@ public class PolyhedralRegion extends AbstractRegion { } @Override - public Vector getMinimumPoint() { + public BlockVector3 getMinimumPoint() { return minimumPoint; } @Override - public Vector getMaximumPoint() { + public BlockVector3 getMaximumPoint() { return maximumPoint; } @Override - public Vector getCenter() { - return centerAccum.divide(vertices.size()); + public Vector3 getCenter() { + return centerAccum.divide(vertices.size()).toVector3(); } @Override - public void expand(Vector... changes) throws RegionOperationException { + public void expand(BlockVector3... changes) throws RegionOperationException { } @Override - public void contract(Vector... changes) throws RegionOperationException { + public void contract(BlockVector3... changes) throws RegionOperationException { } @Override - public void shift(Vector change) throws RegionOperationException { + public void shift(BlockVector3 change) throws RegionOperationException { shiftCollection(vertices, change); shiftCollection(vertexBacklog, change); for (int i = 0; i < triangles.size(); ++i) { final Triangle triangle = triangles.get(i); - final Vector v0 = change.add(triangle.getVertex(0)); - final Vector v1 = change.add(triangle.getVertex(1)); - final Vector v2 = change.add(triangle.getVertex(2)); + final BlockVector3 v0 = change.add(triangle.getVertex(0).toBlockPoint()); + final BlockVector3 v1 = change.add(triangle.getVertex(1).toBlockPoint()); + final BlockVector3 v2 = change.add(triangle.getVertex(2).toBlockPoint()); triangles.set(i, new Triangle(v0, v1, v2)); } @@ -256,24 +260,24 @@ public class PolyhedralRegion extends AbstractRegion { lastTriangle = null; } - private static void shiftCollection(Collection collection, Vector change) { - final List tmp = new ArrayList(collection); + private static void shiftCollection(Collection collection, BlockVector3 change) { + final List tmp = new ArrayList<>(collection); collection.clear(); - for (Vector vertex : tmp) { + for (BlockVector3 vertex : tmp) { collection.add(change.add(vertex)); } } @Override - public boolean contains(Vector position) { + public boolean contains(BlockVector3 position) { if (!isDefined()) { return false; } final int x = position.getBlockX(); final int y = position.getBlockY(); final int z = position.getBlockZ(); - final Vector min = getMinimumPoint(); - final Vector max = getMaximumPoint(); + 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; @@ -283,7 +287,7 @@ public class PolyhedralRegion extends AbstractRegion { return containsRaw(position); } - private boolean containsRaw(Vector pt) { + private boolean containsRaw(BlockVector3 pt) { if (lastTriangle != null && lastTriangle.contains(pt)) { return true; } @@ -299,12 +303,12 @@ public class PolyhedralRegion extends AbstractRegion { return false; } - public Collection getVertices() { + public Collection getVertices() { if (vertexBacklog.isEmpty()) { return vertices; } - final List ret = new ArrayList(vertices); + final List ret = new ArrayList<>(vertices); ret.addAll(vertexBacklog); return ret; @@ -318,4 +322,4 @@ public class PolyhedralRegion extends AbstractRegion { public AbstractRegion clone() { return new PolyhedralRegion(this); } -} \ No newline at end of file +} 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 5f8b3323b..8cea2bfe3 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 @@ -3,7 +3,8 @@ package com.boydti.fawe.object.regions; import com.boydti.fawe.util.MathMan; import com.boydti.fawe.util.StringMan; import com.google.common.base.Preconditions; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.polyhedron.Edge; public class Triangle { @@ -23,10 +24,10 @@ public class Triangle { private final double[] vmin = new double[3]; private final double[] vmax = new double[3]; - private final Vector normalVec; + private final BlockVector3 normalVec; private final double b; - public Triangle(Vector pos1, Vector pos2, Vector pos3) { + public Triangle(BlockVector3 pos1, BlockVector3 pos2, BlockVector3 pos3) { verts[0] = new double[]{pos1.getBlockX(), pos1.getBlockY(), pos1.getBlockZ()}; verts[1] = new double[]{pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ()}; verts[2] = new double[]{pos3.getBlockX(), pos3.getBlockY(), pos3.getBlockZ()}; @@ -37,16 +38,16 @@ public class Triangle { this.b = Math.max(Math.max(this.normalVec.dot(pos1), this.normalVec.dot(pos2)), this.normalVec.dot(pos3)); } - public boolean above(Vector pt) { + public boolean above(BlockVector3 pt) { Preconditions.checkNotNull(pt); return this.normalVec.dot(pt) > this.b; } public Edge getEdge(int index) { if (index == this.verts.length - 1) { - return new Edge(new Vector(this.verts[index]), new Vector(this.verts[0])); + return new Edge(Vector3.at(this.verts[index][0], this.verts[index][1],this.verts[index][2]), Vector3.at(this.verts[0][0], this.verts[0][1], this.verts[0][2])); } else { - return new Edge(new Vector(this.verts[index]), new Vector(this.verts[index + 1])); + return new Edge(Vector3.at(this.verts[index][0], this.verts[index][1],this.verts[index][2]), Vector3.at(this.verts[index + 1][0], this.verts[index + 1][1], this.verts[index + 1][2])); } } @@ -55,11 +56,11 @@ public class Triangle { return StringMan.getString(verts); } - public Vector getVertex(int index) { - return new Vector(verts[index]); + public Vector3 getVertex(int index) { + return Vector3.at(verts[index][0], verts[index][1], verts[index][2]); } - public boolean contains(Vector pos) { + public boolean contains(BlockVector3 pos) { center[0] = pos.getBlockX() + RADIUS; center[1] = pos.getBlockY() + RADIUS; center[2] = pos.getBlockZ() + RADIUS; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/regions/selector/FuzzyRegionSelector.java b/worldedit-core/src/main/java/com/boydti/fawe/object/regions/selector/FuzzyRegionSelector.java index f14b6f03a..ff398e776 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/regions/selector/FuzzyRegionSelector.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/regions/selector/FuzzyRegionSelector.java @@ -6,15 +6,14 @@ import com.boydti.fawe.object.regions.FuzzyRegion; import com.boydti.fawe.util.EditSessionBuilder; import com.boydti.fawe.util.ExtentTraverser; import com.boydti.fawe.util.MaskTraverser; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.regions.selector.limit.SelectorLimits; @@ -27,7 +26,7 @@ public class FuzzyRegionSelector extends AbstractDelegateExtent implements Regio private final Player player; private FuzzyRegion region; - private ArrayList positions; + private ArrayList positions; public FuzzyRegionSelector(Player player, @Nullable World world, Mask mask) { super(new EditSessionBuilder(world) @@ -43,7 +42,7 @@ public class FuzzyRegionSelector extends AbstractDelegateExtent implements Regio } @Override - public List getVerticies() { + public List getVerticies() { return positions; } @@ -72,7 +71,7 @@ public class FuzzyRegionSelector extends AbstractDelegateExtent implements Regio } @Override - public boolean selectPrimary(Vector position, SelectorLimits limits) { + public boolean selectPrimary(BlockVector3 position, SelectorLimits limits) { setWorld(getWorld()); new MaskTraverser(getMask()).reset(getExtent()); positions.clear(); @@ -83,7 +82,7 @@ public class FuzzyRegionSelector extends AbstractDelegateExtent implements Regio } @Override - public boolean selectSecondary(Vector position, SelectorLimits limits) { + public boolean selectSecondary(BlockVector3 position, SelectorLimits limits) { this.positions.add(position); new MaskTraverser(getMask()).reset(getExtent()); this.region.select(position.getBlockX(), position.getBlockY(), position.getBlockZ()); @@ -91,13 +90,13 @@ public class FuzzyRegionSelector extends AbstractDelegateExtent implements Regio } @Override - public void explainPrimarySelection(Actor actor, LocalSession session, Vector position) { + public void explainPrimarySelection(Actor actor, LocalSession session, BlockVector3 position) { int size = this.region.getArea(); BBC.SELECTOR_FUZZY_POS1.send(player, position, "(" + region.getArea() + ")"); } @Override - public void explainSecondarySelection(Actor actor, LocalSession session, Vector position) { + public void explainSecondarySelection(Actor actor, LocalSession session, BlockVector3 position) { int size = this.region.getArea(); BBC.SELECTOR_FUZZY_POS2.send(player, position, "(" + region.getArea() + ")"); } @@ -108,11 +107,11 @@ public class FuzzyRegionSelector extends AbstractDelegateExtent implements Regio } @Override - public BlockVector getPrimaryPosition() throws IncompleteRegionException { + public BlockVector3 getPrimaryPosition() throws IncompleteRegionException { if (positions.isEmpty()) { throw new IncompleteRegionException(); } - return new BlockVector(positions.get(0)); + return positions.get(0); } @Override @@ -153,7 +152,7 @@ public class FuzzyRegionSelector extends AbstractDelegateExtent implements Regio @Override public List getInformationLines() { - final List lines = new ArrayList(); + final List lines = new ArrayList<>(); for (int i = 0; i < positions.size(); i++) { lines.add("Position " + i + ": " + positions.get(i)); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/regions/selector/PolyhedralRegionSelector.java b/worldedit-core/src/main/java/com/boydti/fawe/object/regions/selector/PolyhedralRegionSelector.java index 56229f252..b8815126a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/regions/selector/PolyhedralRegionSelector.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/regions/selector/PolyhedralRegionSelector.java @@ -21,14 +21,13 @@ package com.boydti.fawe.object.regions.selector; import com.boydti.fawe.object.regions.PolyhedralRegion; import com.boydti.fawe.object.regions.Triangle; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.internal.cui.CUIRegion; import com.sk89q.worldedit.internal.cui.SelectionPointEvent; import com.sk89q.worldedit.internal.cui.SelectionPolygonEvent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.regions.selector.limit.SelectorLimits; @@ -46,7 +45,7 @@ import static com.google.common.base.Preconditions.checkNotNull; public class PolyhedralRegionSelector implements RegionSelector, CUIRegion { private final transient PolyhedralRegion region; - private transient BlockVector pos1; + private transient BlockVector3 pos1; /** * Create a new selector with a {@code null} world. @@ -65,7 +64,7 @@ public class PolyhedralRegionSelector implements RegionSelector, CUIRegion { } @Override - public List getVerticies() { + public List getVerticies() { return new ArrayList<>(region.getVertices()); } @@ -81,15 +80,15 @@ public class PolyhedralRegionSelector implements RegionSelector, CUIRegion { } @Override - public boolean selectPrimary(Vector position, SelectorLimits limits) { + public boolean selectPrimary(BlockVector3 position, SelectorLimits limits) { checkNotNull(position); clear(); - pos1 = position.toBlockVector(); + pos1 = position; return region.addVertex(position); } @Override - public boolean selectSecondary(Vector position, SelectorLimits limits) { + public boolean selectSecondary(BlockVector3 position, SelectorLimits limits) { checkNotNull(position); Optional vertexLimit = limits.getPolyhedronVertexLimit(); @@ -102,7 +101,7 @@ public class PolyhedralRegionSelector implements RegionSelector, CUIRegion { } @Override - public BlockVector getPrimaryPosition() throws IncompleteRegionException { + public BlockVector3 getPrimaryPosition() throws IncompleteRegionException { return pos1; } @@ -132,7 +131,7 @@ public class PolyhedralRegionSelector implements RegionSelector, CUIRegion { @Override public void learnChanges() { - pos1 = region.getVertices().iterator().next().toBlockVector(); + pos1 = region.getVertices().iterator().next(); } @Override @@ -147,7 +146,7 @@ public class PolyhedralRegionSelector implements RegionSelector, CUIRegion { @Override public List getInformationLines() { - List ret = new ArrayList(); + List ret = new ArrayList<>(); ret.add("Vertices: " + region.getVertices().size()); ret.add("Triangles: " + region.getTriangles().size()); @@ -157,7 +156,7 @@ public class PolyhedralRegionSelector implements RegionSelector, CUIRegion { @Override - public void explainPrimarySelection(Actor player, LocalSession session, Vector pos) { + public void explainPrimarySelection(Actor player, LocalSession session, BlockVector3 pos) { checkNotNull(player); checkNotNull(session); checkNotNull(pos); @@ -168,7 +167,7 @@ public class PolyhedralRegionSelector implements RegionSelector, CUIRegion { } @Override - public void explainSecondarySelection(Actor player, LocalSession session, Vector pos) { + public void explainSecondarySelection(Actor player, LocalSession session, BlockVector3 pos) { checkNotNull(player); checkNotNull(session); checkNotNull(pos); @@ -200,12 +199,12 @@ public class PolyhedralRegionSelector implements RegionSelector, CUIRegion { checkNotNull(player); checkNotNull(session); - Collection vertices = region.getVertices(); + Collection vertices = region.getVertices(); Collection triangles = region.getTriangles(); - Map vertexIds = new HashMap(vertices.size()); + Map vertexIds = new HashMap<>(vertices.size()); int lastVertexId = -1; - for (Vector vertex : vertices) { + for (BlockVector3 vertex : vertices) { vertexIds.put(vertex, ++lastVertexId); session.dispatchCUIEvent(player, new SelectionPointEvent(lastVertexId, vertex, getArea())); } 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 4a90cbe76..c91531b8f 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 @@ -2,10 +2,10 @@ package com.boydti.fawe.object.schematic; import com.boydti.fawe.Fawe; import com.boydti.fawe.util.TextureUtil; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -68,12 +68,13 @@ public class PNGWriter implements ClipboardWriter { boolean fill = length * 4 < imageSize && width * 4 < imageSize; - MutableBlockVector mutable = new MutableBlockVector(0, 0, 0); - Vector mutableTop = new Vector(0, 0, 0); - Vector mutableRight = new Vector(0, 0, 0); - Vector mutableLeft = new Vector(0, 0, 0); + MutableBlockVector3 mutable, mutableTop, mutableRight, mutableLeft; + mutable = mutableTop = mutableRight = mutableLeft = new MutableBlockVector3(0, 0, 0); +// Vector mutableTop = new Vector(0, 0, 0); +// Vector mutableRight = new Vector(0, 0, 0); +// Vector mutableLeft = new Vector(0, 0, 0); - Vector min = clipboard.getMinimumPoint(); + BlockVector3 min = clipboard.getMinimumPoint(); int y0 = min.getBlockY(); int z0 = min.getBlockZ(); int x0 = min.getBlockX(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/Schematic.java b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/Schematic.java index a9f6bb9a2..ba50e80b3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/Schematic.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/Schematic.java @@ -7,10 +7,7 @@ import com.boydti.fawe.util.EditSessionBuilder; import com.boydti.fawe.util.MaskTraverser; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.MutableBlockVector2D; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; @@ -24,6 +21,9 @@ import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.visitor.RegionVisitor; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector2; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; @@ -73,7 +73,7 @@ public class Schematic { * @param to * @return */ - public EditSession paste(World world, Vector to) { + public EditSession paste(World world, BlockVector3 to) { return paste(world, to, true, true, null); } @@ -105,7 +105,7 @@ public class Schematic { } } - public EditSession paste(World world, Vector to, boolean allowUndo, boolean pasteAir, @Nullable Transform transform) { + public EditSession paste(World world, BlockVector3 to, boolean allowUndo, boolean pasteAir, @Nullable Transform transform) { return paste(world, to, allowUndo, pasteAir, true, transform); } @@ -119,7 +119,7 @@ public class Schematic { * @param transform * @return */ - public EditSession paste(World world, Vector to, boolean allowUndo, boolean pasteAir, boolean copyEntities, @Nullable Transform transform) { + public EditSession paste(World world, BlockVector3 to, boolean allowUndo, boolean pasteAir, boolean copyEntities, @Nullable Transform transform) { checkNotNull(world); checkNotNull(to); Region region = clipboard.getRegion(); @@ -165,7 +165,7 @@ public class Schematic { return editSession; } - public void paste(Extent extent, Vector to, boolean pasteAir, Transform transform) { + public void paste(Extent extent, BlockVector3 to, boolean pasteAir, Transform transform) { checkNotNull(transform); Region region = clipboard.getRegion(); Extent source = clipboard; @@ -192,11 +192,11 @@ public class Schematic { Operations.completeBlindly(copy); } - public void paste(Extent extent, Vector to, final boolean pasteAir) { + public void paste(Extent extent, BlockVector3 to, final boolean pasteAir) { Region region = clipboard.getRegion().clone(); final int maxY = extent.getMaximumPoint().getBlockY(); - final Vector bot = clipboard.getMinimumPoint(); - final Vector origin = clipboard.getOrigin(); + final BlockVector3 bot = clipboard.getMinimumPoint(); + final BlockVector3 origin = clipboard.getOrigin(); final boolean copyBiomes = !(clipboard instanceof BlockArrayClipboard) || ((BlockArrayClipboard) clipboard).IMP.hasBiomes(); @@ -209,12 +209,12 @@ public class Schematic { BlockArrayClipboard bac = (BlockArrayClipboard) clipboard; if (copyBiomes) { bac.IMP.forEach(new FaweClipboard.BlockReader() { - MutableBlockVector2D mpos2d = new MutableBlockVector2D(); + MutableBlockVector2 mpos2d = new MutableBlockVector2(); { mpos2d.setComponents(Integer.MIN_VALUE, Integer.MIN_VALUE); } @Override - public void run(int x, int y, int z, BlockState block) { + public > void run(int x, int y, int z, B block) { try { int xx = x + relx; int zz = z + relz; @@ -232,7 +232,7 @@ public class Schematic { } else { bac.IMP.forEach(new FaweClipboard.BlockReader() { @Override - public void run(int x, int y, int z, BlockState block) { + public > void run(int x, int y, int z, B block) { try { extent.setBlock(x + relx, y + rely, z + relz, block); } catch (WorldEditException e) { throw new RuntimeException(e);} @@ -245,19 +245,20 @@ public class Schematic { final int rely = to.getBlockY() - origin.getBlockY(); final int relz = to.getBlockZ() - origin.getBlockZ(); RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { - MutableBlockVector2D mpos2d_2 = new MutableBlockVector2D(); - MutableBlockVector2D mpos2d = new MutableBlockVector2D(); +// MutableBlockVector2 mpos2d_2 = new MutableBlockVector2(); + MutableBlockVector2 mpos2d = new MutableBlockVector2(); { mpos2d.setComponents(Integer.MIN_VALUE, Integer.MIN_VALUE); } @Override - public boolean apply(Vector mutable) throws WorldEditException { + public boolean apply(BlockVector3 mutable) throws WorldEditException { BlockStateHolder block = clipboard.getBlock(mutable); int xx = mutable.getBlockX() + relx; int zz = mutable.getBlockZ() + relz; if (copyBiomes && xx != mpos2d.getBlockX() && zz != mpos2d.getBlockZ()) { mpos2d.setComponents(xx, zz); - extent.setBiome(mpos2d, clipboard.getBiome(mpos2d_2.setComponents(mutable.getBlockX(), mutable.getBlockZ()))); +// extent.setBiome(mpos2d, clipboard.getBiome(mpos2d_2.setComponents(mutable.getBlockX(), mutable.getBlockZ()))); + extent.setBiome(mpos2d, clipboard.getBiome(BlockVector2.at(mutable.getBlockX(), mutable.getBlockZ()))); } if (!pasteAir && block.getBlockType().getMaterial().isAir()) { return false; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/StructureFormat.java b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/StructureFormat.java index 5720015f9..120327d3f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/StructureFormat.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/schematic/StructureFormat.java @@ -13,9 +13,7 @@ import com.sk89q.jnbt.NBTOutputStream; import com.sk89q.jnbt.NamedTag; import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; @@ -23,6 +21,8 @@ import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.registry.state.AbstractProperty; @@ -77,14 +77,14 @@ public class StructureFormat implements ClipboardReader, ClipboardWriter { int length = size.getInt(2); // Init clipboard - Vector origin = new Vector(0, 0, 0); - CuboidRegion region = new CuboidRegion(origin, origin.add(width, height, length).subtract(Vector.ONE)); + BlockVector3 origin = BlockVector3.at(0, 0, 0); + CuboidRegion region = new CuboidRegion(origin, origin.add(width, height, length).subtract(BlockVector3.ONE)); BlockArrayClipboard clipboard = new BlockArrayClipboard(region, clipboardId); // Blocks ListTag blocks = (ListTag) tags.get("blocks"); if (blocks != null) { // Palette - List palette = (List) (List) tags.get("palette").getValue(); + List palette = (List) tags.get("palette").getValue(); BlockState[] combinedArray = new BlockState[palette.size()]; for (int i = 0; i < palette.size(); i++) { CompoundTag compound = palette.get(i); @@ -108,7 +108,7 @@ public class StructureFormat implements ClipboardReader, ClipboardWriter { combinedArray[i] = state; } // Populate blocks - List blocksList = (List) (List) tags.get("blocks").getValue(); + List blocksList = (List) tags.get("blocks").getValue(); try { for (CompoundTag compound : blocksList) { Map blockMap = compound.getValue(); @@ -168,33 +168,28 @@ public class StructureFormat implements ClipboardReader, ClipboardWriter { } Map structure = FaweCache.asMap("version", 1, "author", owner); // ignored: version / owner - MutableBlockVector mutable = new MutableBlockVector(0, 0, 0); + MutableBlockVector3 mutable = new MutableBlockVector3(0, 0, 0); Int2ObjectArrayMap indexes = new Int2ObjectArrayMap<>(); // Size structure.put("size", Arrays.asList(width, height, length)); // Palette { ArrayList> palette = new ArrayList<>(); - for (Vector point : region) { + for (BlockVector3 point : region) { BlockStateHolder block = clipboard.getBlock(point); int combined = block.getInternalId(); - BlockTypes type = block.getBlockType(); + BlockType type = block.getBlockType(); - switch (type) { - case STRUCTURE_VOID: - continue; - default: - } - if (indexes.containsKey(combined)) { + if (type == BlockTypes.STRUCTURE_VOID || indexes.containsKey(combined)) { continue; } - indexes.put((int) combined, (Integer) palette.size()); + indexes.put(combined, (Integer) palette.size()); HashMap paletteEntry = new HashMap<>(); paletteEntry.put("Name", type.getId()); if (block.getInternalId() != type.getInternalId()) { Map properties = null; - for (AbstractProperty property : (List) type.getProperties()) { + for (AbstractProperty property : (List>) type.getProperties()) { int propIndex = property.getIndex(block.getInternalId()); if (propIndex != 0) { if (properties == null) properties = new HashMap<>(); @@ -215,21 +210,20 @@ public class StructureFormat implements ClipboardReader, ClipboardWriter { // Blocks { ArrayList> blocks = new ArrayList<>(); - Vector min = region.getMinimumPoint(); - for (Vector point : region) { - BlockStateHolder block = clipboard.getBlock(point); - switch (block.getBlockType()) { - case STRUCTURE_VOID: - continue; - default: - int combined = block.getInternalId(); - int index = indexes.get(combined); - List pos = Arrays.asList((int) (point.getX() - min.getX()), (int) (point.getY() - min.getY()), (int) (point.getZ() - min.getZ())); - if (!block.hasNbtData()) { - blocks.add(FaweCache.asMap("state", index, "pos", pos)); - } else { - blocks.add(FaweCache.asMap("state", index, "pos", pos, "nbt", block.getNbtData())); - } + BlockVector3 min = region.getMinimumPoint(); + for (BlockVector3 point : region) { + BaseBlock block = clipboard.getFullBlock(point); + if (block.getBlockType() != BlockTypes.STRUCTURE_VOID) { + int combined = block.getInternalId(); + int index = indexes.get(combined); + List pos = Arrays.asList(point.getX() - min.getX(), + point.getY() - min.getY(), point.getZ() - min.getZ()); + if (!block.hasNbtData()) { + blocks.add(FaweCache.asMap("state", index, "pos", pos)); + } else { + blocks.add( + FaweCache.asMap("state", index, "pos", pos, "nbt", block.getNbtData())); + } } } if (!blocks.isEmpty()) { @@ -272,8 +266,8 @@ public class StructureFormat implements ClipboardReader, ClipboardWriter { } } - private Tag writeVector(Vector vector, String name) { - List list = new ArrayList(); + private Tag writeVector(BlockVector3 vector, String name) { + List list = new ArrayList<>(); list.add(new DoubleTag(vector.getX())); list.add(new DoubleTag(vector.getY())); list.add(new DoubleTag(vector.getZ())); @@ -281,7 +275,7 @@ public class StructureFormat implements ClipboardReader, ClipboardWriter { } private Tag writeRotation(Location location, String name) { - List list = new ArrayList(); + List list = new ArrayList<>(); list.add(new FloatTag(location.getYaw())); list.add(new FloatTag(location.getPitch())); return new ListTag(FloatTag.class, list); 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 7d78397be..808406b24 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 @@ -18,16 +18,22 @@ import com.google.common.io.Files; import com.sk89q.jnbt.NBTInputStream; import com.sk89q.jnbt.NBTOutputStream; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.platform.InputType; import com.sk89q.worldedit.event.platform.PlayerInputEvent; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector2; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.TargetBlock; +import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockTypes; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; @@ -50,11 +56,11 @@ public class SchemVis extends ImmutableVirtualWorld { private final Long2ObjectOpenHashMap> files; private final Long2ObjectOpenHashMap chunks; // TODO use soft references OR clear chunks outside view distance - private final MutableBlockVector2D lastPos = new MutableBlockVector2D(); + private final MutableBlockVector2 lastPos = new MutableBlockVector2(); private final FawePlayer player; private final Location origin; - private final BlockVector2D chunkOffset; - private BlockVector2D lastPosition; + private final BlockVector2 chunkOffset; + private BlockVector2 lastPosition; public static SchemVis create(FawePlayer player, Collection files) throws IOException { checkNotNull(player); @@ -76,12 +82,12 @@ public class SchemVis extends ImmutableVirtualWorld { // Set the origin to somewhere around where the player currently is FaweLocation pos = player.getLocation(); this.origin = player.getPlayer().getLocation(); - this.chunkOffset = new BlockVector2D(pos.x >> 4,pos.z >> 4); + this.chunkOffset = BlockVector2.at(pos.x >> 4,pos.z >> 4); } - private Set getFiles(BlockVector2D chunkPosA, BlockVector2D chunkPosB) { - BlockVector2D pos1 = new BlockVector2D(Math.min(chunkPosA.getBlockX(), chunkPosB.getBlockX()), Math.min(chunkPosA.getBlockZ(), chunkPosB.getBlockZ())); - BlockVector2D pos2 = new BlockVector2D(Math.max(chunkPosA.getBlockX(), chunkPosB.getBlockX()), Math.max(chunkPosA.getBlockZ(), chunkPosB.getBlockZ())); + private Set getFiles(BlockVector2 chunkPosA, BlockVector2 chunkPosB) { + BlockVector2 pos1 = BlockVector2.at(Math.min(chunkPosA.getBlockX(), chunkPosB.getBlockX()), Math.min(chunkPosA.getBlockZ(), chunkPosB.getBlockZ())); + BlockVector2 pos2 = BlockVector2.at(Math.max(chunkPosA.getBlockX(), chunkPosB.getBlockX()), Math.max(chunkPosA.getBlockZ(), chunkPosB.getBlockZ())); Set contained = new HashSet<>(); for (Long2ObjectMap.Entry> entry : files.long2ObjectEntrySet()) { long key = entry.getLongKey(); @@ -116,15 +122,15 @@ public class SchemVis extends ImmutableVirtualWorld { LocalSession session = this.player.getSession(); synchronized (this) { try { - BlockVector2D tmpLastPosition = lastPosition; - lastPosition = new BlockVector2D(chunkX, chunkZ); + BlockVector2 tmpLastPosition = lastPosition; + lastPosition = BlockVector2.at(chunkX, chunkZ); boolean sneaking = this.player.isSneaking(); if (event.getInputType() == InputType.PRIMARY && !sneaking) { File file = new File(cachedFile.getParentFile(), filename.substring(1, filename.length() - 7)); URI uri = file.toURI(); - ClipboardFormat format = ClipboardFormat.findByFile(file); + ClipboardFormat format = ClipboardFormats.findByFile(file); format.hold(player, uri, new FileInputStream(file)); BBC.SCHEMATIC_LOADED.send(player, filename); session.setVirtualWorld(null); @@ -140,7 +146,7 @@ public class SchemVis extends ImmutableVirtualWorld { File file = new File(clicked.getParentFile(), filename.substring(1, filename.length() - 7)); URI uri = file.toURI(); - ClipboardFormat format = ClipboardFormat.findByFile(file); + ClipboardFormat format = ClipboardFormats.findByFile(file); boolean contains = existing instanceof URIClipboardHolder && ((URIClipboardHolder) existing).contains(uri); if (contains) { @@ -251,8 +257,8 @@ public class SchemVis extends ImmutableVirtualWorld { * @return offset vector */ @Override - public Vector getOrigin() { - return new BlockVector(chunkOffset.getBlockX() << 4, 0, chunkOffset.getBlockZ() << 4); + public Vector3 getOrigin() { + return Vector3.at(chunkOffset.getBlockX() << 4, 0, chunkOffset.getBlockZ() << 4); } /** @@ -313,15 +319,15 @@ public class SchemVis extends ImmutableVirtualWorld { * @param schemDimensions * @return */ - private BlockVector2D registerAndGetChunkOffset(BlockVector2D schemDimensions, File file) { + private BlockVector2 registerAndGetChunkOffset(BlockVector2 schemDimensions, File file) { int chunkX = schemDimensions.getBlockX() >> 4; int chunkZ = schemDimensions.getBlockZ() >> 4; - MutableBlockVector2D pos2 = new MutableBlockVector2D(); - MutableBlockVector2D curPos = lastPos; + MutableBlockVector2 pos2 = new MutableBlockVector2(); + MutableBlockVector2 curPos = lastPos; // Find next free position while (!isAreaFree(curPos, pos2.setComponents(curPos.getBlockX() + chunkX, curPos.getBlockZ() + chunkZ))) { // if (curPos == lastPos && !files.containsKey(MathMan.pairInt(curPos.getBlockX(), curPos.getBlockZ()))) { -// curPos = new MutableBlockVector2D(); +// curPos = new MutableBlockVector2(); // curPos.setComponents(lastPos.getBlockX(), lastPos.getBlockZ()); // } curPos.nextPosition(); @@ -339,10 +345,10 @@ public class SchemVis extends ImmutableVirtualWorld { } } for (int i = 0; i < Math.min(chunkX, chunkZ); i++) curPos.nextPosition(); - return curPos.toBlockVector2D(); + return curPos; } - private boolean isAreaFree(BlockVector2D chunkPos1, BlockVector2D chunkPos2 /* inclusive */) { + private boolean isAreaFree(BlockVector2 chunkPos1, BlockVector2 chunkPos2 /* inclusive */) { for (int x = chunkPos1.getBlockX(); x <= chunkPos2.getBlockX(); x++) { for (int z = chunkPos1.getBlockZ(); z <= chunkPos2.getBlockZ(); z++) { if (files.containsKey(MathMan.pairInt(x, z)) || (x == 0 && z == 0)) return false; @@ -367,31 +373,31 @@ public class SchemVis extends ImmutableVirtualWorld { if (dimensionPair != null) { int width = (char) MathMan.unpairX(dimensionPair); int length = (char) MathMan.unpairY(dimensionPair); - BlockVector2D dimensions = new BlockVector2D(width, length); - BlockVector2D offset = registerAndGetChunkOffset(dimensions, cached); + BlockVector2 dimensions = BlockVector2.at(width, length); + BlockVector2 offset = registerAndGetChunkOffset(dimensions, cached); return; } if (cached.exists() && file.lastModified() <= cached.lastModified()) { try (InputStream fis = new BufferedInputStream(new FileInputStream(cached), 4)) { - BlockVector2D dimensions = new BlockVector2D(IOUtil.readVarInt(fis), IOUtil.readVarInt(fis)); + BlockVector2 dimensions = BlockVector2.at(IOUtil.readVarInt(fis), IOUtil.readVarInt(fis)); DIMENSION_CACHE.put(file, MathMan.pair((short) dimensions.getBlockX(), (short) dimensions.getBlockZ())); - BlockVector2D offset = registerAndGetChunkOffset(dimensions, cached); + BlockVector2 offset = registerAndGetChunkOffset(dimensions, cached); } } else { try { player.sendMessage(BBC.getPrefix() + "Converting: " + file); cached.createNewFile(); try (FileInputStream in = new FileInputStream(file)) { - ClipboardFormat format = ClipboardFormat.findByFile(file); + ClipboardFormat format = ClipboardFormats.findByFile(file); if (format != null) { ClipboardReader reader = format.getReader(in); Clipboard clipboard = reader.read(); clipboard.setOrigin(clipboard.getMinimumPoint()); try { MCAQueue queue = new MCAQueue(null, null, false); - BlockVector2D dimensions = clipboard.getDimensions().toVector2D().toBlockVector2D(); - BlockVector2D offset = registerAndGetChunkOffset(dimensions, cached); - new Schematic(clipboard).paste(queue, Vector.ZERO, true); + BlockVector2 dimensions = clipboard.getDimensions().toBlockVector2(); + BlockVector2 offset = registerAndGetChunkOffset(dimensions, cached); + new Schematic(clipboard).paste(queue, BlockVector3.ZERO, true); try (FileOutputStream fos = new FileOutputStream(cached)) { IOUtil.writeVarInt(fos, dimensions.getBlockX()); IOUtil.writeVarInt(fos, dimensions.getBlockZ()); @@ -468,7 +474,7 @@ public class SchemVis extends ImmutableVirtualWorld { int OCZ = MathMan.unpairIntY(origin); try { try (FileInputStream fis = new FileInputStream(cached)) { - BlockVector2D dimensions = new BlockVector2D(IOUtil.readVarInt(fis), IOUtil.readVarInt(fis)); + BlockVector2 dimensions = BlockVector2.at(IOUtil.readVarInt(fis), IOUtil.readVarInt(fis)); try (FaweInputStream in = MainUtil.getCompressedIS(fis)) { NonCloseableInputStream nonCloseable = new NonCloseableInputStream(in); try (NBTInputStream nis = new NBTInputStream(nonCloseable)) { @@ -593,7 +599,7 @@ public class SchemVis extends ImmutableVirtualWorld { clear(); chunks.clear(); files.clear(); - player.getPlayer().setPosition(origin.toVector(), origin.getPitch(), origin.getYaw()); + player.getPlayer().setPosition(origin, origin.getPitch(), origin.getYaw()); if (update) { FaweQueue packetQueue = SetQueue.IMP.getNewQueue(player.getWorld(), true, false); @@ -616,4 +622,28 @@ public class SchemVis extends ImmutableVirtualWorld { } } } + + @Override + public boolean playEffect(Vector3 position, int type, int data) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean setBiome(BlockVector2 position, BaseBiome 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/visitor/AboveVisitor.java b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/AboveVisitor.java index 1b130f976..71de953b1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/AboveVisitor.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/AboveVisitor.java @@ -1,10 +1,11 @@ package com.boydti.fawe.object.visitor; import com.boydti.fawe.object.HasFaweQueue; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; +import com.sk89q.worldedit.math.BlockVector3; + import java.util.Collection; @@ -38,18 +39,18 @@ public class AboveVisitor extends RecursiveVisitor { this.baseY = baseY; - Collection directions = getDirections(); + Collection directions = getDirections(); directions.clear(); - directions.add(new Vector(1, 0, 0)); - directions.add(new Vector(-1, 0, 0)); - directions.add(new Vector(0, 0, 1)); - directions.add(new Vector(0, 0, -1)); - directions.add(new Vector(0, 1, 0)); - directions.add(new Vector(0, -1, 0)); + directions.add(BlockVector3.at(1, 0, 0)); + directions.add(BlockVector3.at(-1, 0, 0)); + directions.add(BlockVector3.at(0, 0, 1)); + directions.add(BlockVector3.at(0, 0, -1)); + directions.add(BlockVector3.at(0, 1, 0)); + directions.add(BlockVector3.at(0, -1, 0)); } @Override - public boolean isVisitable(Vector from, Vector to) { + public boolean isVisitable(BlockVector3 from, BlockVector3 to) { return (from.getBlockY() >= baseY) && super.isVisitable(from, to); } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/DFSRecursiveVisitor.java b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/DFSRecursiveVisitor.java index a9ec075a9..1ed62df9e 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/DFSRecursiveVisitor.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/DFSRecursiveVisitor.java @@ -1,10 +1,9 @@ package com.boydti.fawe.object.visitor; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; - +import com.sk89q.worldedit.math.BlockVector3; import static com.google.common.base.Preconditions.checkNotNull; @@ -33,7 +32,7 @@ public class DFSRecursiveVisitor extends DFSVisitor { } @Override - public boolean isVisitable(final Vector from, final Vector to) { + public boolean isVisitable(final BlockVector3 from, final BlockVector3 to) { return this.mask.test(to); } } \ No newline at end of file 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 c9201d61d..dd9acaefd 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 @@ -2,12 +2,13 @@ package com.boydti.fawe.object.visitor; import com.boydti.fawe.config.BBC; import com.boydti.fawe.object.IntegerTrio; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.RunContext; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; + import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashSet; @@ -20,7 +21,7 @@ import java.util.concurrent.atomic.AtomicInteger; public abstract class DFSVisitor implements Operation { private final RegionFunction function; - private final List directions = new ArrayList<>(); + private final List directions = new ArrayList<>(); private final Map visited; private final ArrayDeque queue; private final HashSet hashQueue; @@ -37,32 +38,32 @@ public abstract class DFSVisitor implements Operation { this.hashQueue = new LinkedHashSet<>(); this.visited = new LinkedHashMap<>(); this.function = function; - this.directions.add(new Vector(0, -1, 0)); - this.directions.add(new Vector(0, 1, 0)); - this.directions.add(new Vector(-1, 0, 0)); - this.directions.add(new Vector(1, 0, 0)); - this.directions.add(new Vector(0, 0, -1)); - this.directions.add(new Vector(0, 0, 1)); + this.directions.add(BlockVector3.at(0, -1, 0)); + this.directions.add(BlockVector3.at(0, 1, 0)); + this.directions.add(BlockVector3.at(-1, 0, 0)); + this.directions.add(BlockVector3.at(1, 0, 0)); + this.directions.add(BlockVector3.at(0, 0, -1)); + this.directions.add(BlockVector3.at(0, 0, 1)); this.maxDepth = maxDepth; this.maxBranch = maxBranching; } - public abstract boolean isVisitable(Vector from, Vector to); + public abstract boolean isVisitable(BlockVector3 from, BlockVector3 to); - public List getDirections() { + public List getDirections() { return this.directions; } private IntegerTrio[] getIntDirections() { IntegerTrio[] array = new IntegerTrio[directions.size()]; for (int i = 0; i < array.length; i++) { - Vector dir = directions.get(i); + BlockVector3 dir = directions.get(i); array[i] = new IntegerTrio(dir.getBlockX(), dir.getBlockY(), dir.getBlockZ()); } return array; } - public void visit(final Vector pos) { + public void visit(final BlockVector3 pos) { Node node = new Node(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()); if (!this.hashQueue.contains(node)) { isVisitable(pos, pos); // Ignore this, just to initialize mask on this point @@ -76,8 +77,8 @@ public abstract class DFSVisitor implements Operation { NodePair current; Node from; Node adjacent; - MutableBlockVector mutable = new MutableBlockVector(); - Vector mutable2 = new Vector(); +// MutableBlockVector3 mutable = new MutableBlockVector3(); +// MutableBlockVector3 mutable2 = new MutableBlockVector3(); int countAdd, countAttempt; IntegerTrio[] dirs = getIntDirections(); @@ -88,18 +89,20 @@ public abstract class DFSVisitor implements Operation { if (visited.containsKey(from)) { continue; } - mutable.mutX(from.getX()); - mutable.mutY(from.getY()); - mutable.mutZ(from.getZ()); - function.apply(mutable); +// mutable.mutX(from.getX()); +// mutable.mutY(from.getY()); +// mutable.mutZ(from.getZ()); + BlockVector3 bv = BlockVector3.at(from.getX(), from.getY(), from.getZ()); + function.apply(bv); countAdd = 0; countAttempt = 0; for (IntegerTrio direction : dirs) { - mutable2.mutX(from.getX() + direction.x); - mutable2.mutY(from.getY() + direction.y); - mutable2.mutZ(from.getZ() + direction.z); - if (isVisitable(mutable, mutable2)) { - adjacent = new Node(mutable2.getBlockX(), mutable2.getBlockY(), mutable2.getBlockZ()); +// mutable2.mutX(from.getX() + direction.x); +// mutable2.mutY(from.getY() + direction.y); +// mutable2.mutZ(from.getZ() + direction.z); + BlockVector3 bv2 = BlockVector3.at(from.getX() + direction.x, from.getY() + direction.y, from.getZ() + direction.z); + if (isVisitable(bv, bv2)) { + adjacent = new Node(bv2.getBlockX(), bv2.getBlockY(), bv2.getBlockZ()); if ((current.from == null || !adjacent.equals(current.from))) { AtomicInteger adjacentCount = visited.get(adjacent); if (adjacentCount == null) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/Fast2DIterator.java b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/Fast2DIterator.java index 33379dd08..50a53fdef 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/Fast2DIterator.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/Fast2DIterator.java @@ -6,46 +6,47 @@ import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.HasFaweQueue; import com.boydti.fawe.util.ExtentTraverser; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; + import java.util.Iterator; import javax.annotation.Nonnull; import javax.annotation.Nullable; -public class Fast2DIterator implements Iterable { +public class Fast2DIterator implements Iterable { - private final Iterable iterable; + private final Iterable iterable; private final MappedFaweQueue queue; - public Fast2DIterator(@Nonnull Iterable iter, @Nullable EditSession extent) { + public Fast2DIterator(@Nonnull Iterable iter, @Nullable EditSession extent) { this(iter, (HasFaweQueue) extent); } - public Fast2DIterator(@Nonnull Iterable iter, @Nullable Extent extent) { + public Fast2DIterator(@Nonnull Iterable iter, @Nullable Extent extent) { this(iter, (HasFaweQueue) (extent != null ? (extent instanceof HasFaweQueue ? extent : new ExtentTraverser(extent).findAndGet(HasFaweQueue.class)) : null)); } - public Fast2DIterator(@Nonnull Iterable iter, @Nullable HasFaweQueue editSession) { + public Fast2DIterator(@Nonnull Iterable iter, @Nullable HasFaweQueue editSession) { this(iter, (FaweQueue) (editSession != null ? editSession.getQueue() : null)); } - public Fast2DIterator(@Nonnull Iterable iter, @Nullable FaweQueue faweQueue) { + public Fast2DIterator(@Nonnull Iterable iter, @Nullable FaweQueue faweQueue) { this.iterable = iter; this.queue = faweQueue != null && faweQueue instanceof MappedFaweQueue ? (MappedFaweQueue) faweQueue : null; } - public Iterable getIterable() { + public Iterable getIterable() { return iterable; } @Override - public Iterator iterator() { + public Iterator iterator() { if (queue == null || Settings.IMP.QUEUE.PRELOAD_CHUNKS <= 1) { - return (Iterator) iterable.iterator(); + return (Iterator) iterable.iterator(); } - return new Iterator() { - Iterator trailIter = iterable.iterator(); - Iterator leadIter = iterable.iterator(); + return new Iterator() { + Iterator trailIter = iterable.iterator(); + Iterator leadIter = iterable.iterator(); int lastTrailChunkX = Integer.MIN_VALUE; int lastTrailChunkZ = Integer.MIN_VALUE; int lastLeadChunkX = Integer.MIN_VALUE; @@ -64,8 +65,8 @@ public class Fast2DIterator implements Iterable { } @Override - public Vector2D next() { - Vector2D pt = trailIter.next(); + public BlockVector2 next() { + BlockVector2 pt = trailIter.next(); if (lastTrailChunkX != (lastTrailChunkX = pt.getBlockX() >> 4) || lastTrailChunkZ != (lastTrailChunkZ = pt.getBlockZ() >> 4)) { if (leadIter.hasNext()) { try { @@ -78,7 +79,7 @@ public class Fast2DIterator implements Iterable { amount = 1; } for (int count = 0; count < amount; ) { - Vector2D v = leadIter.next(); + BlockVector2 v = leadIter.next(); int vcx = v.getBlockX() >> 4; int vcz = v.getBlockZ() >> 4; if (vcx != lastLeadChunkX || vcz != lastLeadChunkZ) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastChunkIterator.java b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastChunkIterator.java index 7149fd563..44c241f87 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastChunkIterator.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastChunkIterator.java @@ -6,54 +6,55 @@ import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.HasFaweQueue; import com.boydti.fawe.util.ExtentTraverser; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector2; + import java.util.Iterator; import javax.annotation.Nonnull; import javax.annotation.Nullable; -public class FastChunkIterator implements Iterable { +public class FastChunkIterator implements Iterable { - private final Iterable iterable; + private final Iterable iterable; private final MappedFaweQueue queue; - public FastChunkIterator(@Nonnull Iterable iter, @Nullable EditSession extent) { + public FastChunkIterator(@Nonnull Iterable iter, @Nullable EditSession extent) { this(iter, (HasFaweQueue) extent); } - public FastChunkIterator(@Nonnull Iterable iter, @Nullable Extent extent) { + public FastChunkIterator(@Nonnull Iterable iter, @Nullable Extent extent) { this(iter, (HasFaweQueue) (extent != null ? (extent instanceof HasFaweQueue ? extent : new ExtentTraverser(extent).findAndGet(HasFaweQueue.class)) : null)); } - public FastChunkIterator(@Nonnull Iterable iter, @Nullable HasFaweQueue editSession) { + public FastChunkIterator(@Nonnull Iterable iter, @Nullable HasFaweQueue editSession) { this(iter, (FaweQueue) (editSession != null ? editSession.getQueue() : null)); } - public FastChunkIterator(@Nonnull Iterable iter, @Nullable FaweQueue faweQueue) { + public FastChunkIterator(@Nonnull Iterable iter, @Nullable FaweQueue faweQueue) { this.iterable = iter; this.queue = faweQueue != null && faweQueue instanceof MappedFaweQueue ? (MappedFaweQueue) faweQueue : null; } - public Iterable getIterable() { + public Iterable getIterable() { return iterable; } @Override - public Iterator iterator() { + public Iterator iterator() { if (queue == null || Settings.IMP.QUEUE.PRELOAD_CHUNKS <= 1) { - return (Iterator) iterable.iterator(); + return (Iterator) iterable.iterator(); } - final Iterator trailIter = iterable.iterator(); - final Iterator leadIter = iterable.iterator(); + final Iterator trailIter = iterable.iterator(); + final Iterator leadIter = iterable.iterator(); int amount = Settings.IMP.QUEUE.PRELOAD_CHUNKS; for (int i = 0; i < Settings.IMP.QUEUE.PRELOAD_CHUNKS && leadIter.hasNext(); i++) { - Vector2D toLoad = leadIter.next(); + BlockVector2 toLoad = leadIter.next(); queue.queueChunkLoad(toLoad.getBlockX(), toLoad.getBlockZ()); } if (!leadIter.hasNext()) { - return (Iterator) trailIter; + return (Iterator) trailIter; } - return new Iterator() { + return new Iterator() { @Override public void remove() { trailIter.remove(); @@ -65,9 +66,9 @@ public class FastChunkIterator implements Iterable { } @Override - public Vector2D next() { + public BlockVector2 next() { if (leadIter.hasNext()) { - Vector2D toLoad = leadIter.next(); + BlockVector2 toLoad = leadIter.next(); queue.queueChunkLoad(toLoad.getBlockX(), toLoad.getBlockZ()); } return trailIter.next(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastIterator.java b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastIterator.java index e4d5e2d82..ee936f88d 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastIterator.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/visitor/FastIterator.java @@ -6,46 +6,47 @@ import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.HasFaweQueue; import com.boydti.fawe.util.ExtentTraverser; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; + import java.util.Iterator; import javax.annotation.Nonnull; import javax.annotation.Nullable; -public class FastIterator implements Iterable { +public class FastIterator implements Iterable { - private final Iterable iterable; + private final Iterable iterable; private final MappedFaweQueue queue; - public FastIterator(@Nonnull Iterable iter, @Nullable EditSession extent) { + public FastIterator(@Nonnull Iterable iter, @Nullable EditSession extent) { this(iter, (HasFaweQueue) extent); } - public FastIterator(@Nonnull Iterable iter, @Nullable Extent extent) { + public FastIterator(@Nonnull Iterable iter, @Nullable Extent extent) { this(iter, (HasFaweQueue) (extent != null ? (extent instanceof HasFaweQueue ? extent : new ExtentTraverser(extent).findAndGet(HasFaweQueue.class)) : null)); } - public FastIterator(@Nonnull Iterable iter, @Nullable HasFaweQueue editSession) { + public FastIterator(@Nonnull Iterable iter, @Nullable HasFaweQueue editSession) { this(iter, (FaweQueue) (editSession != null ? editSession.getQueue() : null)); } - public FastIterator(@Nonnull Iterable iter, @Nullable FaweQueue faweQueue) { + public FastIterator(@Nonnull Iterable iter, @Nullable FaweQueue faweQueue) { this.iterable = iter; this.queue = faweQueue != null && faweQueue instanceof MappedFaweQueue ? (MappedFaweQueue) faweQueue : null; } - public Iterable getIterable() { + public Iterable getIterable() { return iterable; } @Override - public Iterator iterator() { + public Iterator iterator() { if (queue == null || Settings.IMP.QUEUE.PRELOAD_CHUNKS <= 1) { - return (Iterator) iterable.iterator(); + return (Iterator) iterable.iterator(); } - return new Iterator() { - Iterator trailIter = iterable.iterator(); - Iterator leadIter = iterable.iterator(); + return new Iterator() { + Iterator trailIter = iterable.iterator(); + Iterator leadIter = iterable.iterator(); int lastTrailChunkX = Integer.MIN_VALUE; int lastTrailChunkZ = Integer.MIN_VALUE; int lastLeadChunkX = Integer.MIN_VALUE; @@ -64,8 +65,8 @@ public class FastIterator implements Iterable { } @Override - public Vector next() { - Vector pt = trailIter.next(); + public BlockVector3 next() { + BlockVector3 pt = trailIter.next(); if (lastTrailChunkX != (lastTrailChunkX = pt.getBlockX() >> 4) || lastTrailChunkZ != (lastTrailChunkZ = pt.getBlockZ() >> 4)) { if (leadIter.hasNext()) { try { @@ -78,7 +79,7 @@ public class FastIterator implements Iterable { amount = 1; } for (int count = 0; count < amount; ) { - Vector v = leadIter.next(); + BlockVector3 v = leadIter.next(); int vcx = v.getBlockX() >> 4; int vcz = v.getBlockZ() >> 4; if (vcx != lastLeadChunkX || vcz != lastLeadChunkZ) { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/FaweMask.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/FaweMask.java index 99e9aa4b8..2714da0db 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/FaweMask.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/FaweMask.java @@ -1,7 +1,7 @@ package com.boydti.fawe.regions; import com.boydti.fawe.object.FawePlayer; -import com.sk89q.worldedit.BlockVector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.IDelegateRegion; import com.sk89q.worldedit.regions.Region; @@ -11,12 +11,12 @@ public class FaweMask implements IDelegateRegion { private String description = null; @Deprecated - public FaweMask(final BlockVector pos1, final BlockVector pos2, final String id) { + public FaweMask(final BlockVector3 pos1, final BlockVector3 pos2, final String id) { this(new CuboidRegion(pos1, pos2), id); } @Deprecated - public FaweMask(final BlockVector pos1, final BlockVector pos2) { + public FaweMask(final BlockVector3 pos1, final BlockVector3 pos2) { this(pos1, pos2, null); if ((pos1 == null) || (pos2 == null)) { throw new IllegalArgumentException("BlockVectors cannot be null!"); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/SimpleRegion.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/SimpleRegion.java index f01b054bb..6879154db 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/SimpleRegion.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/SimpleRegion.java @@ -1,42 +1,42 @@ package com.boydti.fawe.regions; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.AbstractRegion; import com.sk89q.worldedit.regions.RegionOperationException; import com.sk89q.worldedit.world.World; public abstract class SimpleRegion extends AbstractRegion { - private final Vector max; - private final Vector min; + private final BlockVector3 max; + private final BlockVector3 min; - public SimpleRegion(World world, Vector min, Vector max) { + public SimpleRegion(World world, BlockVector3 min, BlockVector3 max) { super(world); this.min = min; this.max = max; } @Override - public Vector getMinimumPoint() { + public BlockVector3 getMinimumPoint() { return min; } @Override - public Vector getMaximumPoint() { + public BlockVector3 getMaximumPoint() { return max; } @Override - public void expand(Vector... changes) throws RegionOperationException { + public void expand(BlockVector3... changes) throws RegionOperationException { throw new UnsupportedOperationException("Region is immutable"); } @Override - public void contract(Vector... changes) throws RegionOperationException { + public void contract(BlockVector3... changes) throws RegionOperationException { throw new UnsupportedOperationException("Region is immutable"); } @Override - public boolean contains(Vector p) { + public boolean contains(BlockVector3 p) { return contains(p.getBlockX(), p.getBlockY(), p.getBlockZ()); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/CuboidRegionFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/CuboidRegionFilter.java index 832482033..b3bfcd820 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/CuboidRegionFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/CuboidRegionFilter.java @@ -1,7 +1,7 @@ package com.boydti.fawe.regions.general; import com.boydti.fawe.object.collection.LongHashSet; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; public abstract class CuboidRegionFilter implements RegionFilter { @@ -18,7 +18,7 @@ public abstract class CuboidRegionFilter implements RegionFilter { */ public abstract void calculateRegions(); - public void add(Vector2D pos1, Vector2D pos2) { + public void add(BlockVector2 pos1, BlockVector2 pos2) { int ccx1 = pos1.getBlockX() >> 9; int ccz1 = pos1.getBlockZ() >> 9; int ccx2 = pos2.getBlockX() >> 9; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/CFIRedirect.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/CFIRedirect.java index 5cf2d84ad..ac338bd82 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/CFIRedirect.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/CFIRedirect.java @@ -1,17 +1,17 @@ package com.boydti.fawe.regions.general.plot; -import com.intellectualcrafters.plot.commands.CommandCategory; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.commands.RequiredType; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.object.worlds.SinglePlotArea; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.commands.CommandCategory; +import com.github.intellectualsites.plotsquared.plot.commands.MainCommand; +import com.github.intellectualsites.plotsquared.plot.commands.RequiredType; +import com.github.intellectualsites.plotsquared.plot.config.Captions; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; import com.sk89q.worldedit.WorldEdit; @CommandDeclaration( @@ -33,10 +33,10 @@ public class CFIRedirect extends Command { @Override public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { - checkTrue(args.length >= 1, C.COMMAND_SYNTAX, getUsage()); - final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); - checkTrue(plot.isOwner(player.getUUID()), C.NOW_OWNER); - checkTrue(plot.getRunning() == 0, C.WAIT_FOR_TIMER); + checkTrue(args.length >= 1, Captions.COMMAND_SYNTAX, getUsage()); + final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT); + checkTrue(plot.isOwner(player.getUUID()), Captions.NOW_OWNER); + checkTrue(plot.getRunning() == 0, Captions.WAIT_FOR_TIMER); final PlotArea area = plot.getArea(); if (area instanceof SinglePlotArea) { player.sendMessage("The command has been changed to: //cfi"); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweChunkManager.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweChunkManager.java index f1fe00c9a..9c98ff6e3 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweChunkManager.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweChunkManager.java @@ -2,15 +2,15 @@ package com.boydti.fawe.regions.general.plot; import com.boydti.fawe.util.EditSessionBuilder; import com.boydti.fawe.util.TaskManager; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operations; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; @@ -50,8 +50,8 @@ public class FaweChunkManager extends ChunkManager { synchronized (FaweChunkManager.class) { EditSession sessionA = new EditSessionBuilder(pos1.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); EditSession sessionB = new EditSessionBuilder(pos3.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); - CuboidRegion regionA = new CuboidRegion(new Vector(pos1.getX(), pos1.getY(), pos1.getZ()), new Vector(pos2.getX(), pos2.getY(), pos2.getZ())); - CuboidRegion regionB = new CuboidRegion(new Vector(pos3.getX(), pos3.getY(), pos3.getZ()), new Vector(pos4.getX(), pos4.getY(), pos4.getZ())); + CuboidRegion regionA = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); + CuboidRegion regionB = new CuboidRegion(BlockVector3.at(pos3.getX(), pos3.getY(), pos3.getZ()), BlockVector3.at(pos4.getX(), pos4.getY(), pos4.getZ())); ForwardExtentCopy copyA = new ForwardExtentCopy(sessionA, regionA, sessionB, regionB.getMinimumPoint()); ForwardExtentCopy copyB = new ForwardExtentCopy(sessionB, regionB, sessionA, regionA.getMinimumPoint()); try { @@ -76,8 +76,8 @@ public class FaweChunkManager extends ChunkManager { synchronized (FaweChunkManager.class) { EditSession from = new EditSessionBuilder(pos1.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); EditSession to = new EditSessionBuilder(pos3.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); - CuboidRegion region = new CuboidRegion(new Vector(pos1.getX(), pos1.getY(), pos1.getZ()), new Vector(pos2.getX(), pos2.getY(), pos2.getZ())); - ForwardExtentCopy copy = new ForwardExtentCopy(from, region, to, new Vector(pos3.getX(), pos3.getY(), pos3.getZ())); + CuboidRegion region = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); + ForwardExtentCopy copy = new ForwardExtentCopy(from, region, to, BlockVector3.at(pos3.getX(), pos3.getY(), pos3.getZ())); try { Operations.completeLegacy(copy); to.flushQueue(); @@ -99,7 +99,7 @@ public class FaweChunkManager extends ChunkManager { synchronized (FaweChunkManager.class) { EditSession editSession = new EditSessionBuilder(pos1.getWorld()).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); World world = editSession.getWorld(); - CuboidRegion region = new CuboidRegion(new Vector(pos1.getX(), pos1.getY(), pos1.getZ()), new Vector(pos2.getX(), pos2.getY(), pos2.getZ())); + CuboidRegion region = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); world.regenerate(region, editSession); editSession.flushQueue(); TaskManager.IMP.task(whenDone); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweLocalBlockQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweLocalBlockQueue.java index bf1b4a0cf..780d8375a 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweLocalBlockQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweLocalBlockQueue.java @@ -4,15 +4,16 @@ import com.boydti.fawe.FaweAPI; import com.boydti.fawe.FaweCache; import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.util.SetQueue; -import com.intellectualcrafters.jnbt.CompoundTag; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.block.LocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; +import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.biome.Biomes; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.registry.BiomeRegistry; import com.sk89q.worldedit.world.registry.LegacyMapper; @@ -23,10 +24,12 @@ import java.util.List; public class FaweLocalBlockQueue extends LocalBlockQueue { public final FaweQueue IMP; + private final LegacyMapper legacyMapper; public FaweLocalBlockQueue(String world) { super(world); IMP = SetQueue.IMP.getNewQueue(FaweAPI.getWorld(world), true, false); + legacyMapper = LegacyMapper.getInstance(); } @Override @@ -63,10 +66,15 @@ public class FaweLocalBlockQueue extends LocalBlockQueue { public long getModified() { return IMP.getModified(); } - + @Override - public boolean setBlock(int x, int y, int z, int id, int data) { - return IMP.setBlock(x, y, z, LegacyMapper.getInstance().getBlockFromLegacy(id, data)); + public boolean setBlock(final int x, final int y, final int z, final PlotBlock id) { + return setBlock(x, y, z, legacyMapper.getBaseBlockFromPlotBlock(id)); + } + + @Override + public boolean setBlock(final int x, final int y, final int z, final BaseBlock id) { + return IMP.setBlock(x, y, z, id); } @Override diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweSchematicHandler.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweSchematicHandler.java index e5e59f484..dd541e791 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweSchematicHandler.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweSchematicHandler.java @@ -1,27 +1,41 @@ package com.boydti.fawe.regions.general.plot; import com.boydti.fawe.FaweCache; +import com.boydti.fawe.object.FaweOutputStream; import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.clipboard.ReadOnlyClipboard; +import com.boydti.fawe.object.io.FastByteArrayOutputStream; +import com.boydti.fawe.object.io.FastByteArraysInputStream; import com.boydti.fawe.object.io.PGZIPOutputStream; import com.boydti.fawe.util.EditSessionBuilder; +import com.boydti.fawe.util.IOUtil; import com.boydti.fawe.util.SetQueue; import com.boydti.fawe.util.TaskManager; -import com.intellectualcrafters.jnbt.CompoundTag; -import com.intellectualcrafters.jnbt.Tag; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.block.LocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.CompressedCompoundTag; +import com.sk89q.jnbt.CompressedSchematicTag; import com.sk89q.jnbt.NBTOutputStream; +import com.sk89q.jnbt.Tag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.SpongeSchematicWriter; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; +import net.jpountz.lz4.LZ4BlockInputStream; +import net.jpountz.lz4.LZ4BlockOutputStream; + +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -31,6 +45,7 @@ import java.net.URL; import java.util.Map; import java.util.Set; import java.util.UUID; +import java.util.zip.GZIPInputStream; public class FaweSchematicHandler extends SchematicHandler { @Override @@ -53,7 +68,7 @@ public class FaweSchematicHandler extends SchematicHandler { Location[] corners = MainUtil.getCorners(world, regions); Location pos1 = corners[0]; Location pos2 = corners[1]; - final CuboidRegion region = new CuboidRegion(new Vector(pos1.getX(), pos1.getY(), pos1.getZ()), new Vector(pos2.getX(), pos2.getY(), pos2.getZ())); + final CuboidRegion region = new CuboidRegion(BlockVector3.at(pos1.getX(), pos1.getY(), pos1.getZ()), BlockVector3.at(pos2.getX(), pos2.getY(), pos2.getZ())); final EditSession editSession = new EditSessionBuilder(world).checkMemory(false).fastmode(true).limitUnlimited().changeSetNull().autoQueue(false).build(); final int mx = pos1.getX(); @@ -63,10 +78,8 @@ public class FaweSchematicHandler extends SchematicHandler { ReadOnlyClipboard clipboard = ReadOnlyClipboard.of(editSession, region); Clipboard holder = new BlockArrayClipboard(region, clipboard); - // TODO FIXME -// com.sk89q.jnbt.CompoundTag weTag = SchematicWriter.writeTag(holder); -// CompoundTag tag = new CompoundTag((Map) (Map) weTag.getValue()); -// whenDone.run(tag); + CompressedSchematicTag tag = new CompressedSchematicTag(holder); + whenDone.run(tag); } }); } @@ -74,16 +87,30 @@ public class FaweSchematicHandler extends SchematicHandler { @Override public boolean save(CompoundTag tag, String path) { if (tag == null) { - PS.debug("&cCannot save empty tag"); + PlotSquared.debug("&cCannot save empty tag"); return false; } try { - File tmp = MainUtil.getFile(PS.get().IMP.getDirectory(), path); + File tmp = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), path); tmp.getParentFile().mkdirs(); - com.sk89q.jnbt.CompoundTag weTag = (com.sk89q.jnbt.CompoundTag) FaweCache.asTag(tag); - try (OutputStream stream = new FileOutputStream(tmp); NBTOutputStream output = new NBTOutputStream(new PGZIPOutputStream(stream))) { - Map map = weTag.getValue(); - output.writeNamedTag("Schematic", map.containsKey("Schematic") ? map.get("Schematic") : weTag); + if (tag instanceof CompressedCompoundTag) { + CompressedCompoundTag cTag = (CompressedCompoundTag) tag; + if (cTag instanceof CompressedSchematicTag) { + Clipboard clipboard = (Clipboard) cTag.getSource(); + try (OutputStream stream = new FileOutputStream(tmp); NBTOutputStream output = new NBTOutputStream(new BufferedOutputStream(new PGZIPOutputStream(stream)))) { + new SpongeSchematicWriter(output).write(clipboard); + } + } else { + try (OutputStream stream = new FileOutputStream(tmp); BufferedOutputStream output = new BufferedOutputStream(new PGZIPOutputStream(stream))) { + DataInputStream is = cTag.adapt(cTag.getSource()); + IOUtil.copy(is, stream); + } + } + } else { + try (OutputStream stream = new FileOutputStream(tmp); NBTOutputStream output = new NBTOutputStream(new PGZIPOutputStream(stream))) { + Map map = tag.getValue(); + output.writeNamedTag("Schematic", map.containsKey("Schematic") ? map.get("Schematic") : tag); + } } } catch (FileNotFoundException e) { e.printStackTrace(); @@ -97,8 +124,8 @@ public class FaweSchematicHandler extends SchematicHandler { @Override public void upload(final CompoundTag tag, final UUID uuid, final String file, final RunnableVal whenDone) { if (tag == null) { - PS.debug("&cCannot save empty tag"); - com.intellectualcrafters.plot.util.TaskManager.runTask(whenDone); + PlotSquared.debug("&cCannot save empty tag"); + com.github.intellectualsites.plotsquared.plot.util.TaskManager.runTask(whenDone); return; } MainUtil.upload(uuid, file, "schematic", new RunnableVal() { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweTrim.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweTrim.java index 4b1555971..2222f9859 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweTrim.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/FaweTrim.java @@ -1,14 +1,14 @@ package com.boydti.fawe.regions.general.plot; import com.boydti.fawe.util.TaskManager; -import com.intellectualcrafters.plot.commands.CommandCategory; -import com.intellectualcrafters.plot.commands.RequiredType; -import com.intellectualcrafters.plot.commands.SubCommand; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.commands.CommandCategory; +import com.github.intellectualsites.plotsquared.plot.commands.RequiredType; +import com.github.intellectualsites.plotsquared.plot.commands.SubCommand; +import com.github.intellectualsites.plotsquared.plot.config.Captions; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; @CommandDeclaration( command = "trimchunks", @@ -33,7 +33,7 @@ public class FaweTrim extends SubCommand { return false; } if (!WorldUtil.IMP.isWorld(strings[0])) { - C.NOT_VALID_PLOT_WORLD.send(plotPlayer, strings[0]); + Captions.NOT_VALID_PLOT_WORLD.send(plotPlayer, strings[0]); return false; } ran = true; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/MoveTo512.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/MoveTo512.java index 4f539df48..7bc11ec16 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/MoveTo512.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/MoveTo512.java @@ -8,27 +8,27 @@ import com.boydti.fawe.jnbt.anvil.MCAWriter; import com.boydti.fawe.object.FaweChunk; import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.util.SetQueue; -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.commands.CommandCategory; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.commands.RequiredType; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.database.SQLManager; -import com.intellectualcrafters.plot.generator.HybridPlotWorld; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.object.SetupObject; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.commands.CommandCategory; +import com.github.intellectualsites.plotsquared.plot.commands.MainCommand; +import com.github.intellectualsites.plotsquared.plot.commands.RequiredType; +import com.github.intellectualsites.plotsquared.plot.config.Captions; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.database.SQLManager; +import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; +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.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.object.SetupObject; +import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -44,121 +44,121 @@ import java.util.Map; usage = "/plots moveto512 [world]" ) // TODO FIXME -public class MoveTo512 extends Command { +public class MoveTo512 /*extends Command*/ { - public MoveTo512() { - super(MainCommand.getInstance(), true); - } +// public MoveTo512() { +// super(MainCommand.getInstance(), true); +// } +// +// private MCAChunk emptyPlot(MCAChunk chunk, HybridPlotWorld hpw) { +// int maxLayer = (hpw.PLOT_HEIGHT) >> 4; +// for (int i = maxLayer + 1; i < chunk.ids.length; i++) { +// chunk.ids[i] = null; +// chunk.data[i] = null; +// } +// for (int layer = 0; layer <= maxLayer; layer++) { +// byte[] ids = chunk.ids[layer]; +// if (ids == null) { +// ids = chunk.ids[layer] = new byte[4096]; +// chunk.data[layer] = new byte[2048]; +// chunk.skyLight[layer] = new byte[2048]; +// chunk.blockLight[layer] = new byte[2048]; +// } else { +// Arrays.fill(ids, (byte) 0); +// Arrays.fill(chunk.data[layer], (byte) 0); +// Arrays.fill(chunk.skyLight[layer], (byte) 0); +// Arrays.fill(chunk.blockLight[layer], (byte) 0); +// } +// if (layer == maxLayer) { +// int yMax = hpw.PLOT_HEIGHT & 15; +// for (int y = yMax + 1; y < 15; y++) { +// Arrays.fill(chunk.skyLight[layer], y << 7, (y << 7) + 128, (byte) 255); +// } +// if (layer == 0) { +// Arrays.fill(ids, 0, 256, (byte) 7); +// for (int y = 1; y < yMax; y++) { +// int y8 = y << 8; +// Arrays.fill(ids, y8, y8 + 256, (byte) 3); +// } +// } else { +// for (int y = 0; y < yMax; y++) { +// int y8 = y << 8; +// Arrays.fill(ids, y8, y8 + 256, (byte) 3); +// } +// } +// int yMax15 = yMax & 15; +// int yMax158 = yMax15 << 8; +// Arrays.fill(ids, yMax158, yMax158 + 256, (byte) 2); +// if (yMax != 15) { +// Arrays.fill(ids, yMax158 + 256, 4096, (byte) 0); +// } +// } else if (layer == 0){ +// Arrays.fill(ids, 256, 4096, (byte) 3); +// Arrays.fill(ids, 0, 256, (byte) 7); +// } else { +// Arrays.fill(ids, (byte) 3); +// } +// } +// return chunk; +// } +// +// private MCAChunk emptyRoad(MCAChunk chunk, HybridPlotWorld hpw) { +// int maxLayer = (hpw.ROAD_HEIGHT) >> 4; +// for (int i = maxLayer + 1; i < chunk.ids.length; i++) { +// chunk.ids[i] = null; +// chunk.data[i] = null; +// } +// for (int layer = 0; layer <= maxLayer; layer++) { +// byte[] ids = chunk.ids[layer]; +// if (ids == null) { +// ids = chunk.ids[layer] = new byte[4096]; +// chunk.data[layer] = new byte[2048]; +// chunk.skyLight[layer] = new byte[2048]; +// chunk.blockLight[layer] = new byte[2048]; +// } else { +// Arrays.fill(ids, (byte) 0); +// Arrays.fill(chunk.data[layer], (byte) 0); +// Arrays.fill(chunk.skyLight[layer], (byte) 0); +// Arrays.fill(chunk.blockLight[layer], (byte) 0); +// } +// if (layer == maxLayer) { +// int yMax = hpw.ROAD_HEIGHT & 15; +// for (int y = yMax + 1; y < 15; y++) { +// Arrays.fill(chunk.skyLight[layer], y << 7, (y << 7) + 128, (byte) 255); +// } +// if (layer == 0) { +// Arrays.fill(ids, 0, 256, (byte) 7); +// for (int y = 1; y <= yMax; y++) { +// int y8 = y << 8; +// Arrays.fill(ids, y8, y8 + 256, (byte) hpw.ROAD_BLOCK.id); +// } +// } else { +// for (int y = 0; y <= yMax; y++) { +// int y8 = y << 8; +// Arrays.fill(ids, y8, y8 + 256, (byte) hpw.ROAD_BLOCK.id); +// } +// } +// if (yMax != 15) { +// int yMax15 = yMax & 15; +// int yMax158 = yMax15 << 8; +// Arrays.fill(ids, yMax158 + 256, 4096, (byte) 0); +// } +// } else if (layer == 0){ +// Arrays.fill(ids, 256, 4096, (byte) hpw.ROAD_BLOCK.id); +// Arrays.fill(ids, 0, 256, (byte) 7); +// } else { +// Arrays.fill(ids, (byte) hpw.ROAD_BLOCK.id); +// } +// } +// return chunk; +// } - private MCAChunk emptyPlot(MCAChunk chunk, HybridPlotWorld hpw) { - int maxLayer = (hpw.PLOT_HEIGHT) >> 4; - for (int i = maxLayer + 1; i < chunk.ids.length; i++) { - chunk.ids[i] = null; - chunk.data[i] = null; - } - for (int layer = 0; layer <= maxLayer; layer++) { - byte[] ids = chunk.ids[layer]; - if (ids == null) { - ids = chunk.ids[layer] = new byte[4096]; - chunk.data[layer] = new byte[2048]; - chunk.skyLight[layer] = new byte[2048]; - chunk.blockLight[layer] = new byte[2048]; - } else { - Arrays.fill(ids, (byte) 0); - Arrays.fill(chunk.data[layer], (byte) 0); - Arrays.fill(chunk.skyLight[layer], (byte) 0); - Arrays.fill(chunk.blockLight[layer], (byte) 0); - } - if (layer == maxLayer) { - int yMax = hpw.PLOT_HEIGHT & 15; - for (int y = yMax + 1; y < 15; y++) { - Arrays.fill(chunk.skyLight[layer], y << 7, (y << 7) + 128, (byte) 255); - } - if (layer == 0) { - Arrays.fill(ids, 0, 256, (byte) 7); - for (int y = 1; y < yMax; y++) { - int y8 = y << 8; - Arrays.fill(ids, y8, y8 + 256, (byte) 3); - } - } else { - for (int y = 0; y < yMax; y++) { - int y8 = y << 8; - Arrays.fill(ids, y8, y8 + 256, (byte) 3); - } - } - int yMax15 = yMax & 15; - int yMax158 = yMax15 << 8; - Arrays.fill(ids, yMax158, yMax158 + 256, (byte) 2); - if (yMax != 15) { - Arrays.fill(ids, yMax158 + 256, 4096, (byte) 0); - } - } else if (layer == 0){ - Arrays.fill(ids, 256, 4096, (byte) 3); - Arrays.fill(ids, 0, 256, (byte) 7); - } else { - Arrays.fill(ids, (byte) 3); - } - } - return chunk; - } - - private MCAChunk emptyRoad(MCAChunk chunk, HybridPlotWorld hpw) { - int maxLayer = (hpw.ROAD_HEIGHT) >> 4; - for (int i = maxLayer + 1; i < chunk.ids.length; i++) { - chunk.ids[i] = null; - chunk.data[i] = null; - } - for (int layer = 0; layer <= maxLayer; layer++) { - byte[] ids = chunk.ids[layer]; - if (ids == null) { - ids = chunk.ids[layer] = new byte[4096]; - chunk.data[layer] = new byte[2048]; - chunk.skyLight[layer] = new byte[2048]; - chunk.blockLight[layer] = new byte[2048]; - } else { - Arrays.fill(ids, (byte) 0); - Arrays.fill(chunk.data[layer], (byte) 0); - Arrays.fill(chunk.skyLight[layer], (byte) 0); - Arrays.fill(chunk.blockLight[layer], (byte) 0); - } - if (layer == maxLayer) { - int yMax = hpw.ROAD_HEIGHT & 15; - for (int y = yMax + 1; y < 15; y++) { - Arrays.fill(chunk.skyLight[layer], y << 7, (y << 7) + 128, (byte) 255); - } - if (layer == 0) { - Arrays.fill(ids, 0, 256, (byte) 7); - for (int y = 1; y <= yMax; y++) { - int y8 = y << 8; - Arrays.fill(ids, y8, y8 + 256, (byte) hpw.ROAD_BLOCK.id); - } - } else { - for (int y = 0; y <= yMax; y++) { - int y8 = y << 8; - Arrays.fill(ids, y8, y8 + 256, (byte) hpw.ROAD_BLOCK.id); - } - } - if (yMax != 15) { - int yMax15 = yMax & 15; - int yMax158 = yMax15 << 8; - Arrays.fill(ids, yMax158 + 256, 4096, (byte) 0); - } - } else if (layer == 0){ - Arrays.fill(ids, 256, 4096, (byte) hpw.ROAD_BLOCK.id); - Arrays.fill(ids, 0, 256, (byte) 7); - } else { - Arrays.fill(ids, (byte) hpw.ROAD_BLOCK.id); - } - } - return chunk; - } - - @Override - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { -// checkTrue(args.length == 1, C.COMMAND_SYNTAX, getUsage()); +// @Override +// public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { +// checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage()); // PlotArea area = player.getPlotAreaAbs(); -// check(area, C.COMMAND_SYNTAX, getUsage()); -// checkTrue(area instanceof HybridPlotWorld, C.NOT_VALID_HYBRID_PLOT_WORLD); +// check(area, Captions.COMMAND_SYNTAX, getUsage()); +// checkTrue(area instanceof HybridPlotWorld, Captions.NOT_VALID_HYBRID_PLOT_WORLD); // // WorldUtil.IMP.saveWorld(area.worldname); // @@ -167,7 +167,7 @@ public class MoveTo512 extends Command { // // String world = args[0]; // File folder = new File(PS.imp().getWorldContainer(), world + File.separator + "region"); -// checkTrue(!folder.exists(), C.SETUP_WORLD_TAKEN, world); +// checkTrue(!folder.exists(), Captions.SETUP_WORLD_TAKEN, world); // // HybridPlotWorld hpw = (HybridPlotWorld) area; // int minRoad = 7; @@ -368,5 +368,5 @@ public class MoveTo512 extends Command { // object.plotManager = PS.imp().getPluginName(); // object.setupGenerator = PS.imp().getPluginName(); // String created = SetupUtils.manager.setupWorld(object); - } +// } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotRegionFilter.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotRegionFilter.java index e32e4a856..ffade473b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotRegionFilter.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotRegionFilter.java @@ -1,10 +1,11 @@ package com.boydti.fawe.regions.general.plot; import com.boydti.fawe.regions.general.CuboidRegionFilter; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.sk89q.worldedit.BlockVector2D; +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; @@ -21,9 +22,9 @@ public class PlotRegionFilter extends CuboidRegionFilter { public void calculateRegions() { ArrayList plots = new ArrayList<>(area.getPlots()); for (Plot plot : plots) { - Location pos1 = plot.getBottom(); - Location pos2 = plot.getTop(); - add(new BlockVector2D(pos1.getX(), pos1.getZ()), new BlockVector2D(pos2.getX(), pos2.getZ())); + Location bottom = plot.getCorners()[0]; + Location top = plot.getCorners()[1]; + add(BlockVector2.at(bottom.getX(), bottom.getZ()), BlockVector2.at(top.getX(), top.getZ())); } } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotSetBiome.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotSetBiome.java index 2d016eed3..b87c8d912 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotSetBiome.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotSetBiome.java @@ -1,35 +1,34 @@ package com.boydti.fawe.regions.general.plot; -import com.boydti.fawe.FaweAPI; import com.boydti.fawe.object.FawePlayer; -import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.util.EditSessionBuilder; import com.boydti.fawe.util.TaskManager; -import com.intellectualcrafters.plot.commands.CommandCategory; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.commands.RequiredType; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.commands.CommandCategory; +import com.github.intellectualsites.plotsquared.plot.commands.MainCommand; +import com.github.intellectualsites.plotsquared.plot.commands.RequiredType; +import com.github.intellectualsites.plotsquared.plot.config.Captions; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.extension.platform.Capability; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.biome.Biomes; import com.sk89q.worldedit.world.registry.BiomeRegistry; import java.util.HashSet; import java.util.List; +import java.util.concurrent.ThreadLocalRandom; @CommandDeclaration( command = "generatebiome", @@ -47,28 +46,28 @@ public class PlotSetBiome extends Command { @Override public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { - final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); - checkTrue(plot.isOwner(player.getUUID()) || Permissions.hasPermission(player, "plots.admin.command.generatebiome"), C.NO_PLOT_PERMS); + final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT); + checkTrue(plot.isOwner(player.getUUID()) || Permissions.hasPermission(player, "plots.admin.command.generatebiome"), Captions.NO_PLOT_PERMS); if (plot.getRunning() != 0) { - C.WAIT_FOR_TIMER.send(player); + Captions.WAIT_FOR_TIMER.send(player); return; } - checkTrue(args.length == 1, C.COMMAND_SYNTAX, getUsage()); + checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage()); final HashSet regions = plot.getRegions(); BiomeRegistry biomeRegistry = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBiomeRegistry(); List knownBiomes = biomeRegistry.getBiomes(); final BaseBiome biome = Biomes.findBiomeByName(knownBiomes, args[0], biomeRegistry); if (biome == null) { - String biomes = StringMan.join(WorldUtil.IMP.getBiomeList(), C.BLOCK_LIST_SEPARATER.s()); - C.NEED_BIOME.send(player); - MainUtil.sendMessage(player, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + biomes); + String biomes = StringMan.join(WorldUtil.IMP.getBiomeList(), Captions.BLOCK_LIST_SEPARATER.s()); + Captions.NEED_BIOME.send(player); + MainUtil.sendMessage(player, Captions.SUBCOMMAND_SET_OPTIONS_HEADER.s() + biomes); return; } confirm.run(this, new Runnable() { @Override public void run() { if (plot.getRunning() != 0) { - C.WAIT_FOR_TIMER.send(player); + Captions.WAIT_FOR_TIMER.send(player); return; } plot.addRunning(); @@ -82,9 +81,9 @@ public class PlotSetBiome extends Command { .player(FawePlayer.wrap(player.getName())) .limitUnlimited() .build(); - long seed = PseudoRandom.random.nextLong(); + long seed = ThreadLocalRandom.current().nextLong(); for (RegionWrapper region : regions) { - CuboidRegion cuboid = new CuboidRegion(new Vector(region.minX, 0, region.minZ), new Vector(region.maxX, 256, region.maxZ)); + CuboidRegion cuboid = new CuboidRegion(BlockVector3.at(region.minX, 0, region.minZ), BlockVector3.at(region.maxX, 256, region.maxZ)); session.regenerate(cuboid, biome, seed); } session.flushQueue(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotSquaredFeature.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotSquaredFeature.java index d313d4f19..1dc34efd0 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotSquaredFeature.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotSquaredFeature.java @@ -7,23 +7,23 @@ import com.boydti.fawe.regions.FaweMask; import com.boydti.fawe.regions.FaweMaskManager; import com.boydti.fawe.regions.SimpleRegion; import com.boydti.fawe.regions.general.RegionFilter; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.generator.HybridPlotManager; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; -import com.intellectualcrafters.plot.util.block.QueueProvider; -import com.plotsquared.listener.WEManager; -import com.sk89q.worldedit.BlockVector; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +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.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; +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.github.intellectualsites.plotsquared.plot.listener.WEManager; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import java.util.HashSet; @@ -33,7 +33,7 @@ public class PlotSquaredFeature extends FaweMaskManager { public PlotSquaredFeature() { super("PlotSquared"); Fawe.debug("Optimizing PlotSquared"); - PS.get().worldedit = null; +// PlotSquared.get().worldedit = null; setupBlockQueue(); setupSchematicHandler(); setupChunkManager(); @@ -44,10 +44,10 @@ public class PlotSquaredFeature extends FaweMaskManager { new PlotSetBiome(); } try { - new MoveTo512(); +// new MoveTo512(); if (Settings.Enabled_Components.WORLDS) { new ReplaceAll(); - new CFIRedirect(); +// new CFIRedirect(); } } catch (Throwable e) { Fawe.debug("You need to update PlotSquared to access the CFI and REPLACEALL commands"); @@ -94,7 +94,7 @@ public class PlotSquaredFeature extends FaweMaskManager { return false; } UUID uid = fp.getUUID(); - return !Flags.NO_WORLDEDIT.isTrue(plot) && ((plot.isOwner(uid) || (type == MaskType.MEMBER && (plot.getTrusted().contains(uid) || plot.getTrusted().contains(DBFunc.everyone) || ((plot.getMembers().contains(uid) || plot.getMembers().contains(DBFunc.everyone)) && fp.hasPermission("fawe.plotsquared.member"))))) || fp.hasPermission("fawe.plotsquared.admin")); + return !Flags.NO_WORLDEDIT.isTrue(plot) && ((plot.isOwner(uid) || (type == MaskType.MEMBER && (plot.getTrusted().contains(uid) || plot.getTrusted().contains(DBFunc.EVERYONE) || ((plot.getMembers().contains(uid) || plot.getMembers().contains(DBFunc.EVERYONE)) && fp.hasPermission("fawe.plotsquared.member"))))) || fp.hasPermission("fawe.plotsquared.admin")); } @Override @@ -125,8 +125,8 @@ public class PlotSquaredFeature extends FaweMaskManager { faweRegions.add(new com.boydti.fawe.object.RegionWrapper(current.minX, current.maxX, min, max, current.minZ, current.maxZ)); } final RegionWrapper region = regions.iterator().next(); - final BlockVector pos1 = new BlockVector(region.minX, min, region.minZ); - final BlockVector pos2 = new BlockVector(region.maxX, max, region.maxZ); + final BlockVector3 pos1 = BlockVector3.at(region.minX, min, region.minZ); + final BlockVector3 pos2 = BlockVector3.at(region.maxX, max, region.maxZ); final Plot finalPlot = plot; if (Settings.Done.RESTRICT_BUILDING && Flags.DONE.isSet(finalPlot) || regions.isEmpty()) { return null; @@ -162,7 +162,7 @@ public class PlotSquaredFeature extends FaweMaskManager { @Override public RegionFilter getFilter(String world) { - PlotArea area = PS.get().getPlotArea(world, null); + PlotArea area = PlotSquared.get().getPlotArea(world, null); if (area != null) return new PlotRegionFilter(area); return null; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotTrim.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotTrim.java index 5392eff6e..599e519bb 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotTrim.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/PlotTrim.java @@ -8,13 +8,13 @@ import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.MathMan; import com.boydti.fawe.util.SetQueue; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.expiry.ExpireManager; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; +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.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -87,7 +87,7 @@ public class PlotTrim { } }); ArrayList plots = new ArrayList<>(); - plots.addAll(PS.get().getPlots(area)); + plots.addAll(PlotSquared.get().getPlots(area)); if (ExpireManager.IMP != null) { plots.removeAll(ExpireManager.IMP.getPendingExpired()); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/ReplaceAll.java b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/ReplaceAll.java index 8d8b96674..80aa7e704 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/ReplaceAll.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/regions/general/plot/ReplaceAll.java @@ -5,19 +5,19 @@ import com.boydti.fawe.object.RunnableVal; import com.boydti.fawe.util.StringMan; import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.wrappers.FakePlayer; -import com.intellectualcrafters.plot.commands.CommandCategory; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.commands.RequiredType; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.object.worlds.SinglePlotArea; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.commands.CommandCategory; +import com.github.intellectualsites.plotsquared.plot.commands.MainCommand; +import com.github.intellectualsites.plotsquared.plot.commands.RequiredType; +import com.github.intellectualsites.plotsquared.plot.config.Captions; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; +import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.extension.platform.CommandManager; @@ -36,15 +36,15 @@ public class ReplaceAll extends Command { @Override public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { - checkTrue(args.length >= 1, C.COMMAND_SYNTAX, getUsage()); - final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); - checkTrue(plot.isOwner(player.getUUID()), C.NOW_OWNER); - checkTrue(plot.getRunning() == 0, C.WAIT_FOR_TIMER); + checkTrue(args.length >= 1, Captions.COMMAND_SYNTAX, getUsage()); + final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT); + checkTrue(plot.isOwner(player.getUUID()), Captions.NOW_OWNER); + checkTrue(plot.getRunning() == 0, Captions.WAIT_FOR_TIMER); final PlotArea area = plot.getArea(); if (area instanceof SinglePlotArea) { plot.addRunning(); FawePlayer fp = FawePlayer.wrap(player.getName()); - C.TASK_START.send(player); + Captions.TASK_START.send(player); TaskManager.IMP.async(new Runnable() { @Override public void run() { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/CachedTextureUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/CachedTextureUtil.java index 5f69745c2..a9ae2f2cb 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/CachedTextureUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/CachedTextureUtil.java @@ -1,7 +1,7 @@ package com.boydti.fawe.util; import com.boydti.fawe.FaweCache; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; @@ -10,9 +10,9 @@ import java.io.FileNotFoundException; public class CachedTextureUtil extends DelegateTextureUtil { private final TextureUtil parent; - private transient Int2ObjectOpenHashMap colorBlockMap; + private transient Int2ObjectOpenHashMap colorBlockMap; private transient Int2ObjectOpenHashMap colorBiomeMap; - private transient Int2ObjectOpenHashMap colorLayerMap; + private transient Int2ObjectOpenHashMap colorLayerMap; public CachedTextureUtil(TextureUtil parent) throws FileNotFoundException { super(parent); @@ -23,8 +23,8 @@ public class CachedTextureUtil extends DelegateTextureUtil { } @Override - public BlockTypes[] getNearestLayer(int color) { - BlockTypes[] closest = colorLayerMap.get(color); + public BlockType[] getNearestLayer(int color) { + BlockType[] closest = colorLayerMap.get(color); if (closest != null) { return closest; } @@ -49,12 +49,12 @@ public class CachedTextureUtil extends DelegateTextureUtil { } @Override - public BlockTypes getNearestBlock(int color) { - BlockTypes value = colorBlockMap.get(color); + public BlockType getNearestBlock(int color) { + BlockType value = colorBlockMap.get(color); if (value != null) { return value; } - BlockTypes result = parent.getNearestBlock(color); + BlockType result = parent.getNearestBlock(color); if (result != null) { colorBlockMap.put((int) color, result); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/DelegateTextureUtil.java b/worldedit-core/src/main/java/com/boydti/fawe/util/DelegateTextureUtil.java index 5dfbede85..5aa095f62 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/DelegateTextureUtil.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/DelegateTextureUtil.java @@ -1,6 +1,6 @@ package com.boydti.fawe.util; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; @@ -19,7 +19,7 @@ public class DelegateTextureUtil extends TextureUtil { } @Override - public BlockTypes getNearestBlock(int color) { + public BlockType getNearestBlock(int color) { return parent.getNearestBlock(color); } @@ -34,7 +34,7 @@ public class DelegateTextureUtil extends TextureUtil { } @Override - public BlockTypes[] getNearestLayer(int color) { + public BlockType[] getNearestLayer(int color) { return parent.getNearestLayer(color); } 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 1c32412fa..25a711786 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 @@ -1,7 +1,7 @@ package com.boydti.fawe.util; import com.boydti.fawe.FaweCache; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; @@ -26,14 +26,14 @@ public class FilteredTextureUtil extends TextureUtil { this.validBlockIds = new int[distances.length]; int num = 0; for (int i = 0; i < parent.validBlockIds.length; i++) { - BlockTypes block = BlockTypes.get(parent.validBlockIds[i]); + BlockType block = BlockTypes.get(parent.validBlockIds[i]); if (blocks.contains(block)) num++; } this.validBlockIds = new int[num]; this.validColors = new int[num]; num = 0; for (int i = 0; i < parent.validBlockIds.length; i++) { - BlockTypes block = BlockTypes.get(parent.validBlockIds[i]); + BlockType block = BlockTypes.get(parent.validBlockIds[i]); if (blocks.contains(block)) { validBlockIds[num] = parent.validBlockIds[i]; validColors[num++] = parent.validColors[i]; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/IncendoPaster.java b/worldedit-core/src/main/java/com/boydti/fawe/util/IncendoPaster.java index 4f0ce28e2..58fb8fa6b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/IncendoPaster.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/IncendoPaster.java @@ -207,7 +207,7 @@ public final class IncendoPaster { b.append("os.name: '").append(System.getProperty("os.name")).append("'\n"); b.append("os.version: '").append(System.getProperty("os.version")).append("'\n\n"); b.append("# Okay :D Great. You are now ready to create your bug report!"); - b.append("\n# You can do so at https://github.com/boy0001/FastAsyncWorldedit/issues"); + b.append("\n# You can do so at https://github.com/IntellectualSites/FastAsyncWorldEdit-1.13/issues"); b.append("\n# or via our Discord at https://discord.gg/ngZCzbU"); incendoPaster.addFile(new IncendoPaster.PasteFile("information", b.toString())); @@ -224,6 +224,7 @@ public final class IncendoPaster { } incendoPaster.addFile(new PasteFile("config.yml", readFile(new File(Fawe.imp().getDirectory(), "config.yml")))); + incendoPaster.addFile(new PasteFile("config-legacy.yml", readFile(new File(Fawe.imp().getDirectory(), "config-legacy.yml")))); incendoPaster.addFile(new PasteFile("message.yml", readFile(new File(Fawe.imp().getDirectory(), "message.yml")))); incendoPaster.addFile(new PasteFile("commands.yml", readFile(new File(Fawe.imp().getDirectory(), "commands.yml")))); 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 90d60c551..20ada4eb8 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 @@ -12,6 +12,7 @@ import com.github.luben.zstd.ZstdOutputStream; import com.sk89q.jnbt.*; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.history.changeset.ChangeSet; import com.sk89q.worldedit.util.Location; import java.awt.Graphics2D; @@ -889,7 +890,7 @@ public class MainUtil { public static File resolve(File dir, String filename, @Nullable ClipboardFormat format, boolean allowDir) { if (format != null) { if (!filename.matches(".*\\.[\\w].*")) { - filename = filename + "." + format.getExtension(); + filename = filename + "." + format.getPrimaryFileExtension(); } return MainUtil.resolveRelative(new File(dir, filename)); } @@ -897,8 +898,8 @@ public class MainUtil { File file = MainUtil.resolveRelative(new File(dir, filename)); if (file.exists() && file.isDirectory()) return file; } - for (ClipboardFormat f : ClipboardFormat.values) { - File file = MainUtil.resolveRelative(new File(dir, filename + "." + f.getExtension())); + for (ClipboardFormat f : ClipboardFormats.getAll()) { + File file = MainUtil.resolveRelative(new File(dir, filename + "." + f.getPrimaryFileExtension())); if (file.exists()) return file; } return null; 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 d4841d92b..461f760e4 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 @@ -1,11 +1,10 @@ package com.boydti.fawe.util; -import com.boydti.fawe.object.PseudoRandom; import com.sk89q.worldedit.world.block.BlockType; -import com.sk89q.worldedit.world.block.BlockTypes; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import java.io.FileNotFoundException; +import java.util.concurrent.ThreadLocalRandom; public class RandomTextureUtil extends CachedTextureUtil { @@ -33,9 +32,10 @@ public class RandomTextureUtil extends CachedTextureUtil { private int random(int i) { if (i < 0) { - return -PseudoRandom.random.nextInt((-i)); + int i1 = (-i); + return -ThreadLocalRandom.current().nextInt(i1); } else { - return PseudoRandom.random.nextInt(i); + return ThreadLocalRandom.current().nextInt(i); } } @@ -79,14 +79,14 @@ public class RandomTextureUtil extends CachedTextureUtil { } @Override - public BlockTypes getNearestBlock(int color) { + public BlockType getNearestBlock(int color) { int offsetColor = offsets.getOrDefault(color, 0); if (offsetColor != 0) { offsetColor = addRandomColor(color, offsetColor); } else { offsetColor = color; } - BlockTypes res = super.getNearestBlock(offsetColor); + BlockType res = super.getNearestBlock(offsetColor); if (res == null) return null; int newColor = getColor(res); { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/SetQueue.java b/worldedit-core/src/main/java/com/boydti/fawe/util/SetQueue.java index 536f3202a..28a174870 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/SetQueue.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/SetQueue.java @@ -73,120 +73,117 @@ public class SetQueue { public SetQueue() { tasks = new ConcurrentLinkedDeque<>(); - activeQueues = new ConcurrentLinkedDeque(); + activeQueues = new ConcurrentLinkedDeque<>(); inactiveQueues = new ConcurrentLinkedDeque<>(); if (TaskManager.IMP == null) return; - TaskManager.IMP.repeat(new Runnable() { - @Override - public void run() { - try { - long now = System.currentTimeMillis(); - boolean empty = (inactiveQueues.isEmpty() && activeQueues.isEmpty()); - boolean emptyTasks = tasks.isEmpty(); - if (emptyTasks && empty) { - last = now; - runEmptyTasks(); - return; - } + TaskManager.IMP.repeat(() -> { + try { + long now = System.currentTimeMillis(); + boolean empty = (inactiveQueues.isEmpty() && activeQueues.isEmpty()); + boolean emptyTasks = tasks.isEmpty(); + if (emptyTasks && empty) { + last = now; + runEmptyTasks(); + return; + } - targetTPS = 18 - Math.max(Settings.IMP.QUEUE.EXTRA_TIME_MS * 0.05, 0); + targetTPS = 18 - Math.max(Settings.IMP.QUEUE.EXTRA_TIME_MS * 0.05, 0); - long diff = (50 + SetQueue.this.last) - (SetQueue.this.last = now); - long absDiff = Math.abs(diff); - if (diff == 0) { - allocate = Math.min(50, allocate + 1); - } else if (diff < 0) { - allocate = Math.max(5, allocate + diff); - } else if (!Fawe.get().getTimer().isAbove(targetTPS)) { - allocate = Math.max(5, allocate - 1); - } + long diff = (50 + SetQueue.this.last) - (SetQueue.this.last = now); + long absDiff = Math.abs(diff); + if (diff == 0) { + allocate = Math.min(50, allocate + 1); + } else if (diff < 0) { + allocate = Math.max(5, allocate + diff); + } else if (!Fawe.get().getTimer().isAbove(targetTPS)) { + allocate = Math.max(5, allocate - 1); + } - long currentAllocate = allocate - absDiff; + long currentAllocate = allocate - absDiff; - if (!emptyTasks) { - long taskAllocate = activeQueues.isEmpty() ? currentAllocate : 1 + (currentAllocate >> 1); - long used = 0; - boolean wait = false; - do { - Runnable task = tasks.poll(); - if (task == null) { - if (wait) { - synchronized (tasks) { - tasks.wait(1); - } - task = tasks.poll(); - wait = false; - } else { - break; + if (!emptyTasks) { + long taskAllocate = activeQueues.isEmpty() ? currentAllocate : 1 + (currentAllocate >> 1); + long used = 0; + boolean wait = false; + do { + Runnable task = tasks.poll(); + if (task == null) { + if (wait) { + synchronized (tasks) { + tasks.wait(1); } - } - if (task != null) { - task.run(); - wait = true; - } - } while ((used = System.currentTimeMillis() - now) < taskAllocate); - currentAllocate -= used; - } - - if (empty) { - runEmptyTasks(); - return; - } - - if (!MemUtil.isMemoryFree()) { - final int mem = MemUtil.calculateMemory(); - if (mem != Integer.MAX_VALUE) { - allocate = Math.max(5, allocate - 1); - if ((mem <= 1) && Settings.IMP.PREVENT_CRASHES) { - for (FaweQueue queue : getAllQueues()) { - queue.saveMemory(); - } - return; - } - if (SetQueue.this.forceChunkSet()) { - System.gc(); + task = tasks.poll(); + wait = false; } else { - SetQueue.this.runEmptyTasks(); + break; + } + } + if (task != null) { + task.run(); + wait = true; + } + } while ((used = System.currentTimeMillis() - now) < taskAllocate); + currentAllocate -= used; + } + + if (empty) { + runEmptyTasks(); + return; + } + + if (!MemUtil.isMemoryFree()) { + final int mem = MemUtil.calculateMemory(); + if (mem != Integer.MAX_VALUE) { + allocate = Math.max(5, allocate - 1); + if ((mem <= 1) && Settings.IMP.PREVENT_CRASHES) { + for (FaweQueue queue : getAllQueues()) { + queue.saveMemory(); } return; } - } - - FaweQueue queue = getNextQueue(); - if (queue == null) { + if (SetQueue.this.forceChunkSet()) { + System.gc(); + } else { + SetQueue.this.runEmptyTasks(); + } return; } + } - long time = (long) Settings.IMP.QUEUE.EXTRA_TIME_MS + currentAllocate - System.currentTimeMillis() + now; - // Disable the async catcher as it can't discern async vs parallel - boolean parallel = Settings.IMP.QUEUE.PARALLEL_THREADS > 1; - queue.startSet(parallel); - try { - if (!queue.next(Settings.IMP.QUEUE.PARALLEL_THREADS, time) && queue.getStage() == QueueStage.ACTIVE) { - queue.setStage(QueueStage.NONE); - queue.runTasks(); - } - } catch (Throwable e) { - pool.awaitQuiescence(Settings.IMP.QUEUE.DISCARD_AFTER_MS, TimeUnit.MILLISECONDS); - completer = new ExecutorCompletionService(pool); - e.printStackTrace(); + FaweQueue queue = getNextQueue(); + if (queue == null) { + return; + } + + long time = (long) Settings.IMP.QUEUE.EXTRA_TIME_MS + currentAllocate - System.currentTimeMillis() + now; + // Disable the async catcher as it can't discern async vs parallel + boolean parallel = Settings.IMP.QUEUE.PARALLEL_THREADS > 1; + queue.startSet(parallel); + try { + if (!queue.next(Settings.IMP.QUEUE.PARALLEL_THREADS, time) && queue.getStage() == QueueStage.ACTIVE) { + queue.setStage(QueueStage.NONE); + queue.runTasks(); } - if (pool.getQueuedSubmissionCount() != 0 || pool.getRunningThreadCount() != 0 || pool.getQueuedTaskCount() != 0) { + } catch (Throwable e) { + pool.awaitQuiescence(Settings.IMP.QUEUE.DISCARD_AFTER_MS, TimeUnit.MILLISECONDS); + completer = new ExecutorCompletionService(pool); + e.printStackTrace(); + } + if (pool.getQueuedSubmissionCount() != 0 || pool.getRunningThreadCount() != 0 || pool.getQueuedTaskCount() != 0) { // if (Fawe.get().isJava8()) - { - pool.awaitQuiescence(Long.MAX_VALUE, TimeUnit.MILLISECONDS); - } + { + pool.awaitQuiescence(Long.MAX_VALUE, TimeUnit.MILLISECONDS); + } // else { // pool.shutdown(); // pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); // pool = new ForkJoinPool(); // completer = new ExecutorCompletionService(pool); // } - } - queue.endSet(parallel); - } catch (Throwable e) { - e.printStackTrace(); } + queue.endSet(parallel); + } catch (Throwable e) { + e.printStackTrace(); } }, 1); } @@ -228,7 +225,7 @@ public class SetQueue { } public Collection getAllQueues() { - ArrayList list = new ArrayList(activeQueues.size() + inactiveQueues.size()); + ArrayList list = new ArrayList<>(activeQueues.size() + inactiveQueues.size()); list.addAll(inactiveQueues); list.addAll(activeQueues); return list; @@ -264,7 +261,7 @@ public class SetQueue { public void flush(FaweQueue queue) { int parallelThreads; - if (Fawe.get().isMainThread()) { + if (Fawe.isMainThread()) { parallelThreads = Settings.IMP.QUEUE.PARALLEL_THREADS; Settings.IMP.QUEUE.PARALLEL_THREADS = 1; } else { diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/ShapeInterpolator.java b/worldedit-core/src/main/java/com/boydti/fawe/util/ShapeInterpolator.java index 6dc9ba418..9d23d38d4 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/ShapeInterpolator.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/ShapeInterpolator.java @@ -167,7 +167,7 @@ public class ShapeInterpolator { bezierCoordinates[0] = curX = movX = coordinates[0]; bezierCoordinates[1] = curY = movY = coordinates[1]; float newX, newY; - final Vector savedPathEndPoints = new Vector(); + final Vector savedPathEndPoints = new Vector<>(); numCoordinates = 2; while (!pi.isDone()) { switch (pi.currentSegment(coordinates)) { @@ -735,4 +735,4 @@ public class ShapeInterpolator { return res; } } -} \ No newline at end of file +} 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 b02de918d..1622629f9 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 @@ -148,7 +148,7 @@ public class StringMan { } public static List split(String input, char delim) { - List result = new ArrayList(); + List result = new ArrayList<>(); int start = 0; int bracket = 0; boolean inQuotes = false; 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 934926d95..793f18b51 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 @@ -67,20 +67,6 @@ public abstract class TaskManager { * @param runnables */ public void parallel(Collection runnables) { -// if (!Fawe.get().isJava8()) { -// ExecutorCompletionService c = new ExecutorCompletionService(pool); -// for (Runnable run : runnables) { -// c.submit(run, null); -// } -// try { -// for (int i = 0; i < runnables.size(); i++) { -// c.take(); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// } -// return; -// } for (Runnable run : runnables) { pool.submit(run); } @@ -124,14 +110,10 @@ public abstract class TaskManager { } for (i = 0; i < threads.length; i++) { final Runnable[] toRun = split[i]; - Thread thread = threads[i] = new Thread(new Runnable() { - @Override - public void run() { - for (int j = 0; j < toRun.length; j++) { - Runnable run = toRun[j]; - if (run != null) { - run.run(); - } + Thread thread = threads[i] = new Thread(() -> { + for (Runnable run : toRun) { + if (run != null) { + run.run(); } } }); @@ -420,7 +402,7 @@ public abstract class TaskManager { } catch (InterruptedException e) { MainUtil.handleError(e); } - if (run.value != null && run.value instanceof RuntimeException) { + if (run.value instanceof RuntimeException) { throw (RuntimeException) run.value; } return (T) run.value; 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 8aa1fd03b..84d3af4ad 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 @@ -8,17 +8,17 @@ import com.boydti.fawe.util.image.ImageUtil; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.blocks.BlockMaterial; + import com.sk89q.worldedit.util.command.binding.Text; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.pattern.BlockPattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.world.registry.BlockMaterial; import com.sk89q.worldedit.world.registry.BundledBlockData; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; @@ -29,6 +29,7 @@ import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; @@ -38,16 +39,18 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; // TODO FIXME -public class TextureUtil implements TextureHolder{ +public class TextureUtil implements TextureHolder { public static TextureUtil fromClipboard(Clipboard clipboard) throws FileNotFoundException { boolean[] ids = new boolean[BlockTypes.size()]; - for (com.sk89q.worldedit.Vector pt : clipboard.getRegion()) { + for (BlockVector3 pt : clipboard.getRegion()) { ids[clipboard.getBlock(pt).getInternalBlockTypeId()] = true; } HashSet blocks = new HashSet<>(); for (int typeId = 0; typeId < ids.length; typeId++) { - if (ids[typeId]) blocks.add(BlockTypes.get(typeId)); + if (ids[typeId]) { + blocks.add(BlockTypes.get(typeId)); + } } return fromBlocks(blocks); } @@ -65,13 +68,14 @@ public class TextureUtil implements TextureHolder{ for (int typeId : tu.getValidBlockIds()) { BlockType block = BlockTypes.get(typeId); pattern.setBlock(block.getDefaultState()); - if (mask.test(Vector.ZERO)) blocks.add(block); + if (mask.test(BlockVector3.ZERO)) { + blocks.add(block); + } } return fromBlocks(blocks); } - @Override - public TextureUtil getTextureUtil() { + @Override public TextureUtil getTextureUtil() { return this; } @@ -100,266 +104,270 @@ public class TextureUtil implements TextureHolder{ * https://github.com/erich666/Mineways/blob/master/Win/biomes.cpp */ protected BiomeColor[] validBiomes; - private BiomeColor[] biomes = new BiomeColor[]{ - // ID Name Temperature, rainfall, grass, foliage colors - // - note: the colors here are just placeholders, they are computed in the program - new BiomeColor(0, "Ocean", 0.5f, 0.5f, 0x92BD59, 0x77AB2F), // default values of temp and rain - new BiomeColor(1, "Plains", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(2, "Desert", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(3, "Extreme Hills", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), - new BiomeColor(4, "Forest", 0.7f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(5, "Taiga", 0.25f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(6, "Swampland", 0.8f, 0.9f, 0x92BD59, 0x77AB2F), - new BiomeColor(7, "River", 0.5f, 0.5f, 0x92BD59, 0x77AB2F), // default values of temp and rain - new BiomeColor(8, "Nether", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(9, "End", 0.5f, 0.5f, 0x92BD59, 0x77AB2F), // default values of temp and rain - new BiomeColor(10, "Frozen Ocean", 0.0f, 0.5f, 0x92BD59, 0x77AB2F), - new BiomeColor(11, "Frozen River", 0.0f, 0.5f, 0x92BD59, 0x77AB2F), - new BiomeColor(12, "Ice Plains", 0.0f, 0.5f, 0x92BD59, 0x77AB2F), - new BiomeColor(13, "Ice Mountains", 0.0f, 0.5f, 0x92BD59, 0x77AB2F), - new BiomeColor(14, "Mushroom Island", 0.9f, 1.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(15, "Mushroom Island Shore", 0.9f, 1.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(16, "Beach", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(17, "Desert Hills", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(18, "Forest Hills", 0.7f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(19, "Taiga Hills", 0.25f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(20, "Extreme Hills Edge", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), - new BiomeColor(21, "Jungle", 0.95f, 0.9f, 0x92BD59, 0x77AB2F), - new BiomeColor(22, "Jungle Hills", 0.95f, 0.9f, 0x92BD59, 0x77AB2F), - new BiomeColor(23, "Jungle Edge", 0.95f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(24, "Deep Ocean", 0.5f, 0.5f, 0x92BD59, 0x77AB2F), - new BiomeColor(25, "Stone Beach", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), - new BiomeColor(26, "Cold Beach", 0.05f, 0.3f, 0x92BD59, 0x77AB2F), - new BiomeColor(27, "Birch Forest", 0.6f, 0.6f, 0x92BD59, 0x77AB2F), - new BiomeColor(28, "Birch Forest Hills", 0.6f, 0.6f, 0x92BD59, 0x77AB2F), - new BiomeColor(29, "Roofed Forest", 0.7f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(30, "Cold Taiga", -0.5f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(31, "Cold Taiga Hills", -0.5f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(32, "Mega Taiga", 0.3f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(33, "Mega Taiga Hills", 0.3f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(34, "Extreme Hills+", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), - new BiomeColor(35, "Savanna", 1.2f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(36, "Savanna Plateau", 1.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(37, "Mesa", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(38, "Mesa Plateau F", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(39, "Mesa Plateau", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(40, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(41, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(42, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(43, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(44, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(45, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(46, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(47, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(48, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(49, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(50, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(51, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(52, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(53, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(54, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(55, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(56, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(57, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(58, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(59, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(60, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(61, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(62, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(63, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(64, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(65, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(66, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(67, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(68, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(69, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(70, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(71, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(72, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(73, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(74, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(75, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(76, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(77, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(78, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(79, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(80, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(81, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(82, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(83, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(84, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(85, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(86, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(87, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(88, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(89, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(90, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(91, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(92, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(93, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(94, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(95, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(96, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(97, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(98, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(99, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(100, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(101, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(102, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(103, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(104, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(105, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(106, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(107, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(108, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(109, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(110, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(111, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(112, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(113, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(114, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(115, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(116, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(117, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(118, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(119, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(120, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(121, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(122, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(123, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(124, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(125, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(126, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(127, "The Void", 0.5f, 0.5f, 0x92BD59, 0x77AB2F), // default values of temp and rain; also, no height differences - new BiomeColor(128, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(129, "Sunflower Plains", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(130, "Desert M", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(131, "Extreme Hills M", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), - new BiomeColor(132, "Flower Forest", 0.7f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(133, "Taiga M", 0.25f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(134, "Swampland M", 0.8f, 0.9f, 0x92BD59, 0x77AB2F), - new BiomeColor(135, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(136, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(137, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(138, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(139, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(140, "Ice Plains Spikes", 0.0f, 0.5f, 0x92BD59, 0x77AB2F), - new BiomeColor(141, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(142, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(143, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(144, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(145, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(146, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(147, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(148, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(149, "Jungle M", 0.95f, 0.9f, 0x92BD59, 0x77AB2F), - new BiomeColor(150, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(151, "JungleEdge M", 0.95f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(152, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(153, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(154, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(155, "Birch Forest M", 0.6f, 0.6f, 0x92BD59, 0x77AB2F), - new BiomeColor(156, "Birch Forest Hills M", 0.6f, 0.6f, 0x92BD59, 0x77AB2F), - new BiomeColor(157, "Roofed Forest M", 0.7f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(158, "Cold Taiga M", -0.5f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(159, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(160, "Mega Spruce Taiga", 0.25f, 0.8f, 0x92BD59, 0x77AB2F), // special exception, temperature not 0.3 - new BiomeColor(161, "Mega Spruce Taiga Hills", 0.25f, 0.8f, 0x92BD59, 0x77AB2F), - new BiomeColor(162, "Extreme Hills+ M", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), - new BiomeColor(163, "Savanna M", 1.1f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(164, "Savanna Plateau M", 1.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(165, "Mesa (Bryce)", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(166, "Mesa Plateau F M", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(167, "Mesa Plateau M", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), - new BiomeColor(168, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(169, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(170, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(171, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(172, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(173, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(174, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(175, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(176, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(177, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(178, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(179, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(180, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(181, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(182, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(183, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(184, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(185, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(186, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(187, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(188, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(189, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(190, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(191, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(192, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(193, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(194, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(195, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(196, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(197, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(198, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(199, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(200, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(201, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(202, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(203, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(204, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(205, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(206, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(207, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(208, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(209, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(210, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(211, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(212, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(213, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(214, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(215, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(216, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(217, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(218, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(219, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(220, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(221, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(222, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(223, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(224, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(225, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(226, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(227, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(228, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(229, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(230, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(231, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(232, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(233, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(234, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(235, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(236, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(237, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(238, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(239, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(240, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(241, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(242, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(243, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(244, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(245, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(246, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(247, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(248, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(249, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(250, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - new BiomeColor(251, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), - 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), - }; + private BiomeColor[] biomes = new BiomeColor[] { + // ID Name Temperature, rainfall, grass, foliage colors + // - note: the colors here are just placeholders, they are computed in the program + new BiomeColor(0, "Ocean", 0.5f, 0.5f, 0x92BD59, 0x77AB2F), + // default values of temp and rain + new BiomeColor(1, "Plains", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(2, "Desert", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(3, "Extreme Hills", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), + new BiomeColor(4, "Forest", 0.7f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(5, "Taiga", 0.25f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(6, "Swampland", 0.8f, 0.9f, 0x92BD59, 0x77AB2F), + new BiomeColor(7, "River", 0.5f, 0.5f, 0x92BD59, 0x77AB2F), + // default values of temp and rain + new BiomeColor(8, "Nether", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(9, "End", 0.5f, 0.5f, 0x92BD59, 0x77AB2F), + // default values of temp and rain + new BiomeColor(10, "Frozen Ocean", 0.0f, 0.5f, 0x92BD59, 0x77AB2F), + new BiomeColor(11, "Frozen River", 0.0f, 0.5f, 0x92BD59, 0x77AB2F), + new BiomeColor(12, "Ice Plains", 0.0f, 0.5f, 0x92BD59, 0x77AB2F), + new BiomeColor(13, "Ice Mountains", 0.0f, 0.5f, 0x92BD59, 0x77AB2F), + new BiomeColor(14, "Mushroom Island", 0.9f, 1.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(15, "Mushroom Island Shore", 0.9f, 1.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(16, "Beach", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(17, "Desert Hills", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(18, "Forest Hills", 0.7f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(19, "Taiga Hills", 0.25f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(20, "Extreme Hills Edge", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), + new BiomeColor(21, "Jungle", 0.95f, 0.9f, 0x92BD59, 0x77AB2F), + new BiomeColor(22, "Jungle Hills", 0.95f, 0.9f, 0x92BD59, 0x77AB2F), + new BiomeColor(23, "Jungle Edge", 0.95f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(24, "Deep Ocean", 0.5f, 0.5f, 0x92BD59, 0x77AB2F), + new BiomeColor(25, "Stone Beach", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), + new BiomeColor(26, "Cold Beach", 0.05f, 0.3f, 0x92BD59, 0x77AB2F), + new BiomeColor(27, "Birch Forest", 0.6f, 0.6f, 0x92BD59, 0x77AB2F), + new BiomeColor(28, "Birch Forest Hills", 0.6f, 0.6f, 0x92BD59, 0x77AB2F), + new BiomeColor(29, "Roofed Forest", 0.7f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(30, "Cold Taiga", -0.5f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(31, "Cold Taiga Hills", -0.5f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(32, "Mega Taiga", 0.3f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(33, "Mega Taiga Hills", 0.3f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(34, "Extreme Hills+", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), + new BiomeColor(35, "Savanna", 1.2f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(36, "Savanna Plateau", 1.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(37, "Mesa", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(38, "Mesa Plateau F", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(39, "Mesa Plateau", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(40, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(41, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(42, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(43, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(44, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(45, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(46, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(47, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(48, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(49, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(50, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(51, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(52, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(53, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(54, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(55, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(56, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(57, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(58, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(59, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(60, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(61, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(62, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(63, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(64, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(65, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(66, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(67, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(68, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(69, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(70, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(71, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(72, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(73, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(74, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(75, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(76, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(77, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(78, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(79, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(80, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(81, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(82, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(83, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(84, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(85, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(86, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(87, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(88, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(89, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(90, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(91, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(92, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(93, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(94, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(95, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(96, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(97, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(98, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(99, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(100, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(101, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(102, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(103, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(104, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(105, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(106, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(107, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(108, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(109, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(110, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(111, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(112, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(113, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(114, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(115, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(116, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(117, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(118, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(119, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(120, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(121, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(122, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(123, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(124, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(125, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(126, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(127, "The Void", 0.5f, 0.5f, 0x92BD59, 0x77AB2F), + // default values of temp and rain; also, no height differences + new BiomeColor(128, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(129, "Sunflower Plains", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(130, "Desert M", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(131, "Extreme Hills M", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), + new BiomeColor(132, "Flower Forest", 0.7f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(133, "Taiga M", 0.25f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(134, "Swampland M", 0.8f, 0.9f, 0x92BD59, 0x77AB2F), + new BiomeColor(135, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(136, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(137, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(138, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(139, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(140, "Ice Plains Spikes", 0.0f, 0.5f, 0x92BD59, 0x77AB2F), + new BiomeColor(141, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(142, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(143, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(144, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(145, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(146, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(147, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(148, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(149, "Jungle M", 0.95f, 0.9f, 0x92BD59, 0x77AB2F), + new BiomeColor(150, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(151, "JungleEdge M", 0.95f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(152, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(153, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(154, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(155, "Birch Forest M", 0.6f, 0.6f, 0x92BD59, 0x77AB2F), + new BiomeColor(156, "Birch Forest Hills M", 0.6f, 0.6f, 0x92BD59, 0x77AB2F), + new BiomeColor(157, "Roofed Forest M", 0.7f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(158, "Cold Taiga M", -0.5f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(159, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(160, "Mega Spruce Taiga", 0.25f, 0.8f, 0x92BD59, 0x77AB2F), + // special exception, temperature not 0.3 + new BiomeColor(161, "Mega Spruce Taiga Hills", 0.25f, 0.8f, 0x92BD59, 0x77AB2F), + new BiomeColor(162, "Extreme Hills+ M", 0.2f, 0.3f, 0x92BD59, 0x77AB2F), + new BiomeColor(163, "Savanna M", 1.1f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(164, "Savanna Plateau M", 1.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(165, "Mesa (Bryce)", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(166, "Mesa Plateau F M", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(167, "Mesa Plateau M", 2.0f, 0.0f, 0x92BD59, 0x77AB2F), + new BiomeColor(168, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(169, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(170, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(171, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(172, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(173, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(174, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(175, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(176, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(177, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(178, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(179, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(180, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(181, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(182, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(183, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(184, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(185, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(186, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(187, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(188, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(189, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(190, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(191, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(192, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(193, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(194, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(195, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(196, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(197, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(198, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(199, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(200, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(201, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(202, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(203, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(204, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(205, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(206, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(207, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(208, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(209, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(210, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(211, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(212, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(213, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(214, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(215, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(216, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(217, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(218, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(219, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(220, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(221, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(222, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(223, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(224, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(225, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(226, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(227, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(228, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(229, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(230, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(231, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(232, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(233, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(234, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(235, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(236, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(237, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(238, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(239, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(240, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(241, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(242, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(243, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(244, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(245, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(246, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(247, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(248, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(249, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(250, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + new BiomeColor(251, "Unknown Biome", 0.8f, 0.4f, 0x92BD59, 0x77AB2F), + 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),}; public TextureUtil() throws FileNotFoundException { this(MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.TEXTURES)); @@ -368,11 +376,12 @@ public class TextureUtil implements TextureHolder{ public TextureUtil(File folder) throws FileNotFoundException { this.folder = folder; if (!folder.exists()) { - throw new FileNotFoundException("Please create a `FastAsyncWorldEdit/textures` folder with `.minecraft/versions` jar or mods in it."); + throw new FileNotFoundException( + "Please create a `FastAsyncWorldEdit/textures` folder with `.minecraft/versions` jar or mods in it."); } } - public BlockTypes getNearestBlock(int color) { + public BlockType getNearestBlock(int color) { long min = Long.MAX_VALUE; int closest = 0; int red1 = (color >> 16) & 0xFF; @@ -389,13 +398,17 @@ public class TextureUtil implements TextureHolder{ } } } - if (min == Long.MAX_VALUE) return null; + if (min == Long.MAX_VALUE) { + return null; + } return BlockTypes.get(closest); } public BlockType getNearestBlock(BlockType block) { int color = getColor(block); - if (color == 0) return null; + if (color == 0) { + return null; + } return getNextNearestBlock(color); } @@ -416,11 +429,13 @@ public class TextureUtil implements TextureHolder{ } } } - if (min == Long.MAX_VALUE) return null; + if (min == Long.MAX_VALUE) { + return null; + } return BlockTypes.get(closest); } - private BlockTypes[] layerBuffer = new BlockTypes[2]; + private BlockType[] layerBuffer = new BlockType[2]; /** * Returns the block combined ids as an array @@ -428,7 +443,7 @@ public class TextureUtil implements TextureHolder{ * @param color * @return */ - public BlockTypes[] getNearestLayer(int color) { + public BlockType[] getNearestLayer(int color) { int[] closest = null; long min = Long.MAX_VALUE; int red1 = (color >> 16) & 0xFF; @@ -466,13 +481,15 @@ public class TextureUtil implements TextureHolder{ return biomes[biome]; } - public boolean getIsBlockCloserThanBiome(int[] blockAndBiomeIdOutput, int color, int biomePriority) { + public boolean getIsBlockCloserThanBiome(int[] blockAndBiomeIdOutput, int color, + int biomePriority) { BlockType block = getNearestBlock(color); TextureUtil.BiomeColor biome = getNearestBiome(color); int blockColor = getColor(block); blockAndBiomeIdOutput[0] = block.getInternalId(); blockAndBiomeIdOutput[1] = biome.id; - if (colorDistance(biome.grassCombined, color) - biomePriority > colorDistance(blockColor, color)) { + if (colorDistance(biome.grassCombined, color) - biomePriority > colorDistance(blockColor, + color)) { return true; } return false; @@ -513,8 +530,7 @@ public class TextureUtil implements TextureHolder{ int red = (color >> 16) & 0xFF; int green = (color >> 8) & 0xFF; int blue = (color >> 0) & 0xFF; - for (int i = 0; i < validBiomes.length; i++) { - BiomeColor biome = validBiomes[i]; + for (BiomeColor biome : validBiomes) { long distance = colorDistance(red, green, blue, biome.grassCombined); if (distance < min) { min = distance; @@ -560,22 +576,20 @@ public class TextureUtil implements TextureHolder{ Gson gson = new Gson(); if (folder.exists()) { // Get all the jar files - File[] files = folder.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".jar"); - } - }); + File[] files = folder.listFiles((dir, name) -> name.endsWith(".jar")); for (BlockType blockType : BlockTypes.values) { BlockMaterial material = blockType.getMaterial(); - if (!material.isSolid() || !material.isFullCube()) continue; + if (!material.isSolid() || !material.isFullCube()) { + continue; + } int color = material.getMapColor(); if (color != 0) { - colorMap.put((int) blockType.getInternalId(), (Integer) color); + colorMap.put(blockType.getInternalId(), (Integer) color); } } if (files.length == 0) { - Fawe.debug("Please create a `FastAsyncWorldEdit/textures` folder with `.minecraft/versions/1.13.jar` jar or mods in it. If the file exists, please make sure the server has read access to the directory"); + Fawe.debug( + "Please create a `FastAsyncWorldEdit/textures` folder with `.minecraft/versions/1.13.jar` jar or mods in it. If the file exists, please make sure the server has read access to the directory"); } else { for (File file : files) { ZipFile zipFile = new ZipFile(file); @@ -583,7 +597,7 @@ public class TextureUtil implements TextureHolder{ // Get all the groups in the current jar // The vanilla textures are in `assets/minecraft` // A jar may contain textures for multiple mods - Set mods = new HashSet(); + Set mods = new HashSet<>(); { Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { @@ -591,7 +605,8 @@ public class TextureUtil implements TextureHolder{ String name = entry.getName(); Path path = Paths.get(name); if (path.startsWith("assets" + File.separator)) { - String[] split = path.toString().split(Pattern.quote(File.separator)); + String[] split = + path.toString().split(Pattern.quote(File.separator)); if (split.length > 1) { String modId = split[1]; mods.add(modId); @@ -607,7 +622,9 @@ public class TextureUtil implements TextureHolder{ }.getType(); for (BlockType blockType : BlockTypes.values) { - if (!blockType.getMaterial().isFullCube()) continue; + if (!blockType.getMaterial().isFullCube()) { + continue; + } int combined = blockType.getInternalId(); String id = blockType.getId(); String[] split = id.split(":", 2); @@ -625,25 +642,34 @@ public class TextureUtil implements TextureHolder{ String textureFileName; try (InputStream is = zipFile.getInputStream(entry)) { - JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8")); + JsonReader reader = new JsonReader( + new InputStreamReader(is, StandardCharsets.UTF_8)); Map root = gson.fromJson(reader, typeToken); Map textures = (Map) root.get("textures"); - if (textures == null) continue; + if (textures == null) { + continue; + } Set models = new HashSet<>(); // Get models - for (Map.Entry stringObjectEntry : textures.entrySet()) { + for (Map.Entry stringObjectEntry : textures + .entrySet()) { Object value = stringObjectEntry.getValue(); if (value instanceof String) { models.add((String) value); } else if (value instanceof Map) { value = ((Map) value).get("model"); - if (value != null) models.add((String) value); + if (value != null) { + models.add((String) value); + } } } - if (models.size() != 1) continue; + if (models.size() != 1) { + continue; + } - textureFileName = String.format(texturesDir, nameSpace, models.iterator().next()); + textureFileName = + String.format(texturesDir, nameSpace, models.iterator().next()); } BufferedImage image = readImage(zipFile, textureFileName); @@ -653,14 +679,15 @@ public class TextureUtil implements TextureHolder{ } int color = ImageUtil.getColor(image); long distance = getDistance(image, color); - distanceMap.put((int) combined, (Long) distance); - colorMap.put((int) combined, (Integer) color); + distanceMap.put(combined, (Long) distance); + colorMap.put(combined, (Integer) color); } } { Integer grass = null; { - String grassFileName = String.format(texturesDir, "minecraft", "grass_block_top"); + String grassFileName = + String.format(texturesDir, "minecraft", "grass_block_top"); BufferedImage image = readImage(zipFile, grassFileName); if (image != null) { grass = ImageUtil.getColor(image); @@ -668,15 +695,17 @@ public class TextureUtil implements TextureHolder{ } if (grass != null) { // assets\minecraft\textures\colormap - ZipEntry grassEntry = getEntry(zipFile, "assets/minecraft/textures/colormap/grass_block.png"); + ZipEntry grassEntry = getEntry(zipFile, + "assets/minecraft/textures/colormap/grass_block.png"); if (grassEntry != null) { try (InputStream is = zipFile.getInputStream(grassEntry)) { BufferedImage image = ImageIO.read(is); // Update biome colors - for (int i = 0; i < biomes.length; i++) { - BiomeColor biome = biomes[i]; - float adjTemp = MathMan.clamp(biome.temperature, 0.0f, 1.0f); - float adjRainfall = MathMan.clamp(biome.rainfall, 0.0f, 1.0f) * adjTemp; + for (BiomeColor biome : biomes) { + float adjTemp = + MathMan.clamp(biome.temperature, 0.0f, 1.0f); + float adjRainfall = + MathMan.clamp(biome.rainfall, 0.0f, 1.0f) * adjTemp; int x = (int) (255 - adjTemp * 255); int z = (int) (255 - adjRainfall * 255); biome.grass = image.getRGB(x, z); @@ -686,8 +715,10 @@ public class TextureUtil implements TextureHolder{ biomes[6].grass = 0; biomes[134].grass = 0; // roofed forest: averaged w/ 0x28340A - biomes[29].grass = multiplyColor(biomes[29].grass, 0x28340A + (255 << 24)); - biomes[157].grass = multiplyColor(biomes[157].grass, 0x28340A + (255 << 24)); + biomes[29].grass = + multiplyColor(biomes[29].grass, 0x28340A + (255 << 24)); + biomes[157].grass = + multiplyColor(biomes[157].grass, 0x28340A + (255 << 24)); // mesa : 0x90814D biomes[37].grass = 0x90814D + (255 << 24); biomes[38].grass = 0x90814D + (255 << 24); @@ -696,10 +727,10 @@ public class TextureUtil implements TextureHolder{ biomes[166].grass = 0x90814D + (255 << 24); biomes[167].grass = 0x90814D + (255 << 24); List valid = new ArrayList<>(); - for (int i = 0; i < biomes.length; i++) { - BiomeColor biome = biomes[i]; -// biome.grass = multiplyColor(biome.grass, grass); - if (biome.grass != 0 && !biome.name.equalsIgnoreCase("Unknown Biome")) { + for (BiomeColor biome : biomes) { + // biome.grass = multiplyColor(biome.grass, grass); + if (biome.grass != 0 && !biome.name + .equalsIgnoreCase("Unknown Biome")) { valid.add(biome); } biome.grassCombined = multiplyColor(grass, biome.grass); @@ -726,26 +757,30 @@ public class TextureUtil implements TextureHolder{ BiomeColor c1 = uniqueColors.get(i); BiomeColor c2 = uniqueColors.get(j); BiomeColor c3 = uniqueColors.get(k); - int average = averageColor(c1.grass, c2.grass, c3.grass); + int average = + averageColor(c1.grass, c2.grass, c3.grass); if (uniqueBiomesColors.add(average)) { count++; layerColors.add((long) average); - layerIds.add((long) ((c1.id) + (c2.id << 8) + (c3.id << 16))); + layerIds.add( + (long) ((c1.id) + (c2.id << 8) + (c3.id + << 16))); } } } } validMixBiomeColors = new int[layerColors.size()]; - for (int i = 0; i < layerColors.size(); i++) + for (int i = 0; i < layerColors.size(); i++) { validMixBiomeColors[i] = (int) layerColors.getLong(i); + } validMixBiomeIds = layerIds.toLongArray(); } } } } -// Close the file + // Close the file zipFile.close(); } } @@ -854,7 +889,7 @@ public class TextureUtil implements TextureHolder{ if (!hasAlpha(colorOther)) { int combinedOther = validBlockIds[j]; int combinedColor = combineTransparency(color, colorOther); - colorLayerMap.put(combinedColor, new int[]{combined, combinedOther}); + colorLayerMap.put(combinedColor, new int[] {combined, combinedOther}); } } } @@ -902,12 +937,14 @@ public class TextureUtil implements TextureHolder{ } } } - if (min == Long.MAX_VALUE) return null; + if (min == Long.MAX_VALUE) { + return null; + } return BlockTypes.get(closest); } private String getFileName(String path) { - String[] split = path.toString().split("[/|\\\\]"); + String[] split = path.split("[/|\\\\]"); String name = split[split.length - 1]; int dot = name.indexOf('.'); if (dot != -1) { @@ -936,10 +973,12 @@ public class TextureUtil implements TextureHolder{ int g = green1 - green2; int b = blue1 - blue2; int hd = hueDistance(red1, green1, blue1, red2, green2, blue2); - return (((512 + rmean) * r * r) >> 8) + 4 * g * g + (((767 - rmean) * b * b) >> 8) + (hd * hd); + return (((512 + rmean) * r * r) >> 8) + 4 * g * g + (((767 - rmean) * b * b) >> 8) + (hd + * hd); } - protected static int hueDistance(int red1, int green1, int blue1, int red2, int green2, int blue2) { + protected static int hueDistance(int red1, int green1, int blue1, int red2, int green2, + int blue2) { int total1 = (red1 + green1 + blue1); int total2 = (red2 + green2 + blue2); if (total1 == 0 || total2 == 0) { @@ -980,7 +1019,8 @@ public class TextureUtil implements TextureHolder{ public int grassCombined; public int foliage; - public BiomeColor(int id, String name, float temperature, float rainfall, int grass, int foliage) { + public BiomeColor(int id, String name, float temperature, float rainfall, int grass, + int foliage) { this.id = id; this.name = name; this.temperature = temperature; 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 bbe9a1dbc..b7ecabf2b 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 @@ -9,10 +9,10 @@ import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.object.extent.NullExtent; import com.boydti.fawe.regions.FaweMask; import com.boydti.fawe.regions.FaweMaskManager; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import java.lang.reflect.Field; import java.util.*; @@ -124,7 +124,7 @@ public class WEManager { } } } - if (!removed) return regions.toArray(new Region[regions.size()]); + if (!removed) return regions.toArray(new Region[0]); masks.clear(); } } @@ -146,7 +146,7 @@ public class WEManager { } if (!tmpMasks.isEmpty()) { masks = tmpMasks; - regions = masks.stream().map(mask -> mask.getRegion()).collect(Collectors.toSet()); + regions = masks.stream().map(FaweMask::getRegion).collect(Collectors.toSet()); } else { regions.addAll(backupRegions); } @@ -155,15 +155,15 @@ public class WEManager { } else { player.deleteMeta("lastMask"); } - return regions.toArray(new Region[regions.size()]); + return regions.toArray(new Region[0]); } public boolean intersects(final Region region1, final Region region2) { - Vector rg1P1 = region1.getMinimumPoint(); - Vector rg1P2 = region1.getMaximumPoint(); - Vector rg2P1 = region2.getMinimumPoint(); - Vector rg2P2 = region2.getMaximumPoint(); + BlockVector3 rg1P1 = region1.getMinimumPoint(); + BlockVector3 rg1P2 = region1.getMaximumPoint(); + 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()); } @@ -179,36 +179,22 @@ public class WEManager { public boolean delay(final FawePlayer player, final String command) { final long start = System.currentTimeMillis(); - return this.delay(player, new Runnable() { - @Override - public void run() { - try { - if ((System.currentTimeMillis() - start) > 1000) { - BBC.WORLDEDIT_RUN.send(FawePlayer.wrap(player)); - } - TaskManager.IMP.task(new Runnable() { - @Override - public void run() { - final long start = System.currentTimeMillis(); - player.executeCommand(command.substring(1)); - TaskManager.IMP.later(new Runnable() { - @Override - public void run() { - SetQueue.IMP.addEmptyTask(new Runnable() { - @Override - public void run() { - if ((System.currentTimeMillis() - start) > 1000) { - BBC.WORLDEDIT_COMPLETE.send(FawePlayer.wrap(player)); - } - } - }); - } - }, 2); - } - }); - } catch (final Exception e) { - MainUtil.handleError(e); + return this.delay(player, () -> { + try { + if ((System.currentTimeMillis() - start) > 1000) { + BBC.WORLDEDIT_RUN.send(FawePlayer.wrap(player)); } + TaskManager.IMP.task(() -> { + final long start1 = System.currentTimeMillis(); + player.executeCommand(command.substring(1)); + TaskManager.IMP.later(() -> SetQueue.IMP.addEmptyTask(() -> { + if ((System.currentTimeMillis() - start1) > 1000) { + BBC.WORLDEDIT_COMPLETE.send(FawePlayer.wrap(player)); + } + }), 2); + }); + } catch (final Exception e) { + MainUtil.handleError(e); } }, false, false); } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/chat/Message.java b/worldedit-core/src/main/java/com/boydti/fawe/util/chat/Message.java index b96444ac6..46a74b7f1 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/chat/Message.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/chat/Message.java @@ -55,7 +55,7 @@ public class Message { return text(caption.format(args)); } - public Message text(Object text) { + public Message text(java.io.Serializable text) { Fawe.get().getChatManager().text(this, BBC.color(Objects.toString(text))); return this; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/chat/UsageMessage.java b/worldedit-core/src/main/java/com/boydti/fawe/util/chat/UsageMessage.java index ea33a753d..313bb6275 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/chat/UsageMessage.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/chat/UsageMessage.java @@ -17,7 +17,6 @@ import com.sk89q.worldedit.util.command.binding.Range; import com.sk89q.worldedit.util.command.parametric.ParameterData; import java.lang.reflect.Type; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import javax.annotation.Nullable; @@ -57,8 +56,8 @@ public class UsageMessage extends Message { text(BBC.HELP_HEADER_SUBCOMMANDS.f()); String prefix = !commandString.isEmpty() ? commandString + " " : ""; - List list = new ArrayList(dispatcher.getCommands()); - Collections.sort(list, new PrimaryAliasComparator(CommandManager.COMMAND_CLEAN_PATTERN)); + List list = new ArrayList<>(dispatcher.getCommands()); + list.sort(new PrimaryAliasComparator(CommandManager.COMMAND_CLEAN_PATTERN)); for (CommandMapping mapping : list) { boolean perm = locals == null || mapping.getCallable().testPermission(locals); @@ -110,7 +109,6 @@ public class UsageMessage extends Message { StringBuilder tooltip = new StringBuilder(); String command = null; - String webpage = null; tooltip.append("Name: " + param.getName()); if (param instanceof ParameterData) { @@ -129,23 +127,21 @@ public class UsageMessage extends Message { if (type instanceof Class) { Link link = (Link) ((Class) type).getAnnotation(Link.class); if (link != null) { - if (link.value().startsWith("http")) webpage = link.value(); - else command = Commands.getAlias(link.clazz(), link.value()); + command = Commands.getAlias(link.clazz(), link.value()); } } } tooltip.append("\nOptional: " + (param.isOptional() || param.isValueFlag())); - if (param.getDefaultValue() != null && param.getDefaultValue().length >= 0) { + if (param.getDefaultValue() != null) { tooltip.append("\nDefault: " + param.getDefaultValue()[0]); } else if (argStr.contains("=")) { tooltip.append("\nDefault: " + argStr.split("[=|\\]|>]")[1]); } - if (command != null || webpage != null) { + if (command != null) { tooltip.append("\nClick for more info"); } tooltip(tooltip.toString()); if (command != null) command(command); - if (webpage != null) link(webpage); } newline(); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/gui/FormBuilder.java b/worldedit-core/src/main/java/com/boydti/fawe/util/gui/FormBuilder.java deleted file mode 100644 index 8897d558c..000000000 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/gui/FormBuilder.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.boydti.fawe.util.gui; - -import com.boydti.fawe.object.FawePlayer; -import java.net.URL; -import java.util.Map; -import java.util.function.Consumer; -import javax.annotation.Nullable; - -public interface FormBuilder { - FormBuilder setTitle(String text); - - FormBuilder setIcon(URL icon); - - FormBuilder addButton(String text, @Nullable URL image); - - FormBuilder addDropdown(String text, int def, String... options); - - FormBuilder addInput(String text, String placeholder, String def); - - FormBuilder addLabel(String text); - - FormBuilder addSlider(String text, double min, double max, int step, double def); - - FormBuilder addStepSlider(String text, int def, String... options); - - FormBuilder addToggle(String text, boolean def); - - FormBuilder setResponder(Consumer> handler); - - void display(FawePlayer fp); -} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/metrics/BStats.java b/worldedit-core/src/main/java/com/boydti/fawe/util/metrics/BStats.java deleted file mode 100644 index 3c90dd46b..000000000 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/metrics/BStats.java +++ /dev/null @@ -1,419 +0,0 @@ -package com.boydti.fawe.util.metrics; - -import com.boydti.fawe.Fawe; -import com.boydti.fawe.FaweVersion; -import com.boydti.fawe.configuration.file.YamlConfiguration; -import com.boydti.fawe.object.RunnableVal; -import com.boydti.fawe.object.io.PGZIPOutputStream; -import com.boydti.fawe.util.TaskManager; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonSyntaxException; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.file.Path; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.concurrent.ConcurrentLinkedQueue; -import javax.net.ssl.HttpsURLConnection; - -/** - * bStats collects some data for plugin authors. - * - * Check out https://bStats.org/ to learn more about bStats! - */ -public class BStats implements Closeable { - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private final String url; - - // The plugin - private final String plugin; - private final String platform; - private final boolean online; - private final String serverVersion; - private final String pluginVersion; - private Timer timer; - private Gson gson = new Gson(); - - // Is bStats enabled on this server? - private volatile boolean enabled; - - // The uuid of the server - private UUID serverUUID; - - // Should failed requests be logged? - private boolean logFailedRequests = false; - - // A list with all known metrics class objects including this one - private static Class usedMetricsClass; - private static final ConcurrentLinkedQueue knownMetricsInstances = new ConcurrentLinkedQueue<>(); - - public BStats() { - this("FastAsyncWorldEdit", Fawe.get().getVersion(), Fawe.imp().getPlatformVersion(), Fawe.imp().getPlatform(), Fawe.imp().isOnlineMode()); - } - - public int getPlayerCount() { - return Fawe.imp() == null ? 1 : Fawe.imp().getPlayerCount(); - } - - private BStats(String plugin, FaweVersion faweVersion, String serverVersion, String platform, boolean online) { - this.url = "https://bStats.org/submitData/" + platform; - this.plugin = plugin; - this.pluginVersion = "" + faweVersion; - this.serverVersion = serverVersion; - this.platform = platform; - this.online = online; - - File configFile = new File(getJarFile().getParentFile(), "bStats" + File.separator + "config.yml"); - if (!configFile.exists()) { - configFile.getParentFile().mkdirs(); - try { - configFile.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - if (config.isSet("serverUuid")) { - try { - serverUUID = UUID.fromString(config.getString("serverUuid")); - } catch (IllegalArgumentException ignore) {} - } - // Check if the config file exists - if (serverUUID == null) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", (serverUUID = UUID.randomUUID()).toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { } - } - - - if (usedMetricsClass != null) { - // Already an instance of this class - linkMetrics(this); - return; - } - this.usedMetricsClass = getFirstBStatsClass(); - if (usedMetricsClass == null) { - // Failed to get first metrics class - return; - } - if (usedMetricsClass == getClass()) { - // We are the first! :) - linkMetrics(this); - enabled = true; - } else { - // We aren't the first so we link to the first metrics class - try { - usedMetricsClass.getMethod("linkMetrics", Object.class).invoke(null,this); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - if (logFailedRequests) { - System.out.println("Failed to link to first metrics class " + usedMetricsClass.getName() + "!"); - } - } - } - } - - public void start() { - if (enabled) { - startSubmitting(); - } - } - - /** - * Links an other metrics class with this class. - * This method is called using Reflection. - * - * @param metrics An object of the metrics class to link. - */ - public static void linkMetrics(Object metrics) { - if (!knownMetricsInstances.contains(metrics)) knownMetricsInstances.add(metrics); - } - - /** - * Gets the plugin specific data. - * This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JsonObject getPluginData() { - JsonObject data = new JsonObject(); - - data.addProperty("pluginName", plugin); - data.addProperty("pluginVersion", pluginVersion); - - JsonArray customCharts = new JsonArray(); - data.add("customCharts", customCharts); - - return data; - } - - private void startSubmitting() { - this.timer = new Timer(true); - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!enabled) { - timer.cancel(); - return; - } - submitData(); - } - // No 2m delay, as this is only started after the server is loaded - }, 0, 1000*60*30); - } - - @Override - protected void finalize() throws Throwable { - close(); - super.finalize(); - } - - @Override - public void close() { - enabled = false; - if (timer != null) { - timer.cancel(); - } - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JsonObject getServerData() { - int playerAmount = getPlayerCount(); - int onlineMode = online ? 1 : 0; - - int managedServers = 1; - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JsonObject data = new JsonObject(); - - data.addProperty("serverUUID", serverUUID.toString()); - - data.addProperty("playerAmount", playerAmount); - data.addProperty("managedServers", managedServers); - data.addProperty("onlineMode", onlineMode); - data.addProperty(platform + "Version", serverVersion); - - data.addProperty("javaVersion", javaVersion); - data.addProperty("osName", osName); - data.addProperty("osArch", osArch); - data.addProperty("osVersion", osVersion); - data.addProperty("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JsonObject data = getServerData(); - - final JsonArray pluginData = new JsonArray(); - // Search for all other bStats Metrics classes to get their plugin data - for (Object metrics : knownMetricsInstances) { - Object plugin = TaskManager.IMP.sync(new RunnableVal() { - @Override - public void run(Object value) { - try { - this.value = metrics.getClass().getMethod("getPluginData").invoke(metrics); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | NullPointerException | JsonSyntaxException ignored) {} - } - }); - if (plugin != null) { - if (plugin instanceof JsonObject) { - pluginData.add((JsonObject) plugin); - } else { - pluginData.add(gson.fromJson(plugin.toString(), JsonObject.class)); - } - } - } - - data.add("plugins", pluginData); - - try { - // Send the data - sendData(data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - System.err.println("Could not submit plugin stats!"); - } - } - } - - /** - * Gets the first bStat Metrics class. - * - * @return The first bStats metrics class. - */ - private Class getFirstBStatsClass() { - Path configPath = getJarFile().toPath().getParent().resolve("bStats"); - configPath.toFile().mkdirs(); - File tempFile = new File(configPath.toFile(), "temp.txt"); - - try { - String className = readFile(tempFile); - if (className != null) { - try { - // Let's check if a class with the given name exists. - return Class.forName(className); - } catch (ClassNotFoundException ignored) { } - } - writeFile(tempFile, getClass().getName()); - return getClass(); - } catch (IOException e) { - if (logFailedRequests) { - System.err.println("Failed to get first bStats class!"); - } - return null; - } - } - - private File getJarFile() { - try { - URL url = BStats.class.getProtectionDomain().getCodeSource().getLocation(); - return new File(new URL(url.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")).toURI().getPath()); - } catch (MalformedURLException | URISyntaxException | SecurityException e) { - return new File(".", "plugins"); - } - } - - /** - * Reads the first line of the file. - * - * @param file The file to read. Cannot be null. - * @return The first line of the file or null if the file does not exist or is empty. - * @throws IOException If something did not work :( - */ - private String readFile(File file) throws IOException { - if (!file.exists()) { - return null; - } - try ( - FileReader fileReader = new FileReader(file); - BufferedReader bufferedReader = new BufferedReader(fileReader); - ) { - return bufferedReader.readLine(); - } - } - - /** - * Writes a String to a file. It also adds a note for the user, - * - * @param file The file to write to. Cannot be null. - * @param lines The lines to write. - * @throws IOException If something did not work :( - */ - private void writeFile(File file, String... lines) throws IOException { - if (!file.exists()) { - file.createNewFile(); - } - try ( - FileWriter fileWriter = new FileWriter(file); - BufferedWriter bufferedWriter = new BufferedWriter(fileWriter) - ) { - for (String line : lines) { - bufferedWriter.write(line); - bufferedWriter.newLine(); - } - } - } - - /** - * Sends the data to the bStats server. - * - * @param data The data to send. - * @throws Exception If the request failed. - */ - private void sendData(JsonObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null"); - } - - HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); - outputStream.write(compressedData); - outputStream.flush(); - outputStream.close(); - - connection.getInputStream().close(); // We don't care about the response - Just send our data :) - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - PGZIPOutputStream gzip = new PGZIPOutputStream(outputStream); - gzip.write(str.getBytes("UTF-8")); - gzip.close(); - return outputStream.toByteArray(); - } - -} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/task/TaskBuilder.java b/worldedit-core/src/main/java/com/boydti/fawe/util/task/TaskBuilder.java index 402b79f21..74b7959cf 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/task/TaskBuilder.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/task/TaskBuilder.java @@ -167,45 +167,33 @@ public class TaskBuilder extends Metadatable { } public TaskBuilder abortIfTrue(final Runnable run) { - tasks.add(RunnableTask.adapt(new Task() { - @Override - public Boolean run(Boolean previous) { - if (previous == Boolean.TRUE) run.run(); - return previous == Boolean.TRUE; - } + tasks.add(RunnableTask.adapt((Task) previous -> { + if (previous == Boolean.TRUE) run.run(); + return previous == Boolean.TRUE; }, TaskType.ABORT)); return this; } public TaskBuilder abortIfNull(final Runnable run) { - tasks.add(RunnableTask.adapt(new Task() { - @Override - public Boolean run(Object previous) { - if (previous == null) run.run(); - return previous == null; - } + tasks.add(RunnableTask.adapt((Task) previous -> { + if (previous == null) run.run(); + return previous == null; }, TaskType.ABORT)); return this; } public TaskBuilder abortIfEqual(final Runnable run, final Object other) { - tasks.add(RunnableTask.adapt(new Task() { - @Override - public Boolean run(Object previous) { - if (Objects.equals(previous, other)) run.run(); - return Objects.equals(previous, other); - } + tasks.add(RunnableTask.adapt((Task) previous -> { + if (Objects.equals(previous, other)) run.run(); + return Objects.equals(previous, other); }, TaskType.ABORT)); return this; } public TaskBuilder abortIfNotEqual(final Runnable run, final Object other) { - tasks.add(RunnableTask.adapt(new Task() { - @Override - public Boolean run(Object previous) { - if (!Objects.equals(previous, other)) run.run(); - return !Objects.equals(previous, other); - } + tasks.add(RunnableTask.adapt((Task) previous -> { + if (!Objects.equals(previous, other)) run.run(); + return !Objects.equals(previous, other); }, TaskType.ABORT)); return this; } @@ -215,12 +203,7 @@ public class TaskBuilder extends Metadatable { * - As opposed to trying to using the current thread */ public void buildAsync() { - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - build(); - } - }); + TaskManager.IMP.async(this::build); } /** @@ -240,20 +223,10 @@ public class TaskBuilder extends Metadatable { case SYNC: case ABORT: case SYNC_PARALLEL: - TaskManager.IMP.later(new Runnable() { - @Override - public void run() { - build(); - } - }, task.getDelay(result)); + TaskManager.IMP.later(this::build, task.getDelay(result)); return; default: - TaskManager.IMP.laterAsync(new Runnable() { - @Override - public void run() { - build(); - } - }, task.getDelay(result)); + TaskManager.IMP.laterAsync(this::build, task.getDelay(result)); return; } } @@ -274,12 +247,7 @@ public class TaskBuilder extends Metadatable { case ASYNC: case ASYNC_PARALLEL: if (Fawe.isMainThread()) { - TaskManager.IMP.async(new Runnable() { - @Override - public void run() { - build(); - } - }); + TaskManager.IMP.async(this::build); return; } break; @@ -308,7 +276,7 @@ public class TaskBuilder extends Metadatable { continue; case SYNC_PARALLEL: case ASYNC_PARALLEL: - final ArrayList parallel = new ArrayList(); + final ArrayList parallel = new ArrayList<>(); parallel.add(task); RunnableTask next = tasks.peek(); while (next != null && next.type == task.type) { @@ -484,24 +452,21 @@ public class TaskBuilder extends Metadatable { public Object execSplit(final Object previous) { this.value = previous; - final Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - synchronized (asyncWaitLock) { - asyncWaitLock.notifyAll(); - asyncWaitLock.wait(Long.MAX_VALUE); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - exec(previous); - finished = true; - waitingAsync = true; - waitingSync = false; - synchronized (syncWaitLock) { - syncWaitLock.notifyAll(); + final Thread thread = new Thread(() -> { + try { + synchronized (asyncWaitLock) { + asyncWaitLock.notifyAll(); + asyncWaitLock.wait(Long.MAX_VALUE); } + } catch (InterruptedException e) { + e.printStackTrace(); + } + exec(previous); + finished = true; + waitingAsync = true; + waitingSync = false; + synchronized (syncWaitLock) { + syncWaitLock.notifyAll(); } }); try { @@ -571,4 +536,4 @@ public class TaskBuilder extends Metadatable { DELAY, ABORT } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/wrappers/FakePlayer.java b/worldedit-core/src/main/java/com/boydti/fawe/wrappers/FakePlayer.java index d952f8521..44ba6cc34 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/wrappers/FakePlayer.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/wrappers/FakePlayer.java @@ -4,9 +4,8 @@ import com.boydti.fawe.Fawe; import com.boydti.fawe.object.FaweLocation; import com.boydti.fawe.object.FawePlayer; import com.google.common.base.Charsets; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.entity.BaseEntity; @@ -15,6 +14,8 @@ import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.extension.platform.*; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.inventory.BlockBag; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.session.SessionKey; import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.util.Location; @@ -166,11 +167,12 @@ public class FakePlayer extends AbstractPlayerActor { } @Override - public void setPosition(Vector pos, float pitch, float yaw) { - if (pos instanceof Location) { - Extent extent = ((Location) pos).getExtent(); - if (extent instanceof World) this.world = (World) extent; - } + public void setPosition(Vector3 pos, float pitch, float yaw) { + //TODO: find replacement for following code +// if (pos instanceof Location) { +// Extent extent = ((Location) pos).getExtent(); +// if (extent instanceof World) this.world = (World) extent; +// } this.pos = new Location(world, pos, yaw, pitch); } @@ -302,4 +304,10 @@ public class FakePlayer extends AbstractPlayerActor { return true; } } + + @Override + public boolean setLocation(Location location) { + this.pos = location; + return true; + } } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/wrappers/LocationMaskedPlayerWrapper.java b/worldedit-core/src/main/java/com/boydti/fawe/wrappers/LocationMaskedPlayerWrapper.java index 412fd3daa..9bb2e0781 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/wrappers/LocationMaskedPlayerWrapper.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/wrappers/LocationMaskedPlayerWrapper.java @@ -1,7 +1,7 @@ package com.boydti.fawe.wrappers; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.Location; public class LocationMaskedPlayerWrapper extends PlayerWrapper { @@ -32,7 +32,7 @@ public class LocationMaskedPlayerWrapper extends PlayerWrapper { } @Override - public void setPosition(Vector pos, float pitch, float yaw) { + public void setPosition(Vector3 pos, float pitch, float yaw) { this.position = new Location(position.getExtent(), pos, pitch, yaw); if (allowTeleport) { super.setPosition(pos, pitch, yaw); diff --git a/worldedit-core/src/main/java/com/boydti/fawe/wrappers/PlayerWrapper.java b/worldedit-core/src/main/java/com/boydti/fawe/wrappers/PlayerWrapper.java index a5ec89f5f..6e6711650 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/wrappers/PlayerWrapper.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/wrappers/PlayerWrapper.java @@ -6,17 +6,19 @@ import com.boydti.fawe.object.RunnableVal; import com.boydti.fawe.util.EditSessionBuilder; import com.boydti.fawe.util.TaskManager; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.BaseItemStack; -import com.sk89q.worldedit.blocks.BlockType; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.AbstractPlayerActor; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.internal.cui.CUIEvent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.session.SessionKey; +import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.TargetBlock; @@ -50,7 +52,7 @@ public class PlayerWrapper extends AbstractPlayerActor { } @Override - public BlockState getBlockInHand(HandSide handSide) throws WorldEditException { + public BaseBlock getBlockInHand(HandSide handSide) throws WorldEditException { return parent.getBlockInHand(handSide); } @@ -90,7 +92,7 @@ public class PlayerWrapper extends AbstractPlayerActor { } @Override - public void setPosition(Vector pos, float pitch, float yaw) { + public void setPosition(Vector3 pos, float pitch, float yaw) { parent.setPosition(pos, pitch, yaw); } @@ -233,13 +235,13 @@ public class PlayerWrapper extends AbstractPlayerActor { Extent world = getLocation().getExtent(); // No free space above - if (!world.getBlock(new Vector(x, y, z)).getBlockType().getMaterial().isAir()) { + if (!world.getBlock(BlockVector3.at(x, y, z)).getBlockType().getMaterial().isAir()) { return false; } while (y <= world.getMaximumPoint().getY()) { // Found a ceiling! - if (world.getBlock(new Vector(x, y, z)).getBlockType().getMaterial().isMovementBlocker()) { + if (world.getBlock(BlockVector3.at(x, y, z)).getBlockType().getMaterial().isMovementBlocker()) { int platformY = Math.max(initialY, y - 3 - clearance); floatAt(x, platformY + 1, z, alwaysGlass); return true; @@ -267,7 +269,7 @@ public class PlayerWrapper extends AbstractPlayerActor { final Extent world = getLocation().getExtent(); while (y <= world.getMaximumPoint().getY() + 2) { - if (world.getBlock(new Vector(x, y, z)).getBlockType().getMaterial().isMovementBlocker()) { + if (world.getBlock(BlockVector3.at(x, y, z)).getBlockType().getMaterial().isMovementBlocker()) { break; // Hit something } else if (y > maxY + 1) { break; @@ -287,7 +289,7 @@ public class PlayerWrapper extends AbstractPlayerActor { RuntimeException caught = null; try { EditSession edit = new EditSessionBuilder(parent.getWorld()).player(FawePlayer.wrap(this)).build(); - edit.setBlock(new Vector(x, y - 1, z), BlockTypes.GLASS); + edit.setBlock(BlockVector3.at(x, y - 1, z), BlockTypes.GLASS); edit.flushQueue(); LocalSession session = Fawe.get().getWorldEdit().getSessionManager().get(this); if (session != null) { @@ -299,7 +301,7 @@ public class PlayerWrapper extends AbstractPlayerActor { TaskManager.IMP.sync(new RunnableVal() { @Override public void run(Object value) { - setPosition(new Vector(x + 0.5, y, z + 0.5)); + setPosition(Vector3.at(x + 0.5, y, z + 0.5)); } }); if (caught != null) { @@ -341,7 +343,7 @@ public class PlayerWrapper extends AbstractPlayerActor { } @Override - public PlayerDirection getCardinalDirection() { + public Direction getCardinalDirection() { return parent.getCardinalDirection(); } @@ -359,7 +361,7 @@ public class PlayerWrapper extends AbstractPlayerActor { boolean inFree = false; while ((block = hitBlox.getNextBlock()) != null) { - boolean free = !world.getBlock(block.toVector()).getBlockType().getMaterial().isMovementBlocker(); + boolean free = !world.getBlock(BlockVector3.at(block.getBlockX(), block.getBlockY(), block.getBlockZ())).getBlockType().getMaterial().isMovementBlocker(); if (firstBlock) { firstBlock = false; @@ -418,4 +420,9 @@ public class PlayerWrapper extends AbstractPlayerActor { public File openFileSaveDialog(String[] extensions) { return parent.openFileSaveDialog(extensions); } + + @Override + public boolean setLocation(Location location) { + return parent.setLocation(location); + } } 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 e22970871..d9b134a9d 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 @@ -10,6 +10,9 @@ import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.Location; @@ -17,6 +20,7 @@ import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.world.AbstractWorld; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; @@ -59,12 +63,12 @@ public class WorldWrapper extends AbstractWorld { } @Override - public boolean useItem(Vector position, BaseItem item, Direction face) { + public boolean useItem(BlockVector3 position, BaseItem item, Direction face) { return parent.useItem(position, item, face); } @Override - public boolean setBlock(Vector position, BlockStateHolder block, boolean notifyAndLight) throws WorldEditException { + public boolean setBlock(BlockVector3 position, BlockStateHolder block, boolean notifyAndLight) throws WorldEditException { return parent.setBlock(position, block, notifyAndLight); } @@ -79,12 +83,12 @@ public class WorldWrapper extends AbstractWorld { } @Override - public void dropItem(Vector pt, BaseItemStack item, int times) { + public void dropItem(Vector3 pt, BaseItemStack item, int times) { parent.dropItem(pt, item, times); } @Override - public void simulateBlockMine(final Vector pt) { + public void simulateBlockMine(final BlockVector3 pt) { TaskManager.IMP.sync(new RunnableVal() { @Override public void run(Object value) { @@ -94,7 +98,7 @@ public class WorldWrapper extends AbstractWorld { } @Override - public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, Vector position) throws MaxChangedBlocksException { + public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) throws MaxChangedBlocksException { return TaskManager.IMP.sync((Supplier) () -> { try { return parent.generateTree(type, editSession, position); @@ -105,27 +109,27 @@ public class WorldWrapper extends AbstractWorld { } @Override - public void checkLoadedChunk(Vector pt) { + public void checkLoadedChunk(BlockVector3 pt) { parent.checkLoadedChunk(pt); } @Override - public void fixAfterFastMode(Iterable chunks) { + public void fixAfterFastMode(Iterable chunks) { parent.fixAfterFastMode(chunks); } @Override - public void fixLighting(Iterable chunks) { + public void fixLighting(Iterable chunks) { parent.fixLighting(chunks); } @Override - public boolean playEffect(Vector position, int type, int data) { + public boolean playEffect(Vector3 position, int type, int data) { return parent.playEffect(position, type, data); } @Override - public boolean queueBlockBreakEffect(Platform server, Vector position, BlockType blockType, double priority) { + public boolean queueBlockBreakEffect(Platform server, BlockVector3 position, BlockType blockType, double priority) { return parent.queueBlockBreakEffect(server, position, blockType, priority); } @@ -150,12 +154,12 @@ public class WorldWrapper extends AbstractWorld { } @Override - public Vector getMinimumPoint() { + public BlockVector3 getMinimumPoint() { return parent.getMinimumPoint(); } @Override - public Vector getMaximumPoint() { + public BlockVector3 getMaximumPoint() { return parent.getMaximumPoint(); } @@ -171,17 +175,17 @@ public class WorldWrapper extends AbstractWorld { } @Override - public int getBlockLightLevel(Vector position) { + public int getBlockLightLevel(BlockVector3 position) { return parent.getBlockLightLevel(position); } @Override - public boolean clearContainerBlockContents(Vector position) { + public boolean clearContainerBlockContents(BlockVector3 position) { return parent.clearContainerBlockContents(position); } @Override - public void dropItem(Vector position, BaseItemStack item) { + public void dropItem(Vector3 position, BaseItemStack item) { parent.dropItem(position, item); } @@ -227,27 +231,37 @@ public class WorldWrapper extends AbstractWorld { } @Override - public BlockState getBlock(Vector position) { + public BlockState getBlock(BlockVector3 position) { return parent.getBlock(position); } @Override - public BlockState getLazyBlock(Vector position) { + public BlockState getLazyBlock(BlockVector3 position) { return parent.getLazyBlock(position); } @Override - public BlockState getFullBlock(Vector position) { + public BaseBlock getFullBlock(BlockVector3 position) { return parent.getFullBlock(position); } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return parent.getBiome(position); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return parent.setBiome(position, biome); } + + @Override + public boolean notifyAndLightBlock(BlockVector3 position, BlockState previousType) throws WorldEditException { + return parent.notifyAndLightBlock(position, previousType); + } + + @Override + public BlockVector3 getSpawnPosition() { + return parent.getSpawnPosition(); + } } 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 da642d4db..a6b90ecb1 100644 --- a/worldedit-core/src/main/java/com/sk89q/jnbt/CompoundTag.java +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/CompoundTag.java @@ -1,447 +1,447 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.jnbt; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * The {@code TAG_Compound} tag. - */ -public final class CompoundTag extends Tag { - - private final Map value; - - /** - * Creates the tag with an empty name. - * - * @param value the value of the tag - */ - public CompoundTag(Map value) { - super(); - this.value = value; - } - - @Override - public Map getRaw() { - HashMap raw = new HashMap<>(); - for (Map.Entry entry : value.entrySet()) { - raw.put(entry.getKey(), entry.getValue().getRaw()); - } - return raw; - } - - /** - * Returns whether this compound tag contains the given key. - * - * @param key the given key - * @return true if the tag contains the given key - */ - public boolean containsKey(String key) { - return value.containsKey(key); - } - - @Override - public Map getValue() { - return value; - } - - /** - * Return a new compound tag with the given values. - * - * @param value the value - * @return the new compound tag - */ - public CompoundTag setValue(Map value) { - return new CompoundTag(value); - } - - /** - * Create a compound tag builder. - * - * @return the builder - */ - public CompoundTagBuilder createBuilder() { - return new CompoundTagBuilder(new HashMap(value)); - } - - /** - * Get a byte array named with the given key. - * - *

If the key does not exist or its value is not a byte array tag, - * then an empty byte array will be returned.

- * - * @param key the key - * @return a byte array - */ - public byte[] getByteArray(String key) { - Tag tag = value.get(key); - if (tag instanceof ByteArrayTag) { - return ((ByteArrayTag) tag).getValue(); - } else { - return new byte[0]; - } - } - - /** - * Get a byte named with the given key. - * - *

If the key does not exist or its value is not a byte tag, - * then {@code 0} will be returned.

- * - * @param key the key - * @return a byte - */ - public byte getByte(String key) { - Tag tag = value.get(key); - if (tag instanceof ByteTag) { - return ((ByteTag) tag).getValue(); - } else { - return (byte) 0; - } - } - - /** - * Get a double named with the given key. - * - *

If the key does not exist or its value is not a double tag, - * then {@code 0} will be returned.

- * - * @param key the key - * @return a double - */ - public double getDouble(String key) { - Tag tag = value.get(key); - if (tag instanceof DoubleTag) { - return ((DoubleTag) tag).getValue(); - } else { - return 0; - } - } - - /** - * Get a double named with the given key, even if it's another - * type of number. - * - *

If the key does not exist or its value is not a number, - * then {@code 0} will be returned.

- * - * @param key the key - * @return a double - */ - public double asDouble(String key) { - Tag tag = value.get(key); - if (tag instanceof ByteTag) { - return ((ByteTag) tag).getValue(); - - } else if (tag instanceof ShortTag) { - return ((ShortTag) tag).getValue(); - - } else if (tag instanceof IntTag) { - return ((IntTag) tag).getValue(); - - } else if (tag instanceof LongTag) { - return ((LongTag) tag).getValue(); - - } else if (tag instanceof FloatTag) { - return ((FloatTag) tag).getValue(); - - } else if (tag instanceof DoubleTag) { - return ((DoubleTag) tag).getValue(); - - } else { - return 0; - } - } - - /** - * Get a float named with the given key. - * - *

If the key does not exist or its value is not a float tag, - * then {@code 0} will be returned.

- * - * @param key the key - * @return a float - */ - public float getFloat(String key) { - Tag tag = value.get(key); - if (tag instanceof FloatTag) { - return ((FloatTag) tag).getValue(); - } else { - return 0; - } - } - - /** - * Get a {@code int[]} named with the given key. - * - *

If the key does not exist or its value is not an int array tag, - * then an empty array will be returned.

- * - * @param key the key - * @return an int array - */ - public int[] getIntArray(String key) { - Tag tag = value.get(key); - if (tag instanceof IntArrayTag) { - return ((IntArrayTag) tag).getValue(); - } else { - return new int[0]; - } - } - - /** - * Get an int named with the given key. - * - *

If the key does not exist or its value is not an int tag, - * then {@code 0} will be returned.

- * - * @param key the key - * @return an int - */ - public int getInt(String key) { - Tag tag = value.get(key); - if (tag instanceof IntTag) { - return ((IntTag) tag).getValue(); - } else { - return 0; - } - } - - /** - * Get an int named with the given key, even if it's another - * type of number. - * - *

If the key does not exist or its value is not a number, - * then {@code 0} will be returned.

- * - * @param key the key - * @return an int - */ - public int asInt(String key) { - Tag tag = value.get(key); - if (tag instanceof ByteTag) { - return ((ByteTag) tag).getValue(); - - } else if (tag instanceof ShortTag) { - return ((ShortTag) tag).getValue(); - - } else if (tag instanceof IntTag) { - return ((IntTag) tag).getValue(); - - } else if (tag instanceof LongTag) { - return ((LongTag) tag).getValue().intValue(); - - } else if (tag instanceof FloatTag) { - return ((FloatTag) tag).getValue().intValue(); - - } else if (tag instanceof DoubleTag) { - return ((DoubleTag) tag).getValue().intValue(); - - } else { - return 0; - } - } - - /** - * Get a list of tags named with the given key. - * - *

If the key does not exist or its value is not a list tag, - * then an empty list will be returned.

- * - * @param key the key - * @return a list of tags - */ - public List getList(String key) { - Tag tag = value.get(key); - if (tag instanceof ListTag) { - return ((ListTag) tag).getValue(); - } else { - return Collections.emptyList(); - } - } - - /** - * Get a {@code TagList} named with the given key. - * - *

If the key does not exist or its value is not a list tag, - * then an empty tag list will be returned.

- * - * @param key the key - * @return a tag list instance - */ - public ListTag getListTag(String key) { - Tag tag = value.get(key); - if (tag instanceof ListTag) { - return (ListTag) tag; - } else { - return new ListTag(StringTag.class, Collections.emptyList()); - } - } - - /** - * Get a list of tags named with the given key. - * - *

If the key does not exist or its value is not a list tag, - * then an empty list will be returned. If the given key references - * a list but the list of of a different type, then an empty - * list will also be returned.

- * - * @param key the key - * @param listType the class of the contained type - * @return a list of tags - * @param the type of list - */ - @SuppressWarnings("unchecked") - public List getList(String key, Class listType) { - Tag tag = value.get(key); - if (tag instanceof ListTag) { - ListTag listTag = (ListTag) tag; - if (listTag.getType().equals(listType)) { - return (List) listTag.getValue(); - } else { - return Collections.emptyList(); - } - } else { - return Collections.emptyList(); - } - } - - /** - * Get a {@code long[]} named with the given key. - * - *

If the key does not exist or its value is not an long array tag, - * then an empty array will be returned.

- * - * @param key the key - * @return an int array - */ - public long[] getLongArray(String key) { - Tag tag = value.get(key); - if (tag instanceof LongArrayTag) { - return ((LongArrayTag) tag).getValue(); - } else { - return new long[0]; - } - } - - /** - * Get a long named with the given key. - * - *

If the key does not exist or its value is not a long tag, - * then {@code 0} will be returned.

- * - * @param key the key - * @return a long - */ - public long getLong(String key) { - Tag tag = value.get(key); - if (tag instanceof LongTag) { - return ((LongTag) tag).getValue(); - } else { - return 0L; - } - } - - /** - * Get a long named with the given key, even if it's another - * type of number. - * - *

If the key does not exist or its value is not a number, - * then {@code 0} will be returned.

- * - * @param key the key - * @return a long - */ - public long asLong(String key) { - Tag tag = value.get(key); - if (tag instanceof ByteTag) { - return ((ByteTag) tag).getValue(); - - } else if (tag instanceof ShortTag) { - return ((ShortTag) tag).getValue(); - - } else if (tag instanceof IntTag) { - return ((IntTag) tag).getValue(); - - } else if (tag instanceof LongTag) { - return ((LongTag) tag).getValue(); - - } else if (tag instanceof FloatTag) { - return ((FloatTag) tag).getValue().longValue(); - - } else if (tag instanceof DoubleTag) { - return ((DoubleTag) tag).getValue().longValue(); - - } else { - return 0L; - } - } - - /** - * Get a short named with the given key. - * - *

If the key does not exist or its value is not a short tag, - * then {@code 0} will be returned.

- * - * @param key the key - * @return a short - */ - public short getShort(String key) { - Tag tag = value.get(key); - if (tag instanceof ShortTag) { - return ((ShortTag) tag).getValue(); - } else { - return 0; - } - } - - /** - * Get a string named with the given key. - * - *

If the key does not exist or its value is not a string tag, - * then {@code ""} will be returned.

- * - * @param key the key - * @return a string - */ - public String getString(String key) { - Tag tag = value.get(key); - if (tag instanceof StringTag) { - return ((StringTag) tag).getValue(); - } else { - return ""; - } - } - - @Override - public String toString() { - StringBuilder bldr = new StringBuilder(); - bldr.append("TAG_Compound").append(": ").append(value.size()).append(" entries\r\n{\r\n"); - for (Map.Entry entry : value.entrySet()) { - bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); - } - bldr.append("}"); - return bldr.toString(); - } - -} \ No newline at end of file +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.jnbt; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The {@code TAG_Compound} tag. + */ +public class CompoundTag extends Tag { + + private final Map value; + + /** + * Creates the tag with an empty name. + * + * @param value the value of the tag + */ + public CompoundTag(Map value) { + super(); + this.value = value; + } + + @Override + public Map getRaw() { + HashMap raw = new HashMap<>(); + for (Map.Entry entry : value.entrySet()) { + raw.put(entry.getKey(), entry.getValue().getRaw()); + } + return raw; + } + + /** + * Returns whether this compound tag contains the given key. + * + * @param key the given key + * @return true if the tag contains the given key + */ + public boolean containsKey(String key) { + return getValue().containsKey(key); + } + + @Override + public Map getValue() { + return value; + } + + /** + * Return a new compound tag with the given values. + * + * @param value the value + * @return the new compound tag + */ + public CompoundTag setValue(Map value) { + return new CompoundTag(value); + } + + /** + * Create a compound tag builder. + * + * @return the builder + */ + public CompoundTagBuilder createBuilder() { + return new CompoundTagBuilder(new HashMap<>(value)); + } + + /** + * Get a byte array named with the given key. + * + *

If the key does not exist or its value is not a byte array tag, + * then an empty byte array will be returned.

+ * + * @param key the key + * @return a byte array + */ + public byte[] getByteArray(String key) { + Tag tag = getValue().get(key); + if (tag instanceof ByteArrayTag) { + return ((ByteArrayTag) tag).getValue(); + } else { + return new byte[0]; + } + } + + /** + * Get a byte named with the given key. + * + *

If the key does not exist or its value is not a byte tag, + * then {@code 0} will be returned.

+ * + * @param key the key + * @return a byte + */ + public byte getByte(String key) { + Tag tag = getValue().get(key); + if (tag instanceof ByteTag) { + return ((ByteTag) tag).getValue(); + } else { + return (byte) 0; + } + } + + /** + * Get a double named with the given key. + * + *

If the key does not exist or its value is not a double tag, + * then {@code 0} will be returned.

+ * + * @param key the key + * @return a double + */ + public double getDouble(String key) { + Tag tag = getValue().get(key); + if (tag instanceof DoubleTag) { + return ((DoubleTag) tag).getValue(); + } else { + return 0; + } + } + + /** + * Get a double named with the given key, even if it's another + * type of number. + * + *

If the key does not exist or its value is not a number, + * then {@code 0} will be returned.

+ * + * @param key the key + * @return a double + */ + public double asDouble(String key) { + Tag tag = getValue().get(key); + if (tag instanceof ByteTag) { + return ((ByteTag) tag).getValue(); + + } else if (tag instanceof ShortTag) { + return ((ShortTag) tag).getValue(); + + } else if (tag instanceof IntTag) { + return ((IntTag) tag).getValue(); + + } else if (tag instanceof LongTag) { + return ((LongTag) tag).getValue(); + + } else if (tag instanceof FloatTag) { + return ((FloatTag) tag).getValue(); + + } else if (tag instanceof DoubleTag) { + return ((DoubleTag) tag).getValue(); + + } else { + return 0; + } + } + + /** + * Get a float named with the given key. + * + *

If the key does not exist or its value is not a float tag, + * then {@code 0} will be returned.

+ * + * @param key the key + * @return a float + */ + public float getFloat(String key) { + Tag tag = getValue().get(key); + if (tag instanceof FloatTag) { + return ((FloatTag) tag).getValue(); + } else { + return 0; + } + } + + /** + * Get a {@code int[]} named with the given key. + * + *

If the key does not exist or its value is not an int array tag, + * then an empty array will be returned.

+ * + * @param key the key + * @return an int array + */ + public int[] getIntArray(String key) { + Tag tag = getValue().get(key); + if (tag instanceof IntArrayTag) { + return ((IntArrayTag) tag).getValue(); + } else { + return new int[0]; + } + } + + /** + * Get an int named with the given key. + * + *

If the key does not exist or its value is not an int tag, + * then {@code 0} will be returned.

+ * + * @param key the key + * @return an int + */ + public int getInt(String key) { + Tag tag = getValue().get(key); + if (tag instanceof IntTag) { + return ((IntTag) tag).getValue(); + } else { + return 0; + } + } + + /** + * Get an int named with the given key, even if it's another + * type of number. + * + *

If the key does not exist or its value is not a number, + * then {@code 0} will be returned.

+ * + * @param key the key + * @return an int + */ + public int asInt(String key) { + Tag tag = getValue().get(key); + if (tag instanceof ByteTag) { + return ((ByteTag) tag).getValue(); + + } else if (tag instanceof ShortTag) { + return ((ShortTag) tag).getValue(); + + } else if (tag instanceof IntTag) { + return ((IntTag) tag).getValue(); + + } else if (tag instanceof LongTag) { + return ((LongTag) tag).getValue().intValue(); + + } else if (tag instanceof FloatTag) { + return ((FloatTag) tag).getValue().intValue(); + + } else if (tag instanceof DoubleTag) { + return ((DoubleTag) tag).getValue().intValue(); + + } else { + return 0; + } + } + + /** + * Get a list of tags named with the given key. + * + *

If the key does not exist or its value is not a list tag, + * then an empty list will be returned.

+ * + * @param key the key + * @return a list of tags + */ + public List getList(String key) { + Tag tag = getValue().get(key); + if (tag instanceof ListTag) { + return ((ListTag) tag).getValue(); + } else { + return Collections.emptyList(); + } + } + + /** + * Get a {@code TagList} named with the given key. + * + *

If the key does not exist or its value is not a list tag, + * then an empty tag list will be returned.

+ * + * @param key the key + * @return a tag list instance + */ + public ListTag getListTag(String key) { + Tag tag = getValue().get(key); + if (tag instanceof ListTag) { + return (ListTag) tag; + } else { + return new ListTag(StringTag.class, Collections.emptyList()); + } + } + + /** + * Get a list of tags named with the given key. + * + *

If the key does not exist or its value is not a list tag, + * then an empty list will be returned. If the given key references + * a list but the list of of a different type, then an empty + * list will also be returned.

+ * + * @param key the key + * @param listType the class of the contained type + * @return a list of tags + * @param the type of list + */ + @SuppressWarnings("unchecked") + public List getList(String key, Class listType) { + Tag tag = getValue().get(key); + if (tag instanceof ListTag) { + ListTag listTag = (ListTag) tag; + if (listTag.getType().equals(listType)) { + return (List) listTag.getValue(); + } else { + return Collections.emptyList(); + } + } else { + return Collections.emptyList(); + } + } + + /** + * Get a {@code long[]} named with the given key. + * + *

If the key does not exist or its value is not an long array tag, + * then an empty array will be returned.

+ * + * @param key the key + * @return an int array + */ + public long[] getLongArray(String key) { + Tag tag = getValue().get(key); + if (tag instanceof LongArrayTag) { + return ((LongArrayTag) tag).getValue(); + } else { + return new long[0]; + } + } + + /** + * Get a long named with the given key. + * + *

If the key does not exist or its value is not a long tag, + * then {@code 0} will be returned.

+ * + * @param key the key + * @return a long + */ + public long getLong(String key) { + Tag tag = getValue().get(key); + if (tag instanceof LongTag) { + return ((LongTag) tag).getValue(); + } else { + return 0L; + } + } + + /** + * Get a long named with the given key, even if it's another + * type of number. + * + *

If the key does not exist or its value is not a number, + * then {@code 0} will be returned.

+ * + * @param key the key + * @return a long + */ + public long asLong(String key) { + Tag tag = getValue().get(key); + if (tag instanceof ByteTag) { + return ((ByteTag) tag).getValue(); + + } else if (tag instanceof ShortTag) { + return ((ShortTag) tag).getValue(); + + } else if (tag instanceof IntTag) { + return ((IntTag) tag).getValue(); + + } else if (tag instanceof LongTag) { + return ((LongTag) tag).getValue(); + + } else if (tag instanceof FloatTag) { + return ((FloatTag) tag).getValue().longValue(); + + } else if (tag instanceof DoubleTag) { + return ((DoubleTag) tag).getValue().longValue(); + + } else { + return 0L; + } + } + + /** + * Get a short named with the given key. + * + *

If the key does not exist or its value is not a short tag, + * then {@code 0} will be returned.

+ * + * @param key the key + * @return a short + */ + public short getShort(String key) { + Tag tag = getValue().get(key); + if (tag instanceof ShortTag) { + return ((ShortTag) tag).getValue(); + } else { + return 0; + } + } + + /** + * Get a string named with the given key. + * + *

If the key does not exist or its value is not a string tag, + * then {@code ""} will be returned.

+ * + * @param key the key + * @return a string + */ + public String getString(String key) { + Tag tag = getValue().get(key); + if (tag instanceof StringTag) { + return ((StringTag) tag).getValue(); + } else { + return ""; + } + } + + @Override + public String toString() { + StringBuilder bldr = new StringBuilder(); + bldr.append("TAG_Compound").append(": ").append(getValue().size()).append(" entries\r\n{\r\n"); + for (Map.Entry entry : getValue().entrySet()) { + bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); + } + bldr.append("}"); + return bldr.toString(); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/jnbt/CompoundTagBuilder.java b/worldedit-core/src/main/java/com/sk89q/jnbt/CompoundTagBuilder.java index 1799993bb..2e701ddf3 100644 --- a/worldedit-core/src/main/java/com/sk89q/jnbt/CompoundTagBuilder.java +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/CompoundTagBuilder.java @@ -35,7 +35,7 @@ public class CompoundTagBuilder { * Create a new instance. */ public CompoundTagBuilder() { - this.entries = new HashMap(); + this.entries = new HashMap<>(); } /** @@ -201,7 +201,7 @@ public class CompoundTagBuilder { * @return the new compound tag */ public CompoundTag build() { - return new CompoundTag(new HashMap(entries)); + return new CompoundTag(new HashMap<>(entries)); } /** @@ -213,4 +213,4 @@ public class CompoundTagBuilder { return new CompoundTagBuilder(); } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/jnbt/CompressedCompoundTag.java b/worldedit-core/src/main/java/com/sk89q/jnbt/CompressedCompoundTag.java new file mode 100644 index 000000000..6ce8b20f1 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/CompressedCompoundTag.java @@ -0,0 +1,42 @@ +package com.sk89q.jnbt; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +public abstract class CompressedCompoundTag extends CompoundTag { + private T in; + + public CompressedCompoundTag(T in) { + super(new HashMap<>()); + this.in = in; + } + + @Override + public Map getValue() { + if (in != null) decompress(); + return super.getValue(); + } + + public abstract DataInputStream adapt(T src) throws IOException; + + public T getSource() { + return in; + } + + private void decompress() { + try (NBTInputStream nbtIn = new NBTInputStream(adapt(in))) { + in = null; + CompoundTag tag = (CompoundTag) nbtIn.readTag(); + Map value = tag.getValue(); + Map raw = super.getValue(); + for (Map.Entry entry : value.entrySet()) { + raw.put(entry.getKey(), entry.getValue()); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/jnbt/CompressedSchematicTag.java b/worldedit-core/src/main/java/com/sk89q/jnbt/CompressedSchematicTag.java new file mode 100644 index 000000000..c5f43e4d6 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/CompressedSchematicTag.java @@ -0,0 +1,32 @@ +package com.sk89q.jnbt; + +import com.boydti.fawe.object.io.FastByteArrayOutputStream; +import com.boydti.fawe.object.io.FastByteArraysInputStream; +import com.boydti.fawe.object.io.PGZIPOutputStream; +import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.SpongeSchematicWriter; +import net.jpountz.lz4.LZ4BlockInputStream; +import net.jpountz.lz4.LZ4BlockOutputStream; + +import java.io.DataInputStream; +import java.io.IOException; +import java.util.zip.GZIPInputStream; + +public class CompressedSchematicTag extends CompressedCompoundTag { + public CompressedSchematicTag(Clipboard holder) { + super(holder); + } + + @Override + public DataInputStream adapt(Clipboard src) throws IOException { + FastByteArrayOutputStream blocksOut = new FastByteArrayOutputStream(); + try (LZ4BlockOutputStream lz4out = new LZ4BlockOutputStream(blocksOut)) { + NBTOutputStream nbtOut = new NBTOutputStream(lz4out); + new SpongeSchematicWriter(nbtOut).write(getSource()); + } catch (IOException e) { + throw new RuntimeException(e); + } + FastByteArraysInputStream in = new FastByteArraysInputStream(blocksOut.toByteArrays()); + return new DataInputStream(new LZ4BlockInputStream(in)); + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/jnbt/EndTag.java b/worldedit-core/src/main/java/com/sk89q/jnbt/EndTag.java index 3674740de..02da93f18 100644 --- a/worldedit-core/src/main/java/com/sk89q/jnbt/EndTag.java +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/EndTag.java @@ -1,40 +1,37 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.jnbt; - -/** - * The {@code TAG_End} tag. - */ -public final class EndTag extends Tag { - public static final EndTag INSTANCE = new EndTag(); - - private EndTag() {} - - @Override - public Object getValue() { - return null; - } - - @Override - public String toString() { - return "TAG_End"; - } - -} +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.jnbt; + +/** + * The {@code TAG_End} tag. + */ +public final class EndTag extends Tag { + + @Override + public Object getValue() { + return null; + } + + @Override + public String toString() { + return "TAG_End"; + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/jnbt/ListTag.java b/worldedit-core/src/main/java/com/sk89q/jnbt/ListTag.java index e9f92b99a..13b7f1235 100644 --- a/worldedit-core/src/main/java/com/sk89q/jnbt/ListTag.java +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/ListTag.java @@ -1,423 +1,430 @@ -package com.sk89q.jnbt; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.NoSuchElementException; - -import javax.annotation.Nullable; - -/** - * The {@code TAG_List} tag. - */ -public final class ListTag extends Tag { - - private final Class type; - private final List value; - - /** - * Creates the tag with an empty name. - * - * @param type the type of tag - * @param value the value of the tag - */ - public ListTag(Class type, List value) { - super(); - checkNotNull(value); - this.type = type; - this.value = value; - } - - @Override - public List getRaw() { - ArrayList raw = new ArrayList<>(); - for (Tag t : value) { - raw.add(t.getRaw()); - } - return raw; - } - - /** - * Gets the type of item in this list. - * - * @return The type of item in this list. - */ - public Class getType() { - return type; - } - - @Override - public List getValue() { - return value; - } - - /** - * Create a new list tag with this tag's name and type. - * - * @param list the new list - * @return a new list tag - */ - public ListTag setValue(List list) { - return new ListTag(getType(), list); - } - - /** - * Get the tag if it exists at the given index. - * - * @param index the index - * @return the tag or null - */ - @Nullable - public Tag getIfExists(int index) { - try { - return value.get(index); - } catch (NoSuchElementException e) { - return null; - } - } - - /** - * Get a byte array named with the given index. - * - *

If the index does not exist or its value is not a byte array tag, - * then an empty byte array will be returned.

- * - * @param index the index - * @return a byte array - */ - public byte[] getByteArray(int index) { - Tag tag = getIfExists(index); - if (tag instanceof ByteArrayTag) { - return ((ByteArrayTag) tag).getValue(); - } else { - return new byte[0]; - } - } - - /** - * Get a byte named with the given index. - * - *

If the index does not exist or its value is not a byte tag, - * then {@code 0} will be returned.

- * - * @param index the index - * @return a byte - */ - public byte getByte(int index) { - Tag tag = getIfExists(index); - if (tag instanceof ByteTag) { - return ((ByteTag) tag).getValue(); - } else { - return (byte) 0; - } - } - - /** - * Get a double named with the given index. - * - *

If the index does not exist or its value is not a double tag, - * then {@code 0} will be returned.

- * - * @param index the index - * @return a double - */ - public double getDouble(int index) { - Tag tag = getIfExists(index); - if (tag instanceof DoubleTag) { - return ((DoubleTag) tag).getValue(); - } else { - return 0; - } - } - - /** - * Get a double named with the given index, even if it's another - * type of number. - * - *

If the index does not exist or its value is not a number, - * then {@code 0} will be returned.

- * - * @param index the index - * @return a double - */ - public double asDouble(int index) { - Tag tag = getIfExists(index); - if (tag instanceof ByteTag) { - return ((ByteTag) tag).getValue(); - - } else if (tag instanceof ShortTag) { - return ((ShortTag) tag).getValue(); - - } else if (tag instanceof IntTag) { - return ((IntTag) tag).getValue(); - - } else if (tag instanceof LongTag) { - return ((LongTag) tag).getValue(); - - } else if (tag instanceof FloatTag) { - return ((FloatTag) tag).getValue(); - - } else if (tag instanceof DoubleTag) { - return ((DoubleTag) tag).getValue(); - - } else { - return 0; - } - } - - /** - * Get a float named with the given index. - * - *

If the index does not exist or its value is not a float tag, - * then {@code 0} will be returned.

- * - * @param index the index - * @return a float - */ - public float getFloat(int index) { - Tag tag = getIfExists(index); - if (tag instanceof FloatTag) { - return ((FloatTag) tag).getValue(); - } else { - return 0; - } - } - - /** - * Get a {@code int[]} named with the given index. - * - *

If the index does not exist or its value is not an int array tag, - * then an empty array will be returned.

- * - * @param index the index - * @return an int array - */ - public int[] getIntArray(int index) { - Tag tag = getIfExists(index); - if (tag instanceof IntArrayTag) { - return ((IntArrayTag) tag).getValue(); - } else { - return new int[0]; - } - } - - /** - * Get an int named with the given index. - * - *

If the index does not exist or its value is not an int tag, - * then {@code 0} will be returned.

- * - * @param index the index - * @return an int - */ - public int getInt(int index) { - Tag tag = getIfExists(index); - if (tag instanceof IntTag) { - return ((IntTag) tag).getValue(); - } else { - return 0; - } - } - - /** - * Get an int named with the given index, even if it's another - * type of number. - * - *

If the index does not exist or its value is not a number, - * then {@code 0} will be returned.

- * - * @param index the index - * @return an int - */ - public int asInt(int index) { - Tag tag = getIfExists(index); - if (tag instanceof ByteTag) { - return ((ByteTag) tag).getValue(); - - } else if (tag instanceof ShortTag) { - return ((ShortTag) tag).getValue(); - - } else if (tag instanceof IntTag) { - return ((IntTag) tag).getValue(); - - } else if (tag instanceof LongTag) { - return ((LongTag) tag).getValue().intValue(); - - } else if (tag instanceof FloatTag) { - return ((FloatTag) tag).getValue().intValue(); - - } else if (tag instanceof DoubleTag) { - return ((DoubleTag) tag).getValue().intValue(); - - } else { - return 0; - } - } - - /** - * Get a list of tags named with the given index. - * - *

If the index does not exist or its value is not a list tag, - * then an empty list will be returned.

- * - * @param index the index - * @return a list of tags - */ - public List getList(int index) { - Tag tag = getIfExists(index); - if (tag instanceof ListTag) { - return ((ListTag) tag).getValue(); - } else { - return Collections.emptyList(); - } - } - - /** - * Get a {@code TagList} named with the given index. - * - *

If the index does not exist or its value is not a list tag, - * then an empty tag list will be returned.

- * - * @param index the index - * @return a tag list instance - */ - public ListTag getListTag(int index) { - Tag tag = getIfExists(index); - if (tag instanceof ListTag) { - return (ListTag) tag; - } else { - return new ListTag(StringTag.class, Collections.emptyList()); - } - } - - /** - * Get a list of tags named with the given index. - * - *

If the index does not exist or its value is not a list tag, - * then an empty list will be returned. If the given index references - * a list but the list of of a different type, then an empty - * list will also be returned.

- * - * @param index the index - * @param listType the class of the contained type - * @return a list of tags - * @param the NBT type - */ - @SuppressWarnings("unchecked") - public List getList(int index, Class listType) { - Tag tag = getIfExists(index); - if (tag instanceof ListTag) { - ListTag listTag = (ListTag) tag; - if (listTag.getType().equals(listType)) { - return (List) listTag.getValue(); - } else { - return Collections.emptyList(); - } - } else { - return Collections.emptyList(); - } - } - - /** - * Get a long named with the given index. - * - *

If the index does not exist or its value is not a long tag, - * then {@code 0} will be returned.

- * - * @param index the index - * @return a long - */ - public long getLong(int index) { - Tag tag = getIfExists(index); - if (tag instanceof LongTag) { - return ((LongTag) tag).getValue(); - } else { - return 0L; - } - } - - /** - * Get a long named with the given index, even if it's another - * type of number. - * - *

If the index does not exist or its value is not a number, - * then {@code 0} will be returned.

- * - * @param index the index - * @return a long - */ - public long asLong(int index) { - Tag tag = getIfExists(index); - if (tag instanceof ByteTag) { - return ((ByteTag) tag).getValue(); - - } else if (tag instanceof ShortTag) { - return ((ShortTag) tag).getValue(); - - } else if (tag instanceof IntTag) { - return ((IntTag) tag).getValue(); - - } else if (tag instanceof LongTag) { - return ((LongTag) tag).getValue(); - - } else if (tag instanceof FloatTag) { - return ((FloatTag) tag).getValue().longValue(); - - } else if (tag instanceof DoubleTag) { - return ((DoubleTag) tag).getValue().longValue(); - - } else { - return 0; - } - } - - /** - * Get a short named with the given index. - * - *

If the index does not exist or its value is not a short tag, - * then {@code 0} will be returned.

- * - * @param index the index - * @return a short - */ - public short getShort(int index) { - Tag tag = getIfExists(index); - if (tag instanceof ShortTag) { - return ((ShortTag) tag).getValue(); - } else { - return 0; - } - } - - /** - * Get a string named with the given index. - * - *

If the index does not exist or its value is not a string tag, - * then {@code ""} will be returned.

- * - * @param index the index - * @return a string - */ - public String getString(int index) { - Tag tag = getIfExists(index); - if (tag instanceof StringTag) { - return ((StringTag) tag).getValue(); - } else { - return ""; - } - } - - @Override - public String toString() { - StringBuilder bldr = new StringBuilder(); - bldr.append("TAG_List").append(": ").append(value.size()).append(" entries of type ").append(NBTUtils.getTypeName(type)).append("\r\n{\r\n"); - for (Tag t : value) { - bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); - } - bldr.append("}"); - return bldr.toString(); - } - -} \ No newline at end of file +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.jnbt; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Collections; +import java.util.List; + +import javax.annotation.Nullable; + +/** + * The {@code TAG_List} tag. + */ +public final class ListTag extends Tag { + + private final Class type; + private final List value; + + /** + * Creates the tag with an empty name. + * + * @param type the type of tag + * @param value the value of the tag + */ + public ListTag(Class type, List value) { + super(); + checkNotNull(value); + this.type = type; + this.value = Collections.unmodifiableList(value); + } + + /** + * Gets the type of item in this list. + * + * @return The type of item in this list. + */ + public Class getType() { + return type; + } + + @Override + public List getValue() { + return value; + } + + /** + * Create a new list tag with this tag's name and type. + * + * @param list the new list + * @return a new list tag + */ + public ListTag setValue(List list) { + return new ListTag(getType(), list); + } + + /** + * Get the tag if it exists at the given index. + * + * @param index the index + * @return the tag or null + */ + @Nullable + public Tag getIfExists(int index) { + if (index >= value.size()) { + return null; + } + return value.get(index); + } + + /** + * Get a byte array named with the given index. + * + *

If the index does not exist or its value is not a byte array tag, + * then an empty byte array will be returned.

+ * + * @param index the index + * @return a byte array + */ + public byte[] getByteArray(int index) { + Tag tag = getIfExists(index); + if (tag instanceof ByteArrayTag) { + return ((ByteArrayTag) tag).getValue(); + } else { + return new byte[0]; + } + } + + /** + * Get a byte named with the given index. + * + *

If the index does not exist or its value is not a byte tag, + * then {@code 0} will be returned.

+ * + * @param index the index + * @return a byte + */ + public byte getByte(int index) { + Tag tag = getIfExists(index); + if (tag instanceof ByteTag) { + return ((ByteTag) tag).getValue(); + } else { + return (byte) 0; + } + } + + /** + * Get a double named with the given index. + * + *

If the index does not exist or its value is not a double tag, + * then {@code 0} will be returned.

+ * + * @param index the index + * @return a double + */ + public double getDouble(int index) { + Tag tag = getIfExists(index); + if (tag instanceof DoubleTag) { + return ((DoubleTag) tag).getValue(); + } else { + return 0; + } + } + + /** + * Get a double named with the given index, even if it's another + * type of number. + * + *

If the index does not exist or its value is not a number, + * then {@code 0} will be returned.

+ * + * @param index the index + * @return a double + */ + public double asDouble(int index) { + Tag tag = getIfExists(index); + if (tag instanceof ByteTag) { + return ((ByteTag) tag).getValue(); + + } else if (tag instanceof ShortTag) { + return ((ShortTag) tag).getValue(); + + } else if (tag instanceof IntTag) { + return ((IntTag) tag).getValue(); + + } else if (tag instanceof LongTag) { + return ((LongTag) tag).getValue(); + + } else if (tag instanceof FloatTag) { + return ((FloatTag) tag).getValue(); + + } else if (tag instanceof DoubleTag) { + return ((DoubleTag) tag).getValue(); + + } else { + return 0; + } + } + + /** + * Get a float named with the given index. + * + *

If the index does not exist or its value is not a float tag, + * then {@code 0} will be returned.

+ * + * @param index the index + * @return a float + */ + public float getFloat(int index) { + Tag tag = getIfExists(index); + if (tag instanceof FloatTag) { + return ((FloatTag) tag).getValue(); + } else { + return 0; + } + } + + /** + * Get a {@code int[]} named with the given index. + * + *

If the index does not exist or its value is not an int array tag, + * then an empty array will be returned.

+ * + * @param index the index + * @return an int array + */ + public int[] getIntArray(int index) { + Tag tag = getIfExists(index); + if (tag instanceof IntArrayTag) { + return ((IntArrayTag) tag).getValue(); + } else { + return new int[0]; + } + } + + /** + * Get an int named with the given index. + * + *

If the index does not exist or its value is not an int tag, + * then {@code 0} will be returned.

+ * + * @param index the index + * @return an int + */ + public int getInt(int index) { + Tag tag = getIfExists(index); + if (tag instanceof IntTag) { + return ((IntTag) tag).getValue(); + } else { + return 0; + } + } + + /** + * Get an int named with the given index, even if it's another + * type of number. + * + *

If the index does not exist or its value is not a number, + * then {@code 0} will be returned.

+ * + * @param index the index + * @return an int + */ + public int asInt(int index) { + Tag tag = getIfExists(index); + if (tag instanceof ByteTag) { + return ((ByteTag) tag).getValue(); + + } else if (tag instanceof ShortTag) { + return ((ShortTag) tag).getValue(); + + } else if (tag instanceof IntTag) { + return ((IntTag) tag).getValue(); + + } else if (tag instanceof LongTag) { + return ((LongTag) tag).getValue().intValue(); + + } else if (tag instanceof FloatTag) { + return ((FloatTag) tag).getValue().intValue(); + + } else if (tag instanceof DoubleTag) { + return ((DoubleTag) tag).getValue().intValue(); + + } else { + return 0; + } + } + + /** + * Get a list of tags named with the given index. + * + *

If the index does not exist or its value is not a list tag, + * then an empty list will be returned.

+ * + * @param index the index + * @return a list of tags + */ + public List getList(int index) { + Tag tag = getIfExists(index); + if (tag instanceof ListTag) { + return ((ListTag) tag).getValue(); + } else { + return Collections.emptyList(); + } + } + + /** + * Get a {@code TagList} named with the given index. + * + *

If the index does not exist or its value is not a list tag, + * then an empty tag list will be returned.

+ * + * @param index the index + * @return a tag list instance + */ + public ListTag getListTag(int index) { + Tag tag = getIfExists(index); + if (tag instanceof ListTag) { + return (ListTag) tag; + } else { + return new ListTag(StringTag.class, Collections.emptyList()); + } + } + + /** + * Get a list of tags named with the given index. + * + *

If the index does not exist or its value is not a list tag, + * then an empty list will be returned. If the given index references + * a list but the list of of a different type, then an empty + * list will also be returned.

+ * + * @param index the index + * @param listType the class of the contained type + * @return a list of tags + * @param the NBT type + */ + @SuppressWarnings("unchecked") + public List getList(int index, Class listType) { + Tag tag = getIfExists(index); + if (tag instanceof ListTag) { + ListTag listTag = (ListTag) tag; + if (listTag.getType().equals(listType)) { + return (List) listTag.getValue(); + } else { + return Collections.emptyList(); + } + } else { + return Collections.emptyList(); + } + } + + /** + * Get a long named with the given index. + * + *

If the index does not exist or its value is not a long tag, + * then {@code 0} will be returned.

+ * + * @param index the index + * @return a long + */ + public long getLong(int index) { + Tag tag = getIfExists(index); + if (tag instanceof LongTag) { + return ((LongTag) tag).getValue(); + } else { + return 0L; + } + } + + /** + * Get a long named with the given index, even if it's another + * type of number. + * + *

If the index does not exist or its value is not a number, + * then {@code 0} will be returned.

+ * + * @param index the index + * @return a long + */ + public long asLong(int index) { + Tag tag = getIfExists(index); + if (tag instanceof ByteTag) { + return ((ByteTag) tag).getValue(); + + } else if (tag instanceof ShortTag) { + return ((ShortTag) tag).getValue(); + + } else if (tag instanceof IntTag) { + return ((IntTag) tag).getValue(); + + } else if (tag instanceof LongTag) { + return ((LongTag) tag).getValue(); + + } else if (tag instanceof FloatTag) { + return ((FloatTag) tag).getValue().longValue(); + + } else if (tag instanceof DoubleTag) { + return ((DoubleTag) tag).getValue().longValue(); + + } else { + return 0; + } + } + + /** + * Get a short named with the given index. + * + *

If the index does not exist or its value is not a short tag, + * then {@code 0} will be returned.

+ * + * @param index the index + * @return a short + */ + public short getShort(int index) { + Tag tag = getIfExists(index); + if (tag instanceof ShortTag) { + return ((ShortTag) tag).getValue(); + } else { + return 0; + } + } + + /** + * Get a string named with the given index. + * + *

If the index does not exist or its value is not a string tag, + * then {@code ""} will be returned.

+ * + * @param index the index + * @return a string + */ + public String getString(int index) { + Tag tag = getIfExists(index); + if (tag instanceof StringTag) { + return ((StringTag) tag).getValue(); + } else { + return ""; + } + } + + @Override + public String toString() { + StringBuilder bldr = new StringBuilder(); + bldr.append("TAG_List").append(": ").append(value.size()).append(" entries of type ").append(NBTUtils.getTypeName(type)).append("\r\n{\r\n"); + for (Tag t : value) { + bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); + } + bldr.append("}"); + return bldr.toString(); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/jnbt/ListTagBuilder.java b/worldedit-core/src/main/java/com/sk89q/jnbt/ListTagBuilder.java index c410ec3ae..ab2b41399 100644 --- a/worldedit-core/src/main/java/com/sk89q/jnbt/ListTagBuilder.java +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/ListTagBuilder.java @@ -97,7 +97,7 @@ public class ListTagBuilder { * * @return a new builder */ - public static ListTagBuilder createWith(T ... entries) { + public static ListTagBuilder createWith(Tag... entries) { checkNotNull(entries); if (entries.length == 0) { 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 414af43fd..03c708844 100644 --- a/worldedit-core/src/main/java/com/sk89q/jnbt/NBTInputStream.java +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/NBTInputStream.java @@ -1,620 +1,623 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.jnbt; - -import com.boydti.fawe.jnbt.NBTStreamer; -import com.boydti.fawe.object.RunnableVal2; -import java.io.Closeable; -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiConsumer; -import java.util.function.Function; - -/** - * This class reads NBT, or Named Binary Tag - * streams, and produces an object graph of subclasses of the {@code Tag} - * object. - * - *

The NBT format was created by Markus Persson, and the specification may be - * found at - * http://www.minecraft.net/docs/NBT.txt.

- */ -public final class NBTInputStream implements Closeable { - - private final DataInputStream is; - - /** - * Creates a new {@code NBTInputStream}, which will source its data - * from the specified input stream. - * - * @param is the input stream - * @throws IOException if an I/O error occurs - */ - public NBTInputStream(InputStream is) throws IOException { - this.is = new DataInputStream(is); - } - - public NBTInputStream(DataInputStream dis) { - this.is = dis; - } - - public DataInputStream getInputStream() { - return is; - } - - /** - * Reads an NBT tag from the stream. - * - * @return The tag that was read. - * @throws IOException if an I/O error occurs. - */ - public NamedTag readNamedTag() throws IOException { - return readNamedTag(0); - } - - /** - * Reads an NBT map from the stream. - * - * @return The map that was read. - * @throws IOException if an I/O error occurs. - */ - public NamedData readNamedData() throws IOException { - return readNamedData(0); - } - - /** - * Reads an NBT from the stream. - * - * @param depth the depth of this tag - * @return The tag that was read. - * @throws IOException if an I/O error occurs. - */ - private NamedTag readNamedTag(int depth) throws IOException { - int type = is.readByte() & 0xFF; - return new NamedTag(readNamedTagName(type), readTagPayload(type, depth)); - } - - private NamedData readNamedData(int depth) throws IOException { - int type = is.readByte(); - return new NamedData(readNamedTagName(type), readDataPayload(type, depth)); - } - - public Tag readTag() throws IOException { - int type = is.readByte(); - return readTagPayload(type, 0); - } - - public Object readData() throws IOException { - int type = is.readByte(); - return readDataPayload(type, 0); - } - - public void readNamedTagLazy(Function getReader) throws IOException { - int type = is.readByte(); - String name = readNamedTagName(type); - BiConsumer reader = getReader.apply(name); - if (reader != null) { - reader.accept(0, readTagPaylodRaw(type, 0)); - return; - } - readTagPaylodLazy(type, 0, name, getReader); - } - - public String readNamedTagName(int type) throws IOException { - String name; - if (type != NBTConstants.TYPE_END) { - int nameLength = is.readShort() & 0xFFFF; - byte[] nameBytes = new byte[nameLength]; - is.readFully(nameBytes); - return new String(nameBytes, NBTConstants.CHARSET); - } else { - return ""; - } - } - - private byte[] buf; - - public void readTagPaylodLazy(int type, int depth, String node, Function getReader) throws IOException { - switch (type) { - case NBTConstants.TYPE_END: - return; - case NBTConstants.TYPE_BYTE: - is.skipBytes(1); - return; - case NBTConstants.TYPE_SHORT: - is.skipBytes(2); - return; - case NBTConstants.TYPE_INT: - is.skipBytes(4); - return; - case NBTConstants.TYPE_LONG: - is.skipBytes(8); - return; - case NBTConstants.TYPE_FLOAT: - is.skipBytes(4); - return; - case NBTConstants.TYPE_DOUBLE: - is.skipBytes(8); - return; - case NBTConstants.TYPE_STRING: - int length = is.readShort(); - is.skipBytes(length); - return; - case NBTConstants.TYPE_BYTE_ARRAY: - BiConsumer reader = getReader.apply(node + ".?"); - length = is.readInt(); - if (reader != null) { - reader.accept(length, NBTConstants.TYPE_BYTE); - } - reader = getReader.apply(node + ".#"); - if (reader == null) { - is.skipBytes(length); - return; - } - if (reader instanceof NBTStreamer.ByteReader) { - NBTStreamer.ByteReader byteReader = (NBTStreamer.ByteReader) reader; - int i = 0; - if (is instanceof InputStream) { - DataInputStream dis = is; - if (length > 1024) { - if (buf == null) { - buf = new byte[1024]; - } - int left = length; - for (; left > 1024; left -= 1024) { - dis.readFully(buf); - for (byte b : buf) { - byteReader.run(i++, b & 0xFF); - } - } - } - for (; i < length; i++) { - byteReader.run(i, dis.read()); - } - } else { - if (length > 1024) { - if (buf == null) { - buf = new byte[1024]; - } - int left = length; - for (; left > 1024; left -= 1024) { - is.readFully(buf); - for (byte b : buf) { - byteReader.run(i++, b & 0xFF); - } - } - } - for (; i < length; i++) { - byteReader.run(i, is.readByte() & 0xFF); - } - } - } else if (reader instanceof NBTStreamer.LazyReader) { - reader.accept(length, is); - } else { - for (int i = 0; i < length; i++) { - reader.accept(i, is.readByte()); - } - } - return; - case NBTConstants.TYPE_LIST: - int childType = is.readByte(); - if (childType == NBTConstants.TYPE_LIST) { - childType = NBTConstants.TYPE_COMPOUND; - } - length = is.readInt(); - reader = getReader.apply(node + ".?"); - if (reader != null) { - reader.accept(length, childType); - } - node += ".#"; - reader = getReader.apply(node); - depth++; - if (reader == null) { - for (int i = 0; i < length; ++i) { - readTagPaylodLazy(childType, depth, node, getReader); - } - return; - } - for (int i = 0; i < length; ++i) { - reader.accept(i, readTagPayload(childType, depth)); - } - return; - case NBTConstants.TYPE_COMPOUND: - depth++; - // 3 - for (int i = 0; ; i++) { - childType = is.readByte(); - if (childType == NBTConstants.TYPE_END) { - return; - } - String name = readNamedTagName(childType); - String childNode = node + "." + name; - reader = getReader.apply(childNode); - if (reader == null) { - readTagPaylodLazy(childType, depth, childNode, getReader); - continue; - } - reader.accept(i, readTagPaylodRaw(childType, depth)); - } - case NBTConstants.TYPE_INT_ARRAY: { - length = is.readInt(); - reader = getReader.apply(node + ".?"); - if (reader != null) { - reader.accept(length, NBTConstants.TYPE_INT); - } - reader = getReader.apply(node + ".#"); - if (reader == null) { - is.skipBytes(length << 2); - return; - } - if (reader instanceof NBTStreamer.ByteReader) { - NBTStreamer.ByteReader byteReader = (NBTStreamer.ByteReader) reader; - for (int i = 0; i < length; i++) { - byteReader.run(i, is.readInt()); - } - } else if (reader instanceof NBTStreamer.LazyReader) { - reader.accept(length, is); - } else { - for (int i = 0; i < length; i++) { - reader.accept(i, is.readInt()); - } - } - return; - } - case NBTConstants.TYPE_LONG_ARRAY: { - length = is.readInt(); - reader = getReader.apply(node + ".?"); - if (reader != null) { - reader.accept(length, NBTConstants.TYPE_LONG); - } - reader = getReader.apply(node + ".#"); - if (reader == null) { - is.skipBytes(length << 3); - return; - } - if (reader instanceof NBTStreamer.LongReader) { - NBTStreamer.LongReader longReader = (NBTStreamer.LongReader) reader; - for (int i = 0; i < length; i++) { - longReader.run(i, is.readLong()); - } - } else if (reader instanceof NBTStreamer.LazyReader) { - reader.accept(length, is); - } else { - for (int i = 0; i < length; i++) { - reader.accept(i, is.readLong()); - } - } - return; - } - - default: - throw new IOException("Invalid tag type: " + type + "."); - } - } - - public static int getSize(int type) { - switch (type) { - default: - case NBTConstants.TYPE_END: - case NBTConstants.TYPE_BYTE: - return 1; - case NBTConstants.TYPE_BYTE_ARRAY: - case NBTConstants.TYPE_STRING: - case NBTConstants.TYPE_LIST: - case NBTConstants.TYPE_COMPOUND: - case NBTConstants.TYPE_INT_ARRAY: - case NBTConstants.TYPE_LONG_ARRAY: - case NBTConstants.TYPE_SHORT: - return 2; - case NBTConstants.TYPE_FLOAT: - case NBTConstants.TYPE_INT: - return 4; - case NBTConstants.TYPE_DOUBLE: - case NBTConstants.TYPE_LONG: - return 8; - } - } - - private Object readTagPaylodRaw(int type, int depth) throws IOException { - switch (type) { - case NBTConstants.TYPE_END: - if (depth == 0) { - throw new IOException( - "TAG_End found without a TAG_Compound/TAG_List tag preceding it."); - } else { - return null; - } - case NBTConstants.TYPE_BYTE: - return (is.readByte()); - case NBTConstants.TYPE_SHORT: - return (is.readShort()); - case NBTConstants.TYPE_INT: - return (is.readInt()); - case NBTConstants.TYPE_LONG: - return (is.readLong()); - case NBTConstants.TYPE_FLOAT: - return (is.readFloat()); - case NBTConstants.TYPE_DOUBLE: - return (is.readDouble()); - case NBTConstants.TYPE_BYTE_ARRAY: - int length = is.readInt(); - byte[] bytes = new byte[length]; - is.readFully(bytes); - return (bytes); - case NBTConstants.TYPE_STRING: - length = is.readShort(); - bytes = new byte[length]; - is.readFully(bytes); - return (new String(bytes, NBTConstants.CHARSET)); - case NBTConstants.TYPE_LIST: - int childType = is.readByte(); - if (childType == NBTConstants.TYPE_LIST) { - childType = NBTConstants.TYPE_COMPOUND; - } - length = is.readInt(); - List tagList = new ArrayList(); - for (int i = 0; i < length; ++i) { - Tag tag = readTagPayload(childType, depth + 1); - if (tag instanceof EndTag) { - throw new IOException("TAG_End not permitted in a list."); - } - tagList.add(tag); - } - return (tagList); - case NBTConstants.TYPE_COMPOUND: - Map tagMap = new HashMap(); - while (true) { - NamedTag namedTag = readNamedTag(depth + 1); - Tag tag = namedTag.getTag(); - if (tag instanceof EndTag) { - break; - } else { - tagMap.put(namedTag.getName(), tag); - } - } - return (tagMap); - case NBTConstants.TYPE_INT_ARRAY: { - length = is.readInt(); - int[] data = new int[length]; - if (buf == null) { - buf = new byte[1024]; - } - int index = 0; - while (length > 0) { - int toRead = Math.min(length << 2, buf.length); - is.readFully(buf, 0, toRead); - for (int i = 0; i < toRead; i += 4, index++) { - data[index] = ((buf[i] << 24) + (buf[i + 1] << 16) + (buf[i + 2] << 8) + (buf[i + 3])); - } - length -= toRead; - } - return (data); - } - case NBTConstants.TYPE_LONG_ARRAY: { - length = is.readInt(); - long[] data = new long[length]; - if (buf == null) { - buf = new byte[1024]; - } - int index = 0; - while (length > 0) { - int toRead = Math.min(length << 3, buf.length); - is.readFully(buf, 0, toRead); - for (int i = 0; i < toRead; i += 8, index++) { - data[index] = (((long) buf[i] << 56) | ((long) buf[i + 1] << 48) | ((long) buf[i + 2] << 40) | ((long) buf[i + 3] << 32) | (buf[i + 4] << 24) | (buf[i + 5] << 16) | (buf[i + 6] << 8) | (buf[i + 7])); - } - length -= toRead; - } - return (data); - } - default: - throw new IOException("Invalid tag type: " + type + "."); - } - } - - public Object readDataPayload(int type, int depth) throws IOException { - switch (type) { - case NBTConstants.TYPE_END: - if (depth == 0) { - throw new IOException( - "TAG_End found without a TAG_Compound/TAG_List tag preceding it."); - } else { - return null; - } - case NBTConstants.TYPE_BYTE: - return is.readByte(); - case NBTConstants.TYPE_SHORT: - return is.readShort(); - case NBTConstants.TYPE_INT: - return is.readInt(); - case NBTConstants.TYPE_LONG: - return is.readLong(); - case NBTConstants.TYPE_FLOAT: - return is.readFloat(); - case NBTConstants.TYPE_DOUBLE: - return is.readDouble(); - case NBTConstants.TYPE_BYTE_ARRAY: - int length = is.readInt(); - byte[] bytes = new byte[length]; - is.readFully(bytes); - return bytes; - case NBTConstants.TYPE_STRING: - length = is.readShort(); - bytes = new byte[length]; - is.readFully(bytes); - return new String(bytes, NBTConstants.CHARSET); - case NBTConstants.TYPE_LIST: - int childType = is.readByte(); - if (childType == NBTConstants.TYPE_LIST) { - childType = NBTConstants.TYPE_COMPOUND; - } - length = is.readInt(); - ArrayList list = new ArrayList<>(); - for (int i = 0; i < length; ++i) { - Object obj = readDataPayload(childType, depth + 1); - if (obj == null) { - throw new IOException("TAG_End not permitted in a list."); - } - list.add(obj); - } - - return list; - case NBTConstants.TYPE_COMPOUND: - Map map = new HashMap<>(); - while (true) { - int newType = is.readByte(); - String name = readNamedTagName(newType); - Object data = readDataPayload(newType, depth + 1); - if (data == null) { - break; - } else { - map.put(name, data); - } - } - - return map; - case NBTConstants.TYPE_INT_ARRAY: { - length = is.readInt(); - int[] data = new int[length]; - for (int i = 0; i < length; i++) { - data[i] = is.readInt(); - } - return data; - } - case NBTConstants.TYPE_LONG_ARRAY: { - length = is.readInt(); - long[] data = new long[length]; - for (int i = 0; i < length; i++) { - data[i] = is.readLong(); - } - return data; - } - default: - throw new IOException("Invalid tag type: " + type + "."); - } - } - - /** - * Reads the payload of a tag given the type. - * - * @param type the type - * @param depth the depth - * @return the tag - * @throws IOException if an I/O error occurs. - */ - public Tag readTagPayload(int type, int depth) throws IOException { - switch (type) { - case NBTConstants.TYPE_END: - if (depth == 0) { - throw new IOException( - "TAG_End found without a TAG_Compound/TAG_List tag preceding it."); - } else { - return EndTag.INSTANCE; - } - case NBTConstants.TYPE_BYTE: - return new ByteTag(is.readByte()); - case NBTConstants.TYPE_SHORT: - return new ShortTag(is.readShort()); - case NBTConstants.TYPE_INT: - return new IntTag(is.readInt()); - case NBTConstants.TYPE_LONG: - return new LongTag(is.readLong()); - case NBTConstants.TYPE_FLOAT: - return new FloatTag(is.readFloat()); - case NBTConstants.TYPE_DOUBLE: - return new DoubleTag(is.readDouble()); - case NBTConstants.TYPE_BYTE_ARRAY: - int length = is.readInt(); - byte[] bytes = new byte[length]; - is.readFully(bytes); - return new ByteArrayTag(bytes); - case NBTConstants.TYPE_STRING: - length = is.readShort(); - bytes = new byte[length]; - is.readFully(bytes); - return new StringTag(new String(bytes, NBTConstants.CHARSET)); - case NBTConstants.TYPE_LIST: - int childType = is.readByte(); - if (childType == NBTConstants.TYPE_LIST) { - childType = NBTConstants.TYPE_COMPOUND; - } - length = is.readInt(); - List tagList = new ArrayList(); - for (int i = 0; i < length; ++i) { - Tag tag = readTagPayload(childType, depth + 1); - if (tag instanceof EndTag) { - throw new IOException("TAG_End not permitted in a list."); - } - tagList.add(tag); - } - - return new ListTag(NBTUtils.getTypeClass(childType), tagList); - case NBTConstants.TYPE_COMPOUND: - Map tagMap = new HashMap(); - while (true) { - NamedTag namedTag = readNamedTag(depth + 1); - Tag tag = namedTag.getTag(); - if (tag instanceof EndTag) { - break; - } else { - tagMap.put(namedTag.getName(), tag); - } - } - - return new CompoundTag(tagMap); - case NBTConstants.TYPE_INT_ARRAY: { - length = is.readInt(); - int[] data = new int[length]; - for (int i = 0; i < length; i++) { - data[i] = is.readInt(); - } - return new IntArrayTag(data); - } - case NBTConstants.TYPE_LONG_ARRAY: { - length = is.readInt(); - long[] data = new long[length]; - for (int i = 0; i < length; i++) { - data[i] = is.readLong(); - } - return new LongArrayTag(data); - } - default: - throw new IOException("Invalid tag type: " + type + "."); - } - } - - @Override - public void close() throws IOException { - if (is instanceof AutoCloseable) { - try { - ((AutoCloseable) is).close(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - -} +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.jnbt; + +import com.boydti.fawe.jnbt.NBTStreamer; +import com.boydti.fawe.object.RunnableVal2; +import com.boydti.fawe.util.StringMan; + +import java.io.Closeable; +import java.io.DataInput; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Function; + +/** + * This class reads NBT, or Named Binary Tag + * streams, and produces an object graph of subclasses of the {@code Tag} + * object. + * + *

The NBT format was created by Markus Persson, and the specification may be + * found at + * http://www.minecraft.net/docs/NBT.txt.

+ */ +public final class NBTInputStream implements Closeable { + + private final DataInputStream is; + + /** + * Creates a new {@code NBTInputStream}, which will source its data + * from the specified input stream. + * + * @param is the input stream + * @throws IOException if an I/O error occurs + */ + public NBTInputStream(InputStream is) throws IOException { + this.is = new DataInputStream(is); + } + + public NBTInputStream(DataInputStream dis) { + this.is = dis; + } + + public DataInputStream getInputStream() { + return is; + } + + /** + * Reads an NBT tag from the stream. + * + * @return The tag that was read. + * @throws IOException if an I/O error occurs. + */ + public NamedTag readNamedTag() throws IOException { + return readNamedTag(0); + } + + /** + * Reads an NBT map from the stream. + * + * @return The map that was read. + * @throws IOException if an I/O error occurs. + */ + public NamedData readNamedData() throws IOException { + return readNamedData(0); + } + + /** + * Reads an NBT from the stream. + * + * @param depth the depth of this tag + * @return The tag that was read. + * @throws IOException if an I/O error occurs. + */ + private NamedTag readNamedTag(int depth) throws IOException { + int type = is.readByte() & 0xFF; + return new NamedTag(readNamedTagName(type), readTagPayload(type, depth)); + } + + private NamedData readNamedData(int depth) throws IOException { + int type = is.readByte(); + return new NamedData(readNamedTagName(type), readDataPayload(type, depth)); + } + + public Tag readTag() throws IOException { + int type = is.readByte(); + return readTagPayload(type, 0); + } + + public Object readData() throws IOException { + int type = is.readByte(); + return readDataPayload(type, 0); + } + + public void readNamedTagLazy(Function getReader) throws IOException { + int type = is.readByte(); + String name = readNamedTagName(type); + BiConsumer reader = getReader.apply(name); + if (reader != null) { + reader.accept(0, readTagPaylodRaw(type, 0)); + return; + } + readTagPaylodLazy(type, 0, name, getReader); + } + + public String readNamedTagName(int type) throws IOException { + String name; + if (type != NBTConstants.TYPE_END) { + int nameLength = is.readShort() & 0xFFFF; + byte[] nameBytes = new byte[nameLength]; + is.readFully(nameBytes); + return new String(nameBytes, NBTConstants.CHARSET); + } else { + return ""; + } + } + + private byte[] buf; + + public void readTagPaylodLazy(int type, int depth, String node, Function getReader) throws IOException { + switch (type) { + case NBTConstants.TYPE_END: + return; + case NBTConstants.TYPE_BYTE: + is.skipBytes(1); + return; + case NBTConstants.TYPE_SHORT: + is.skipBytes(2); + return; + case NBTConstants.TYPE_INT: + is.skipBytes(4); + return; + case NBTConstants.TYPE_LONG: + is.skipBytes(8); + return; + case NBTConstants.TYPE_FLOAT: + is.skipBytes(4); + return; + case NBTConstants.TYPE_DOUBLE: + is.skipBytes(8); + return; + case NBTConstants.TYPE_STRING: + int length = is.readShort(); + is.skipBytes(length); + return; + case NBTConstants.TYPE_BYTE_ARRAY: + BiConsumer reader = getReader.apply(node + ".?"); + length = is.readInt(); + if (reader != null) { + reader.accept(length, NBTConstants.TYPE_BYTE); + } + reader = getReader.apply(node + ".#"); + if (reader == null) { + is.skipBytes(length); + return; + } + if (reader instanceof NBTStreamer.ByteReader) { + NBTStreamer.ByteReader byteReader = (NBTStreamer.ByteReader) reader; + int i = 0; + if (is instanceof InputStream) { + DataInputStream dis = is; + if (length > 1024) { + if (buf == null) { + buf = new byte[1024]; + } + int left = length; + for (; left > 1024; left -= 1024) { + dis.readFully(buf); + for (byte b : buf) { + byteReader.run(i++, b & 0xFF); + } + } + } + for (; i < length; i++) { + byteReader.run(i, dis.read()); + } + } else { + if (length > 1024) { + if (buf == null) { + buf = new byte[1024]; + } + int left = length; + for (; left > 1024; left -= 1024) { + is.readFully(buf); + for (byte b : buf) { + byteReader.run(i++, b & 0xFF); + } + } + } + for (; i < length; i++) { + byteReader.run(i, is.readByte() & 0xFF); + } + } + } else if (reader instanceof NBTStreamer.LazyReader) { + reader.accept(length, is); + } else { + for (int i = 0; i < length; i++) { + reader.accept(i, is.readByte()); + } + } + return; + case NBTConstants.TYPE_LIST: + int childType = is.readByte(); + if (childType == NBTConstants.TYPE_LIST) { + childType = NBTConstants.TYPE_COMPOUND; + } + length = is.readInt(); + reader = getReader.apply(node + ".?"); + if (reader != null) { + reader.accept(length, childType); + } + node += ".#"; + reader = getReader.apply(node); + depth++; + if (reader == null) { + for (int i = 0; i < length; ++i) { + readTagPaylodLazy(childType, depth, node, getReader); + } + return; + } + for (int i = 0; i < length; ++i) { + reader.accept(i, readTagPayload(childType, depth)); + } + return; + case NBTConstants.TYPE_COMPOUND: + depth++; + // 3 + for (int i = 0; ; i++) { + childType = is.readByte(); + if (childType == NBTConstants.TYPE_END) { + return; + } + String name = readNamedTagName(childType); + String childNode = node + "." + name; + reader = getReader.apply(childNode); + if (reader == null) { + readTagPaylodLazy(childType, depth, childNode, getReader); + continue; + } + reader.accept(i, readTagPaylodRaw(childType, depth)); + } + case NBTConstants.TYPE_INT_ARRAY: { + length = is.readInt(); + reader = getReader.apply(node + ".?"); + if (reader != null) { + reader.accept(length, NBTConstants.TYPE_INT); + } + reader = getReader.apply(node + ".#"); + if (reader == null) { + is.skipBytes(length << 2); + return; + } + if (reader instanceof NBTStreamer.ByteReader) { + NBTStreamer.ByteReader byteReader = (NBTStreamer.ByteReader) reader; + for (int i = 0; i < length; i++) { + byteReader.run(i, is.readInt()); + } + } else if (reader instanceof NBTStreamer.LazyReader) { + reader.accept(length, is); + } else { + for (int i = 0; i < length; i++) { + reader.accept(i, is.readInt()); + } + } + return; + } + case NBTConstants.TYPE_LONG_ARRAY: { + length = is.readInt(); + reader = getReader.apply(node + ".?"); + if (reader != null) { + reader.accept(length, NBTConstants.TYPE_LONG); + } + reader = getReader.apply(node + ".#"); + if (reader == null) { + is.skipBytes(length << 3); + return; + } + if (reader instanceof NBTStreamer.LongReader) { + NBTStreamer.LongReader longReader = (NBTStreamer.LongReader) reader; + for (int i = 0; i < length; i++) { + longReader.run(i, is.readLong()); + } + } else if (reader instanceof NBTStreamer.LazyReader) { + reader.accept(length, is); + } else { + for (int i = 0; i < length; i++) { + reader.accept(i, is.readLong()); + } + } + return; + } + + default: + throw new IOException("Invalid tag type: " + type + "."); + } + } + + public static int getSize(int type) { + switch (type) { + default: + case NBTConstants.TYPE_END: + case NBTConstants.TYPE_BYTE: + return 1; + case NBTConstants.TYPE_BYTE_ARRAY: + case NBTConstants.TYPE_STRING: + case NBTConstants.TYPE_LIST: + case NBTConstants.TYPE_COMPOUND: + case NBTConstants.TYPE_INT_ARRAY: + case NBTConstants.TYPE_LONG_ARRAY: + case NBTConstants.TYPE_SHORT: + return 2; + case NBTConstants.TYPE_FLOAT: + case NBTConstants.TYPE_INT: + return 4; + case NBTConstants.TYPE_DOUBLE: + case NBTConstants.TYPE_LONG: + return 8; + } + } + + private Object readTagPaylodRaw(int type, int depth) throws IOException { + switch (type) { + case NBTConstants.TYPE_END: + if (depth == 0) { + throw new IOException( + "TAG_End found without a TAG_Compound/TAG_List tag preceding it."); + } else { + return null; + } + case NBTConstants.TYPE_BYTE: + return (is.readByte()); + case NBTConstants.TYPE_SHORT: + return (is.readShort()); + case NBTConstants.TYPE_INT: + return (is.readInt()); + case NBTConstants.TYPE_LONG: + return (is.readLong()); + case NBTConstants.TYPE_FLOAT: + return (is.readFloat()); + case NBTConstants.TYPE_DOUBLE: + return (is.readDouble()); + case NBTConstants.TYPE_BYTE_ARRAY: + int length = is.readInt(); + byte[] bytes = new byte[length]; + is.readFully(bytes); + return (bytes); + case NBTConstants.TYPE_STRING: + length = is.readShort(); + bytes = new byte[length]; + is.readFully(bytes); + return (new String(bytes, NBTConstants.CHARSET)); + case NBTConstants.TYPE_LIST: + int childType = is.readByte(); + if (childType == NBTConstants.TYPE_LIST) { + childType = NBTConstants.TYPE_COMPOUND; + } + length = is.readInt(); + List tagList = new ArrayList<>(); + for (int i = 0; i < length; ++i) { + Tag tag = readTagPayload(childType, depth + 1); + if (tag instanceof EndTag) { + throw new IOException("TAG_End not permitted in a list."); + } + tagList.add(tag); + } + return (tagList); + case NBTConstants.TYPE_COMPOUND: + Map tagMap = new HashMap<>(); + while (true) { + NamedTag namedTag = readNamedTag(depth + 1); + Tag tag = namedTag.getTag(); + if (tag instanceof EndTag) { + break; + } else { + tagMap.put(namedTag.getName(), tag); + } + } + return (tagMap); + case NBTConstants.TYPE_INT_ARRAY: { + length = is.readInt(); + int[] data = new int[length]; + if (buf == null) { + buf = new byte[1024]; + } + int index = 0; + while (length > 0) { + int toRead = Math.min(length << 2, buf.length); + is.readFully(buf, 0, toRead); + for (int i = 0; i < toRead; i += 4, index++) { + data[index] = ((buf[i + 0] & 0xFF) << 24) + ((buf[i + 1] & 0xFF) << 16) + ((buf[i + 2] & 0xFF) << 8) + (buf[i + 3] & 0xFF); + } + length -= toRead; + } + return (data); + } + case NBTConstants.TYPE_LONG_ARRAY: { + length = is.readInt(); + long[] data = new long[length]; + if (buf == null) { + buf = new byte[1024]; + } + int index = 0; + while (length > 0) { + int toRead = Math.min(length << 3, buf.length); + is.readFully(buf, 0, toRead); + for (int i = 0; i < toRead; i += 8, index++) { + data[index] = (((long) buf[i] << 56) | ((long) (buf[i + 1] & 255) << 48) | ((long) (buf[i + 2] & 255) << 40) | ((long) (buf[i + 3] & 255) << 32) | ((long) (buf[i + 4] & 255) << 24) | ((buf[i + 5] & 255) << 16) | ((buf[i + 6] & 255) << 8) | (buf[i + 7] & 255)); + } + length -= toRead; + } + return (data); + } + default: + throw new IOException("Invalid tag type: " + type + "."); + } + } + + public Object readDataPayload(int type, int depth) throws IOException { + switch (type) { + case NBTConstants.TYPE_END: + if (depth == 0) { + throw new IOException( + "TAG_End found without a TAG_Compound/TAG_List tag preceding it."); + } else { + return null; + } + case NBTConstants.TYPE_BYTE: + return is.readByte(); + case NBTConstants.TYPE_SHORT: + return is.readShort(); + case NBTConstants.TYPE_INT: + return is.readInt(); + case NBTConstants.TYPE_LONG: + return is.readLong(); + case NBTConstants.TYPE_FLOAT: + return is.readFloat(); + case NBTConstants.TYPE_DOUBLE: + return is.readDouble(); + case NBTConstants.TYPE_BYTE_ARRAY: + int length = is.readInt(); + byte[] bytes = new byte[length]; + is.readFully(bytes); + return bytes; + case NBTConstants.TYPE_STRING: + length = is.readShort(); + bytes = new byte[length]; + is.readFully(bytes); + return new String(bytes, NBTConstants.CHARSET); + case NBTConstants.TYPE_LIST: + int childType = is.readByte(); + if (childType == NBTConstants.TYPE_LIST) { + childType = NBTConstants.TYPE_COMPOUND; + } + length = is.readInt(); + ArrayList list = new ArrayList<>(); + for (int i = 0; i < length; ++i) { + Object obj = readDataPayload(childType, depth + 1); + if (obj == null) { + throw new IOException("TAG_End not permitted in a list."); + } + list.add(obj); + } + + return list; + case NBTConstants.TYPE_COMPOUND: + Map map = new HashMap<>(); + while (true) { + int newType = is.readByte(); + String name = readNamedTagName(newType); + Object data = readDataPayload(newType, depth + 1); + if (data == null) { + break; + } else { + map.put(name, data); + } + } + + return map; + case NBTConstants.TYPE_INT_ARRAY: { + length = is.readInt(); + int[] data = new int[length]; + for (int i = 0; i < length; i++) { + data[i] = is.readInt(); + } + return data; + } + case NBTConstants.TYPE_LONG_ARRAY: { + length = is.readInt(); + long[] data = new long[length]; + for (int i = 0; i < length; i++) { + data[i] = is.readLong(); + } + return data; + } + default: + throw new IOException("Invalid tag type: " + type + "."); + } + } + + /** + * Reads the payload of a tag given the type. + * + * @param type the type + * @param depth the depth + * @return the tag + * @throws IOException if an I/O error occurs. + */ + public Tag readTagPayload(int type, int depth) throws IOException { + switch (type) { + case NBTConstants.TYPE_END: + if (depth == 0) { + throw new IOException( + "TAG_End found without a TAG_Compound/TAG_List tag preceding it."); + } else { + return new EndTag(); + } + case NBTConstants.TYPE_BYTE: + return new ByteTag(is.readByte()); + case NBTConstants.TYPE_SHORT: + return new ShortTag(is.readShort()); + case NBTConstants.TYPE_INT: + return new IntTag(is.readInt()); + case NBTConstants.TYPE_LONG: + return new LongTag(is.readLong()); + case NBTConstants.TYPE_FLOAT: + return new FloatTag(is.readFloat()); + case NBTConstants.TYPE_DOUBLE: + return new DoubleTag(is.readDouble()); + case NBTConstants.TYPE_BYTE_ARRAY: + int length = is.readInt(); + byte[] bytes = new byte[length]; + is.readFully(bytes); + return new ByteArrayTag(bytes); + case NBTConstants.TYPE_STRING: + length = is.readShort(); + bytes = new byte[length]; + is.readFully(bytes); + return new StringTag(new String(bytes, NBTConstants.CHARSET)); + case NBTConstants.TYPE_LIST: + int childType = is.readByte(); + if (childType == NBTConstants.TYPE_LIST) { + childType = NBTConstants.TYPE_COMPOUND; + } + length = is.readInt(); + List tagList = new ArrayList<>(); + for (int i = 0; i < length; ++i) { + Tag tag = readTagPayload(childType, depth + 1); + if (tag instanceof EndTag) { + throw new IOException("TAG_End not permitted in a list."); + } + tagList.add(tag); + } + + return new ListTag(NBTUtils.getTypeClass(childType), tagList); + case NBTConstants.TYPE_COMPOUND: + Map tagMap = new HashMap<>(); + while (true) { + NamedTag namedTag = readNamedTag(depth + 1); + Tag tag = namedTag.getTag(); + if (tag instanceof EndTag) { + break; + } else { + tagMap.put(namedTag.getName(), tag); + } + } + + return new CompoundTag(tagMap); + case NBTConstants.TYPE_INT_ARRAY: { + length = is.readInt(); + int[] data = new int[length]; + for (int i = 0; i < length; i++) { + data[i] = is.readInt(); + } + return new IntArrayTag(data); + } + case NBTConstants.TYPE_LONG_ARRAY: { + length = is.readInt(); + long[] data = new long[length]; + for (int i = 0; i < length; i++) { + data[i] = is.readLong(); + } + return new LongArrayTag(data); + } + default: + throw new IOException("Invalid tag type: " + type + "."); + } + } + + @Override + public void close() throws IOException { + if (is instanceof AutoCloseable) { + try { + ((AutoCloseable) is).close(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/jnbt/NBTUtils.java b/worldedit-core/src/main/java/com/sk89q/jnbt/NBTUtils.java index e44262911..d35626ed9 100644 --- a/worldedit-core/src/main/java/com/sk89q/jnbt/NBTUtils.java +++ b/worldedit-core/src/main/java/com/sk89q/jnbt/NBTUtils.java @@ -21,7 +21,7 @@ package com.sk89q.jnbt; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.world.storage.InvalidFormatException; import java.util.Map; @@ -167,9 +167,9 @@ public final class NBTUtils { * @param listTag the list tag * @return a vector */ - public static Vector toVector(ListTag listTag) { + public static Vector3 toVector(ListTag listTag) { checkNotNull(listTag); - return new Vector(listTag.asDouble(0), listTag.asDouble(1), listTag.asDouble(2)); + return Vector3.at(listTag.asDouble(0), listTag.asDouble(1), listTag.asDouble(2)); } /** 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 d0e5fc0c7..0742c9ceb 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 @@ -19,9 +19,10 @@ package com.sk89q.util.yaml; -import com.sk89q.worldedit.BlockVector2D; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector2; +import com.sk89q.worldedit.math.Vector3; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -111,13 +112,32 @@ public class YAMLNode { * @return the new object */ private Object prepareSerialization(Object value) { - if (value instanceof Vector) { + if (value instanceof Vector3) { Map out = new LinkedHashMap<>(); - Vector vec = (Vector) value; + Vector3 vec = (Vector3) value; out.put("x", vec.getX()); out.put("y", vec.getY()); out.put("z", vec.getZ()); return out; + } else if (value instanceof BlockVector3) { + Map out = new LinkedHashMap<>(); + BlockVector3 vec = (BlockVector3) value; + out.put("x", vec.getBlockX()); + out.put("y", vec.getBlockY()); + out.put("z", vec.getBlockZ()); + return out; + } else if (value instanceof Vector2) { + Map out = new LinkedHashMap<>(); + Vector2 vec = (Vector2) value; + out.put("x", vec.getX()); + out.put("z", vec.getZ()); + return out; + } else if (value instanceof BlockVector2) { + Map out = new LinkedHashMap<>(); + BlockVector2 vec = (BlockVector2) value; + out.put("x", vec.getBlockX()); + out.put("z", vec.getBlockZ()); + return out; } return value; @@ -201,7 +221,7 @@ public class YAMLNode { * @param path path to node (dot notation) * @return string or default */ - public Vector getVector(String path) { + public Vector3 getVector(String path) { YAMLNode o = getNode(path); if (o == null) { return null; @@ -215,7 +235,7 @@ public class YAMLNode { return null; } - return new Vector(x, y, z); + return Vector3.at(x, y, z); } /** @@ -226,7 +246,7 @@ public class YAMLNode { * @param path path to node (dot notation) * @return string or default */ - public Vector2D getVector2d(String path) { + public Vector2 getVector2(String path) { YAMLNode o = getNode(path); if (o == null) { return null; @@ -239,7 +259,7 @@ public class YAMLNode { return null; } - return new Vector2D(x, z); + return Vector2.at(x, z); } /** @@ -251,8 +271,8 @@ public class YAMLNode { * @param def default value * @return string or default */ - public Vector getVector(String path, Vector def) { - Vector v = getVector(path); + public Vector3 getVector(String path, Vector3 def) { + Vector3 v = getVector(path); if (v == null) { if (writeDefaults) setProperty(path, def); return def; @@ -558,9 +578,9 @@ public class YAMLNode { * @param def default value or null for an empty list as default * @return list of integers */ - public List getVectorList(String path, List def) { + public List getVectorList(String path, List def) { List raw = getNodeList(path, null); - List list = new ArrayList<>(); + List list = new ArrayList<>(); for (YAMLNode o : raw) { Double x = o.getDouble("x"); @@ -571,7 +591,7 @@ public class YAMLNode { continue; } - list.add(new Vector(x, y, z)); + list.add(Vector3.at(x, y, z)); } return list; @@ -588,10 +608,10 @@ public class YAMLNode { * @param def default value or null for an empty list as default * @return list of integers */ - public List getVector2dList(String path, List def) { + public List getVector2List(String path, List def) { List raw = getNodeList(path, null); - List list = new ArrayList<>(); + List list = new ArrayList<>(); for (YAMLNode o : raw) { Double x = o.getDouble("x"); @@ -601,7 +621,7 @@ public class YAMLNode { continue; } - list.add(new Vector2D(x, z)); + list.add(Vector2.at(x, z)); } return list; @@ -618,10 +638,10 @@ public class YAMLNode { * @param def default value or null for an empty list as default * @return list of integers */ - public List getBlockVector2dList(String path, List def) { + public List getBlockVector2List(String path, List def) { List raw = getNodeList(path, null); - List list = new ArrayList<>(); + List list = new ArrayList<>(); for (YAMLNode o : raw) { Double x = o.getDouble("x"); @@ -631,7 +651,7 @@ public class YAMLNode { continue; } - list.add(new BlockVector2D(x, z)); + list.add(BlockVector2.at(x, z)); } return list; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/BlockVector.java b/worldedit-core/src/main/java/com/sk89q/worldedit/BlockVector.java deleted file mode 100644 index 04b600967..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/BlockVector.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit; - -import java.io.IOException; - -/** - * Extension of {@code Vector} that that compares with other instances - * using integer components. - */ -public class BlockVector extends Vector { - - public static final BlockVector ZERO = new BlockVector(0, 0, 0); - public static final BlockVector UNIT_X = new BlockVector(1, 0, 0); - public static final BlockVector UNIT_Y = new BlockVector(0, 1, 0); - public static final BlockVector UNIT_Z = new BlockVector(0, 0, 1); - public static final BlockVector ONE = new BlockVector(1, 1, 1); - - /** - * Construct an instance as a copy of another instance. - * - * @param position the other position - */ - public BlockVector(Vector position) { - this(position.getBlockX(), position.getBlockY(), position.getBlockZ()); - } - - /** - * Construct a new instance. - * - * @param x the X coordinate - * @param y the Y coordinate - * @param z the Z coordinate - */ - public BlockVector(int x, int y, int z) { - super(x, y, z); - } - - /** - * Construct a new instance. - * - * @param x the X coordinate - * @param y the Y coordinate - * @param z the Z coordinate - */ - public BlockVector(float x, float y, float z) { - this((int) x, (int) y, (int) z); - } - - /** - * Construct a new instance. - * - * @param x the X coordinate - * @param y the Y coordinate - * @param z the Z coordinate - */ - public BlockVector(double x, double y, double z) { - this((int) x, (int) y, (int) z); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Vector)) { - return false; - } - Vector other = (Vector) obj; - return (int) other.getX() == (int) this.getX() && (int) other.getY() == (int) this.getY() - && (int) other.getZ() == (int) this.getZ(); - - } - - public boolean equals(BlockVector obj) { - return obj.getBlockX() == this.getBlockX() && obj.getBlockY() == this.getBlockY() && obj.getBlockZ() == this.getBlockZ(); - } - - @Override - public int hashCode() { - return ((int) getX() ^ ((int) getZ() << 16)) ^ ((int) getY() << 30); - } - - private void writeObject(java.io.ObjectOutputStream stream) throws IOException { - if (!(this instanceof MutableBlockVector)) { - stream.writeInt(getBlockX()); - stream.writeInt(getBlockY()); - stream.writeInt(getBlockZ()); - } - } - - private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { - if (this instanceof MutableBlockVector) return; - this.setComponents(stream.readInt(), stream.readInt(), stream.readInt()); - } - - @Override - public BlockVector toBlockVector() { - return this; - } - - @Override - public String toString() { - return "(" + getBlockX() + ", " + getBlockY() + ", " + getBlockZ() + ")"; - } -} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/BlockVector2D.java b/worldedit-core/src/main/java/com/sk89q/worldedit/BlockVector2D.java deleted file mode 100644 index cdf0cb36a..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/BlockVector2D.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit; - -/** - * Extension of {@code Vector2D} that that compares with other instances - * using integer components. - */ -public class BlockVector2D extends Vector2D { - - public static final BlockVector2D ZERO = new BlockVector2D(0, 0); - public static final BlockVector2D UNIT_X = new BlockVector2D(1, 0); - public static final BlockVector2D UNIT_Z = new BlockVector2D(0, 1); - public static final BlockVector2D ONE = new BlockVector2D(1, 1); - - /** - * Construct an instance from another instance. - * - * @param position the position to copy - */ - public BlockVector2D(Vector2D position) { - this(position.getBlockX(), position.getBlockZ()); - } - - /** - * Construct a new instance. - * - * @param x the X coordinate - * @param z the Z coordinate - */ - public BlockVector2D(int x, int z) { - super(x, z); - } - - /** - * Construct a new instance. - * - * @param x the X coordinate - * @param z the Z coordinate - */ - public BlockVector2D(float x, float z) { - this((int) x, (int) z); - } - - /** - * Construct a new instance. - * - * @param x the X coordinate - * @param z the Z coordinate - */ - public BlockVector2D(double x, double z) { - this((int) x, (int) z); - } - - @Override - public int hashCode() { - return ((int) x << 16) ^ (int) z; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Vector2D)) { - return false; - } - - Vector2D other = (Vector2D) obj; - return (int) other.x == (int) this.x && (int) other.z == (int) this.z; - - } - - @Override - public BlockVector2D toBlockVector2D() { - return this; - } - -} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/CuboidClipboard.java b/worldedit-core/src/main/java/com/sk89q/worldedit/CuboidClipboard.java index 930f0763a..bb87f2c5d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/CuboidClipboard.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/CuboidClipboard.java @@ -21,22 +21,25 @@ package com.sk89q.worldedit; import com.boydti.fawe.object.schematic.Schematic; import com.boydti.fawe.util.MainUtil; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.command.ClipboardCommands; import com.sk89q.worldedit.command.FlattenedClipboardTransform; import com.sk89q.worldedit.command.SchematicCommands; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operations; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Countable; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.world.DataException; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; @@ -85,18 +88,18 @@ public class CuboidClipboard { private BlockArrayClipboard clipboard; private AffineTransform transform; - public Vector size; + public BlockVector3 size; /** * Constructs the clipboard. * * @param size the dimensions of the clipboard (should be at least 1 on every dimension) */ - public CuboidClipboard(Vector size) { + public CuboidClipboard(BlockVector3 size) { checkNotNull(size); MainUtil.warnDeprecated(BlockArrayClipboard.class, ClipboardFormat.class); this.size = size; - this.clipboard = this.init(Vector.ZERO, Vector.ZERO); + this.clipboard = this.init(BlockVector3.ZERO, BlockVector3.ZERO); } public CuboidClipboard(BlockArrayClipboard clipboard) { @@ -111,12 +114,12 @@ public class CuboidClipboard { * @param origin the origin point where the copy was made, which must be the * {@link CuboidRegion#getMinimumPoint()} relative to the copy */ - public CuboidClipboard(Vector size, Vector origin) { + public CuboidClipboard(BlockVector3 size, BlockVector3 origin) { checkNotNull(size); checkNotNull(origin); MainUtil.warnDeprecated(BlockArrayClipboard.class, ClipboardFormat.class); this.size = size; - this.clipboard = init(Vector.ZERO, origin); + this.clipboard = init(BlockVector3.ZERO, origin); } /** @@ -127,7 +130,7 @@ public class CuboidClipboard { * {@link CuboidRegion#getMinimumPoint()} relative to the copy * @param offset the offset from the minimum point of the copy where the user was */ - public CuboidClipboard(Vector size, Vector origin, Vector offset) { + public CuboidClipboard(BlockVector3 size, BlockVector3 origin, BlockVector3 offset) { checkNotNull(size); checkNotNull(origin); checkNotNull(offset); @@ -138,40 +141,41 @@ public class CuboidClipboard { /* ------------------------------------------------------------------------------------------------------------- */ - private BlockArrayClipboard init(Vector offset, Vector min) { - Vector origin = min.subtract(offset); - CuboidRegion region = new CuboidRegion(min, min.add(size).subtract(Vector.ONE)); + private BlockArrayClipboard init(BlockVector3 offset, BlockVector3 min) { + BlockVector3 origin = min.subtract(offset); + CuboidRegion region = new CuboidRegion(min, min.add(size).subtract(BlockVector3.ONE)); BlockArrayClipboard clipboard = new BlockArrayClipboard(region); clipboard.setOrigin(origin); return clipboard; } private BaseBlock adapt(BlockState state) { - if (state instanceof BaseBlock) return (BaseBlock) state; +// if (state instanceof BaseBlock) return (BaseBlock) state; return new BaseBlock(state); } /* ------------------------------------------------------------------------------------------------------------- */ - public BaseBlock getBlock(Vector position) { + public BaseBlock getBlock(BlockVector3 position) { return getBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ()); } public BaseBlock getBlock(int x, int y, int z) { - return adapt(clipboard.IMP.getBlock(x, y, z)); +// return adapt(clipboard.IMP.getBlock(x, y, z)); + return clipboard.IMP.getBlock(x, y, z); } - public BaseBlock getLazyBlock(Vector position) { + public BaseBlock getLazyBlock(BlockVector3 position) { return getBlock(position); } - public void setBlock(Vector location, BaseBlock block) { + public void setBlock(BlockVector3 location, BaseBlock block) { setBlock(location.getBlockX(), location.getBlockY(), location.getBlockZ(), block); } public boolean setBlock(int x, int y, int z, BaseBlock block) { - return setBlock(x, y, z, (BlockState) block); + return setBlock(x, y, z, block); } public boolean setBlock(int x, int y, int z, BlockState block) { @@ -235,7 +239,7 @@ public class CuboidClipboard { public void flip(FlipDirection dir, boolean aroundPlayer) { checkNotNull(dir); Direction direction = dir.direction; - AffineTransform newTransform = new AffineTransform().scale(direction.toVector().positive().multiply(-2).add(1, 1, 1)); + AffineTransform newTransform = new AffineTransform().scale(direction.toVector().abs().multiply(-2).add(1, 1, 1)); this.transform = transform == null ? newTransform : newTransform.combine(transform); } @@ -248,7 +252,7 @@ public class CuboidClipboard { for (int x = 0; x < size.getBlockX(); ++x) { for (int y = 0; y < size.getBlockY(); ++y) { for (int z = 0; z < size.getBlockZ(); ++z) { - setBlock(x, y, z, editSession.getBlock(new Vector(x, y, z).add(getOrigin()))); + setBlock(x, y, z, editSession.getBlock(BlockVector3.at(x, y, z).add(getOrigin()))); } } } @@ -264,11 +268,11 @@ public class CuboidClipboard { for (int x = 0; x < size.getBlockX(); ++x) { for (int y = 0; y < size.getBlockY(); ++y) { for (int z = 0; z < size.getBlockZ(); ++z) { - final Vector pt = new Vector(x, y, z).add(getOrigin()); + final BlockVector3 pt = BlockVector3.at(x, y, z).add(getOrigin()); if (region.contains(pt)) { setBlock(x, y, z, editSession.getBlock(pt)); } else { - setBlock(x, y, z, null); + setBlock(x, y, z, (BlockState)null); } } } @@ -288,7 +292,7 @@ public class CuboidClipboard { * @param noAir true to not copy air blocks in the source * @throws MaxChangedBlocksException thrown if too many blocks were changed */ - public void paste(EditSession editSession, Vector newOrigin, boolean noAir) throws MaxChangedBlocksException { + public void paste(EditSession editSession, BlockVector3 newOrigin, boolean noAir) throws MaxChangedBlocksException { paste(editSession, newOrigin, noAir, false); } @@ -306,7 +310,7 @@ public class CuboidClipboard { * @param entities true to copy entities * @throws MaxChangedBlocksException thrown if too many blocks were changed */ - public void paste(EditSession editSession, Vector newOrigin, boolean noAir, boolean entities) throws MaxChangedBlocksException { + public void paste(EditSession editSession, BlockVector3 newOrigin, boolean noAir, boolean entities) throws MaxChangedBlocksException { new Schematic(clipboard).paste(editSession, newOrigin, false, !noAir, entities, transform); editSession.flushQueue(); } @@ -324,7 +328,7 @@ public class CuboidClipboard { * @param noAir true to not copy air blocks in the source * @throws MaxChangedBlocksException thrown if too many blocks were changed */ - public void place(EditSession editSession, Vector newOrigin, boolean noAir) throws MaxChangedBlocksException { + public void place(EditSession editSession, BlockVector3 newOrigin, boolean noAir) throws MaxChangedBlocksException { paste(editSession, newOrigin, noAir, false); } @@ -339,7 +343,7 @@ public class CuboidClipboard { * @deprecated use {@link #getBlock(Vector)} instead */ @Deprecated - public BaseBlock getPoint(Vector position) throws ArrayIndexOutOfBoundsException { + public BaseBlock getPoint(BlockVector3 position) throws ArrayIndexOutOfBoundsException { final BaseBlock block = getBlock(position); if (block == null) { return new BaseBlock(BlockTypes.AIR); @@ -355,7 +359,7 @@ public class CuboidClipboard { * * @return the origin */ - public Vector getOrigin() { + public BlockVector3 getOrigin() { return clipboard.getMinimumPoint(); } @@ -366,14 +370,14 @@ public class CuboidClipboard { * * @param origin the origin to set */ - public void setOrigin(Vector origin) { + public void setOrigin(BlockVector3 origin) { checkNotNull(origin); setOriginAndOffset(getOffset(), origin); } - public void setOriginAndOffset(Vector offset, Vector min) { - Vector origin = min.subtract(offset); - CuboidRegion region = new CuboidRegion(min, min.add(size).subtract(Vector.ONE)); + public void setOriginAndOffset(BlockVector3 offset, BlockVector3 min) { + BlockVector3 origin = min.subtract(offset); + CuboidRegion region = new CuboidRegion(min, min.add(size).subtract(BlockVector3.ONE)); clipboard.setRegion(region); clipboard.setOrigin(origin); } @@ -386,10 +390,10 @@ public class CuboidClipboard { * * @return the offset the offset */ - public Vector getOffset() { - Vector min = clipboard.getMinimumPoint(); - Vector origin = clipboard.getOrigin(); - Vector offset = min.subtract(origin); + public BlockVector3 getOffset() { + BlockVector3 min = clipboard.getMinimumPoint(); + BlockVector3 origin = clipboard.getOrigin(); + BlockVector3 offset = min.subtract(origin); return offset; } @@ -401,7 +405,7 @@ public class CuboidClipboard { * * @param offset the new offset */ - public void setOffset(Vector offset) { + public void setOffset(BlockVector3 offset) { checkNotNull(offset); setOriginAndOffset(offset, getOrigin()); } @@ -411,7 +415,7 @@ public class CuboidClipboard { * * @return the dimensions, where (1, 1, 1) is 1 wide, 1 across, 1 deep */ - public Vector getSize() { + public BlockVector3 getSize() { return size; } @@ -433,7 +437,7 @@ public class CuboidClipboard { Operations.completeLegacy(result.copyTo(target)); this.clipboard = target; } - new Schematic(clipboard).save(path, ClipboardFormat.SPONGE_SCHEMATIC); + new Schematic(clipboard).save(path, BuiltInClipboardFormat.SPONGE_SCHEMATIC); } /** @@ -448,7 +452,7 @@ public class CuboidClipboard { @Deprecated public static CuboidClipboard loadSchematic(File path) throws DataException, IOException { checkNotNull(path); - return new CuboidClipboard((Vector) ClipboardFormat.SCHEMATIC.load(path).getClipboard()); + return new CuboidClipboard((BlockVector3) BuiltInClipboardFormat.MCEDIT_SCHEMATIC.load(path).getClipboard()); } /** @@ -476,7 +480,7 @@ public class CuboidClipboard { List> distribution = new ArrayList<>(); List> distr = clipboard.getBlockDistributionWithData(clipboard.getRegion()); for (Countable item : distr) { - distribution.add(new Countable<>(new BaseBlock(item.getID()), item.getAmount())); + distribution.add(new Countable<>(item.getID().toBaseBlock(), item.getAmount())); } return distribution; } 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 e6ca93f9a..452fbe70d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/EditSession.java @@ -43,9 +43,6 @@ import com.boydti.fawe.util.*; import com.boydti.fawe.wrappers.WorldWrapper; import com.google.common.base.Supplier; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.function.mask.*; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; @@ -63,8 +60,10 @@ import com.sk89q.worldedit.function.RegionMaskingFilter; import com.sk89q.worldedit.function.block.BlockReplace; import com.sk89q.worldedit.function.block.Naturalizer; import com.sk89q.worldedit.function.generator.GardenPatchGenerator; +import com.sk89q.worldedit.function.mask.*; import com.sk89q.worldedit.function.operation.ChangeSetExecutor; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; +import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; @@ -77,6 +76,7 @@ import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.ExpressionException; import com.sk89q.worldedit.internal.expression.runtime.EvaluationException; import com.sk89q.worldedit.internal.expression.runtime.RValue; +import com.sk89q.worldedit.math.*; import com.sk89q.worldedit.math.interpolation.KochanekBartelsInterpolation; import com.sk89q.worldedit.math.interpolation.Node; import com.sk89q.worldedit.math.noise.RandomNoise; @@ -87,41 +87,23 @@ import com.sk89q.worldedit.regions.shape.ArbitraryShape; import com.sk89q.worldedit.regions.shape.RegionShape; import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment; import com.sk89q.worldedit.util.Countable; +import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.eventbus.EventBus; import com.sk89q.worldedit.world.SimpleWorld; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.world.block.*; import com.sk89q.worldedit.world.weather.WeatherType; -import com.sk89q.worldedit.world.block.BlockCategories; -import com.sk89q.worldedit.world.block.BlockState; -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.registry.LegacyMapper; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -import java.util.*; -import java.util.concurrent.ThreadLocalRandom; import javax.annotation.Nonnull; import javax.annotation.Nullable; - +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import static com.sk89q.worldedit.regions.Regions.asFlatRegion; -import static com.sk89q.worldedit.regions.Regions.maximumBlockY; -import static com.sk89q.worldedit.regions.Regions.minimumBlockY; +import static com.sk89q.worldedit.regions.Regions.*; /** * An {@link Extent} that handles history, {@link BlockBag}s, change limits, @@ -131,8 +113,9 @@ import static com.sk89q.worldedit.regions.Regions.minimumBlockY; * {@link Extent}s that are chained together. For example, history is logged * using the {@link ChangeSetExtent}.

*/ -public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, SimpleWorld { +public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, SimpleWorld, AutoCloseable { /** + * Used by {@link EditSession#setBlock(BlockVector3, BlockStateHolder, Stage)} to * determine which {@link Extent}s should be bypassed. */ public enum Stage { @@ -153,7 +136,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, private FawePlayer player; private FaweChangeSet changeTask; - private MutableBlockVector mutable = new MutableBlockVector(); + private MutableBlockVector3 mutablebv = new MutableBlockVector3(); private int changes = 0; private BlockBag blockBag; @@ -163,13 +146,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, public static final UUID CONSOLE = UUID.fromString("1-1-3-3-7"); public static final BaseBiome nullBiome = new BaseBiome(0); public static final BlockState nullBlock = BlockTypes.AIR.getDefaultState(); - private static final Vector[] recurseDirections = { - PlayerDirection.NORTH.vector(), - PlayerDirection.EAST.vector(), - PlayerDirection.SOUTH.vector(), - PlayerDirection.WEST.vector(), - PlayerDirection.UP.vector(), - PlayerDirection.DOWN.vector(),}; @Deprecated public EditSession(@Nonnull World world, @Nullable FaweQueue queue, @Nullable FawePlayer player, @Nullable FaweLimit limit, @Nullable FaweChangeSet changeSet, @Nullable RegionWrapper[] allowedRegions, @Nullable Boolean autoQueue, @Nullable Boolean fastmode, @Nullable Boolean checkMemory, @Nullable Boolean combineStages, @Nullable BlockBag blockBag, @Nullable EventBus bus, @Nullable EditSessionEvent event) { @@ -364,6 +340,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, this(WorldEdit.getInstance().getEventBus(), world, maxBlocks, blockBag, new EditSessionEvent(world, null, maxBlocks, null)); } + private Mask oldMask; + /** * Construct the object with a maximum number of blocks and a block bag. * @@ -527,6 +505,9 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return new NullExtent(extent, BBC.WORLDEDIT_CANCEL_REASON_MANUAL); } final Extent toReturn = event.getExtent(); + if(toReturn instanceof com.sk89q.worldedit.extent.NullExtent) { + return new NullExtent(toReturn, null); + } if (!(toReturn instanceof AbstractDelegateExtent)) { Fawe.debug("Extent " + toReturn + " must be AbstractDelegateExtent"); return extent; @@ -561,7 +542,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return the world */ public World getWorld() { - return this.world; + return world; } /** @@ -630,6 +611,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * * @return whether the queue is enabled */ + @Deprecated public boolean isQueueEnabled() { return true; } @@ -637,12 +619,14 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, /** * Queue certain types of block for better reproduction of those blocks. */ + @Deprecated public void enableQueue() { } /** * Disable the queue. This will close the queue. */ + @Deprecated public void disableQueue() { if (this.isQueueEnabled()) { this.flushQueue(); @@ -908,12 +892,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } @Override - public BaseBiome getBiome(final Vector2D position) { + public BaseBiome getBiome(final BlockVector2 position) { return this.extent.getBiome(position); } @Override - public boolean setBiome(final Vector2D position, final BaseBiome biome) { + public boolean setBiome(final BlockVector2 position, final BaseBiome biome) { this.changes++; return this.extent.setBiome(position, biome); } @@ -950,7 +934,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } @Override - public BlockState getLazyBlock(final Vector position) { + public BlockState getLazyBlock(final BlockVector3 position) { return getLazyBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ()); } @@ -963,8 +947,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } @Override - public BlockState getBlock(final Vector position) { - return getLazyBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ()); + public BlockState getBlock(BlockVector3 position) { + return world.getBlock(position); + } + + @Override + public BaseBlock getFullBlock(BlockVector3 position) { + return world.getFullBlock(position); } /** @@ -972,13 +961,39 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * * @param position the position * @return the block type - * @deprecated Use {@link #getLazyBlock(Vector)} or {@link #getBlock(Vector)} + * @deprecated Use {@link #getLazyBlock(BlockVector3)} or {@link #getBlock(BlockVector3)} */ @Deprecated - public BlockType getBlockType(final Vector position) { + public BlockType getBlockType(final BlockVector3 position) { return getBlockType(position.getBlockX(), position.getBlockY(), position.getBlockZ()); } + public int getHighestTerrainBlock(int x, int z, int minY, int maxY) { + return getHighestTerrainBlock(x, z, minY, maxY, null); + } + + /** + * Returns the highest solid 'terrain' block. + * + * @param x the X coordinate + * @param z the Z coordinate + * @param minY minimal height + * @param maxY maximal height + * @param filter a mask of blocks to consider, or null to consider any solid (movement-blocking) block + * @return height of highest block found or 'minY' + */ + public int getHighestTerrainBlock(int x, int z, int minY, int maxY, Mask filter) { + for (int y = maxY; y >= minY; --y) { + BlockVector3 pt = BlockVector3.at(x, y, z); + if (filter == null + ? getBlock(pt).getBlockType().getMaterial().isMovementBlocker() + : filter.test(pt)) { + return y; + } + } + return minY; + } + public BlockType getBlockType(int x, int y, int z) { if (!limit.MAX_CHECKS()) { throw new FaweException(BBC.WORLDEDIT_CANCEL_REASON_MAX_CHECKS); @@ -996,7 +1011,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return whether the block changed * @throws WorldEditException thrown on a set error */ - public boolean setBlock(final Vector position, final BaseBlock block, final Stage stage) throws WorldEditException { + public > boolean setBlock(BlockVector3 position, B block, Stage stage) throws WorldEditException { this.changes++; switch (stage) { case BEFORE_HISTORY: @@ -1010,6 +1025,21 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, throw new RuntimeException("New enum entry added that is unhandled here"); } + /** + * Set a block, bypassing both history and block re-ordering. + * + * @param position the position to set the block at + * @param block the block + * @return whether the block changed + */ + public > boolean rawSetBlock(BlockVector3 position, B block) { + try { + return this.bypassAll.setBlock(position, block); + } catch (WorldEditException e) { + throw new RuntimeException("Unexpected exception", e); + } + } + /** * Set a block, bypassing history but still utilizing block re-ordering. * @@ -1017,17 +1047,16 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @param block the block * @return whether the block changed */ - public boolean smartSetBlock(final Vector position, final BlockStateHolder block) { - this.changes++; + public > boolean smartSetBlock(BlockVector3 position, B block) { try { - return this.bypassAll.setBlock(position, block); - } catch (final WorldEditException e) { + return setBlock(position, block, Stage.BEFORE_REORDER); + } catch (WorldEditException e) { throw new RuntimeException("Unexpected exception", e); } } @Override - public boolean setBlock(Vector position, BlockStateHolder block) throws MaxChangedBlocksException { + public > boolean setBlock(BlockVector3 position, B block) throws MaxChangedBlocksException { this.changes++; try { return this.extent.setBlock(position, block); @@ -1038,7 +1067,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } } - public boolean setBlock(int x, int y, int z, BlockStateHolder block) { + public > boolean setBlock(int x, int y, int z, B block) { this.changes++; try { return this.extent.setBlock(x, y, z, block); @@ -1050,35 +1079,15 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, public boolean setBlock(int x, int y, int z, Pattern pattern) { this.changes++; try { - mutable.setComponents(x, y, z); - return pattern.apply(extent, mutable, mutable); + BlockVector3 bv = mutablebv.setComponents(x, y, z); + return pattern.apply(extent, bv, bv); } catch (WorldEditException e) { throw new RuntimeException("Unexpected exception", e); } } - @Deprecated - public boolean setBlock(int x, int y, int z, com.sk89q.worldedit.patterns.Pattern pattern) { - return setBlock(x, y, z, (Pattern) pattern); - } - - @Deprecated - public boolean setBlock(Vector position, com.sk89q.worldedit.patterns.Pattern pattern) { - return setBlock(position, (Pattern) pattern); - } - - @Deprecated - public boolean setBlock(int x, int y, int z, BaseBlock block) { - return setBlock(x, y, z, (BlockState) block); - } - - @Deprecated - public boolean setBlock(Vector position, BaseBlock block) throws MaxChangedBlocksException { - return setBlock(position, (BlockState) block); - } - @SuppressWarnings("deprecation") - public boolean setBlock(final Vector position, final Pattern pattern) { + public boolean setBlock(final BlockVector3 position, final Pattern pattern) { this.changes++; try { return pattern.apply(this.extent, position, position); @@ -1088,7 +1097,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } @SuppressWarnings("deprecation") - public int setBlocks(final Set vset, final Pattern pattern) { + public int setBlocks(final Set vset, final Pattern pattern) { RegionVisitor visitor = new RegionVisitor(vset, new BlockReplace(extent, pattern), this); Operations.completeBlindly(visitor); changes += visitor.getAffected(); @@ -1105,7 +1114,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return whether a block was changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public boolean setChanceBlockIfAir(final Vector position, final BaseBlock block, final double probability) throws MaxChangedBlocksException { + public boolean setChanceBlockIfAir(final BlockVector3 position, final BaseBlock block, final double probability) throws MaxChangedBlocksException { return (ThreadLocalRandom.current().nextInt(65536) <= (probability * 65536)) && this.setBlockIfAir(position, block); } @@ -1119,9 +1128,16 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @deprecated Use your own method */ @Deprecated - public boolean setBlockIfAir(final Vector position, final BlockStateHolder block) throws MaxChangedBlocksException { + public boolean setBlockIfAir(final BlockVector3 position, final BlockStateHolder block) throws MaxChangedBlocksException { return this.getBlock(position).getBlockType().getMaterial().isAir() && this.setBlock(position, block); } +// private int setBlocks(Set vset, Pattern pattern) throws MaxChangedBlocksException { +// int affected = 0; +// for (BlockVector3 v : vset) { +// affected += setBlock(v, pattern) ? 1 : 0; +// } +// return affected; +// } @Override @Nullable @@ -1139,10 +1155,10 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @deprecated Get the change set with {@link #getChangeSet()} and add the change with that */ @Deprecated - public void rememberChange(final Vector position, final BaseBlock existing, final BaseBlock block) { + public void rememberChange(final BlockVector3 position, final BaseBlock existing, final BaseBlock block) { ChangeSet changeSet = getChangeSet(); if (changeSet != null) { - changeSet.add(new BlockChange(position.toBlockVector(), existing, block)); + changeSet.add(new BlockChange(position, existing, block)); } } @@ -1191,7 +1207,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return the number of changes */ public int size() { - return this.getBlockChangeCount(); + return getBlockChangeCount(); } public void setSize(int size) { @@ -1199,20 +1215,20 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } @Override - public Vector getMinimumPoint() { + public BlockVector3 getMinimumPoint() { if (extent != null) { return this.extent.getMinimumPoint(); } else { - return new Vector(-30000000, 0, -30000000); + return BlockVector3.at(-30000000, 0, -30000000); } } @Override - public Vector getMaximumPoint() { + public BlockVector3 getMaximumPoint() { if (extent != null) { return this.extent.getMaximumPoint(); } else { - return new Vector(30000000, 255, 30000000); + return BlockVector3.at(30000000, 255, 30000000); } } @@ -1225,6 +1241,27 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, public List getEntities() { return this.extent.getEntities(); } + + /** + * Closing an EditSession {@linkplain #flushSession() flushes its buffers}. + */ + @Override + public void close() { + flushSession(); + } + + /** + * Communicate to the EditSession that all block changes are complete, + * and that it should apply them to the world. + */ + public void flushSession() { + Operations.completeBlindly(commit()); + } + + @Override + public @Nullable Operation commit() { + return extent.commit(); + } /** * Finish off the queue. @@ -1278,7 +1315,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, final BlockType id = searchIDs.iterator().next(); RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { return getBlockType(position) == id; } }, this); @@ -1295,7 +1332,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, public int countBlock(final Region region, final boolean[] ids) { RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { return ids[getBlockType(position).getInternalId()]; } }, this); @@ -1306,7 +1343,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, public int countBlock(final Region region, final Mask mask) { RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { return mask.test(position); } }, this); @@ -1325,7 +1362,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, final Mask mask = new BlockMaskBuilder().addBlocks(searchBlocks).build(extent); RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { return mask.test(position); } }, this); @@ -1340,7 +1377,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, final int endY = region.getMaximumPoint().getBlockY(); RegionVisitor visitor = new RegionVisitor(flat, new RegionFunction() { @Override - public boolean apply(Vector pos) throws WorldEditException { + public boolean apply(BlockVector3 pos) throws WorldEditException { int x = pos.getBlockX(); int z = pos.getBlockZ(); int freeSpot = startCheckY; @@ -1378,15 +1415,15 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int fillDirection(final Vector origin, final Pattern pattern, final double radius, final int depth, Vector direction) { + public int fillDirection(final BlockVector3 origin, final Pattern pattern, final double radius, final int depth, BlockVector3 direction) { checkNotNull(origin); checkNotNull(pattern); checkArgument(radius >= 0, "radius >= 0"); checkArgument(depth >= 1, "depth >= 1"); - if (direction.equals(new Vector(0, -1, 0))) { + if (direction.equals(BlockVector3.at(0, -1, 0))) { return fillXZ(origin, pattern, radius, depth, false); } - final MaskIntersection mask = new MaskIntersection(new RegionMask(new EllipsoidRegion(null, origin, new Vector(radius, radius, radius))), Masks.negate(new ExistingBlockMask(EditSession.this))); + final MaskIntersection mask = new MaskIntersection(new RegionMask(new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), Masks.negate(new ExistingBlockMask(EditSession.this))); // Want to replace blocks final BlockReplace replace = new BlockReplace(EditSession.this, pattern); @@ -1413,11 +1450,9 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int fillXZ(final Vector origin, final BaseBlock block, final double radius, final int depth, final boolean recursive) { - return this.fillXZ(origin, (Pattern) block, radius, depth, recursive); + public int fillXZ(final BlockVector3 origin, BaseBlock block, double radius, int depth, boolean recursive) throws MaxChangedBlocksException { + return fillXZ(origin, (Pattern) block, radius, depth, recursive); } - /** * Fills an area recursively in the X/Z directions. * @@ -1429,17 +1464,22 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int fillXZ(final Vector origin, final Pattern pattern, final double radius, final int depth, final boolean recursive) { + public int fillXZ(BlockVector3 origin, Pattern pattern, double radius, int depth, boolean recursive) throws MaxChangedBlocksException { checkNotNull(origin); checkNotNull(pattern); checkArgument(radius >= 0, "radius >= 0"); checkArgument(depth >= 1, "depth >= 1"); - final MaskIntersection mask = new MaskIntersection(new RegionMask(new EllipsoidRegion(null, origin, new Vector(radius, radius, radius))), new BoundedHeightMask(Math.max( + final MaskIntersection mask = new MaskIntersection(new RegionMask(new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), new BoundedHeightMask(Math.max( (origin.getBlockY() - depth) + 1, getMinimumPoint().getBlockY()), Math.min(getMaximumPoint().getBlockY(), origin.getBlockY())), Masks.negate(new ExistingBlockMask(EditSession.this))); +// MaskIntersection mask = new MaskIntersection( +// new RegionMask(new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), +// new BoundedHeightMask( +// Math.max(origin.getBlockY() - depth + 1, 0), +// Math.min(getWorld().getMaxY(), origin.getBlockY())), +// Masks.negate(new ExistingBlockMask(this))); // Want to replace blocks - final BlockReplace replace = new BlockReplace(EditSession.this, pattern); + BlockReplace replace = new BlockReplace(this, pattern); // Pick how we're going to visit blocks RecursiveVisitor visitor; @@ -1466,8 +1506,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int removeAbove(final Vector position, final int apothem, final int height) { + public int removeAbove(BlockVector3 position, int apothem, int height) throws MaxChangedBlocksException { checkNotNull(position); checkArgument(apothem >= 1, "apothem >= 1"); checkArgument(height >= 1, "height >= 1"); @@ -1487,8 +1526,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int removeBelow(final Vector position, final int apothem, final int height) { + public int removeBelow(BlockVector3 position, int apothem, int height) throws MaxChangedBlocksException { checkNotNull(position); checkArgument(apothem >= 1, "apothem >= 1"); checkArgument(height >= 1, "height >= 1"); @@ -1508,12 +1546,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int removeNear(final Vector position, Mask mask, final int apothem) { + public int removeNear(final BlockVector3 position, Mask mask, final int apothem) { checkNotNull(position); checkArgument(apothem >= 1, "apothem >= 1"); - final Vector adjustment = new Vector(1, 1, 1).multiply(apothem - 1); + final BlockVector3 adjustment = BlockVector3.at(1, 1, 1).multiply(apothem - 1); final Region region = new CuboidRegion(this.getWorld(), // Causes clamping of Y range position.add(adjustment.multiply(-1)), position.add(adjustment)); final Pattern pattern = BlockTypes.AIR.getDefaultState(); @@ -1527,8 +1564,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, if (!(region instanceof CuboidRegion)) return false; if (regionExtent != null) { if (!(region instanceof CuboidRegion)) return false; - Vector pos1 = region.getMinimumPoint(); - Vector pos2 = region.getMaximumPoint(); + BlockVector3 pos1 = region.getMinimumPoint(); + BlockVector3 pos2 = region.getMaximumPoint(); boolean contains = false; for (Region current : regionExtent.getRegions()) { if (current.contains((int) pos1.getX(), pos1.getBlockY(), pos1.getBlockZ()) && current.contains(pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ())) { @@ -1551,6 +1588,19 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, public boolean hasExtraExtents() { return wrapped || getMask() != null || getSourceMask() != null || history != null; } + public int removeNear(BlockVector3 position, BlockType blockType, int apothem) throws MaxChangedBlocksException { + checkNotNull(position); + checkArgument(apothem >= 1, "apothem >= 1"); + + Mask mask = new BlockTypeMask(this, blockType); + BlockVector3 adjustment = BlockVector3.ONE.multiply(apothem - 1); + Region region = new CuboidRegion( + getWorld(), // Causes clamping of Y range + position.add(adjustment.multiply(-1)), + position.add(adjustment)); + Pattern pattern = new BlockPattern(BlockTypes.AIR.getDefaultState()); + return replaceBlocks(region, mask, pattern); + } /** * Sets all the blocks inside a region to a given block type. @@ -1560,11 +1610,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int setBlocks(final Region region, final BlockStateHolder block) { + public > int setBlocks(final Region region, final B block) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(block); - if (canBypassAll(region, false, true) && !block.hasNbtData()) { + boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); + + if (canBypassAll(region, false, true) && !hasNbt) { return changes = queue.setBlocks((CuboidRegion) region, block.getInternalId()); } try { @@ -1573,7 +1624,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, Operations.completeBlindly(visitor); this.changes += visitor.getAffected(); } else { - Iterator iter = region.iterator(); + Iterator iter = region.iterator(); while (iter.hasNext()) { if (this.extent.setBlock(iter.next(), block)) { changes++; @@ -1594,8 +1645,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - @SuppressWarnings("deprecation") - public int setBlocks(final Region region, final Pattern pattern) { + public int setBlocks(Region region, Pattern pattern) throws MaxChangedBlocksException { checkNotNull(region); checkNotNull(pattern); if (pattern instanceof BlockPattern) { @@ -1620,7 +1670,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int replaceBlocks(Region region, Set filter, BlockStateHolder replacement) throws MaxChangedBlocksException { + public > int replaceBlocks(Region region, Set filter, B replacement) throws MaxChangedBlocksException { return replaceBlocks(region, filter, new BlockPattern(replacement)); } @@ -1676,10 +1726,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, checkNotNull(region); checkNotNull(pattern); - final Vector center = region.getCenter(); - final Region centerRegion = new CuboidRegion(this.getWorld(), // Causes clamping of Y range - center.floor(), center.ceil()); - return this.setBlocks(centerRegion, pattern); + Vector3 center = region.getCenter(); + Region centerRegion = new CuboidRegion( + getWorld(), // Causes clamping of Y range + BlockVector3.at(((int) center.getX()), ((int) center.getY()), ((int) center.getZ())), + BlockVector3.at(MathUtils.roundHalfUp(center.getX()), + center.getY(), MathUtils.roundHalfUp(center.getZ()))); + return setBlocks(centerRegion, pattern); } /** @@ -1691,7 +1744,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @throws MaxChangedBlocksException thrown if too many blocks are changed */ @SuppressWarnings("deprecation") - public int makeCuboidFaces(final Region region, final BlockStateHolder block) { + public > int makeCuboidFaces(final Region region, final B block) { return this.makeCuboidFaces(region, (Pattern) (block)); } @@ -1746,7 +1799,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @throws MaxChangedBlocksException thrown if too many blocks are changed */ @SuppressWarnings("deprecation") - public int makeCuboidWalls(final Region region, final BlockStateHolder block) { + public > int makeCuboidWalls(final Region region, final B block) { return this.makeCuboidWalls(region, (Pattern) (block)); } @@ -1787,7 +1840,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, if (region instanceof CuboidRegion) { return this.makeCuboidWalls(region, pattern); } else { - for (BlockVector position : region) { + for (BlockVector3 position : region) { int x = position.getBlockX(); int y = position.getBlockY(); int z = position.getBlockZ(); @@ -1808,9 +1861,9 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int overlayCuboidBlocks(Region region, BlockStateHolder block) throws MaxChangedBlocksException { + public > int overlayCuboidBlocks(Region region, B block) throws MaxChangedBlocksException { checkNotNull(block); - return this.overlayCuboidBlocks(region, (Pattern) (block)); + return overlayCuboidBlocks(region, new BlockPattern(block)); } /** @@ -1827,13 +1880,19 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, checkNotNull(region); checkNotNull(pattern); final BlockReplace replace = new BlockReplace(EditSession.this, pattern); - final RegionOffset offset = new RegionOffset(new Vector(0, 1, 0), replace); + final RegionOffset offset = new RegionOffset(BlockVector3.at(0, 1, 0), replace); int minY = region.getMinimumPoint().getBlockY(); int maxY = Math.min(getMaximumPoint().getBlockY(), region.getMaximumPoint().getBlockY() + 1); SurfaceRegionFunction surface = new SurfaceRegionFunction(this, offset, minY, maxY); FlatRegionVisitor visitor = new FlatRegionVisitor(asFlatRegion(region), surface, this); Operations.completeBlindly(visitor); return this.changes = visitor.getAffected(); +// BlockReplace replace = new BlockReplace(this, pattern); +// RegionOffset offset = new RegionOffset(BlockVector3.at(0, 1, 0), replace); +// GroundFunction ground = new GroundFunction(new ExistingBlockMask(this), offset); +// LayerVisitor visitor = new LayerVisitor(asFlatRegion(region), minimumBlockY(region), maximumBlockY(region), ground); +// Operations.completeLegacy(visitor); +// return ground.getAffected(); } /** @@ -1853,7 +1912,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return this.changes = naturalizer.getAffected(); } - public int stackCuboidRegion(final Region region, final Vector dir, final int count, final boolean copyAir) { + public int stackCuboidRegion(final Region region, final BlockVector3 dir, final int count, final boolean copyAir) { return stackCuboidRegion(region, dir, count, copyAir, true, false); } @@ -1867,12 +1926,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int stackCuboidRegion(final Region region, final Vector dir, final int count, final boolean copyAir, boolean copyEntities, boolean copyBiomes) { + public int stackCuboidRegion(final Region region, final BlockVector3 dir, final int count, final boolean copyAir, boolean copyEntities, boolean copyBiomes) { checkNotNull(region); checkNotNull(dir); checkArgument(count >= 1, "count >= 1 required"); - final Vector size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); - final Vector to = region.getMinimumPoint(); + final BlockVector3 size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); + final BlockVector3 to = region.getMinimumPoint(); final ForwardExtentCopy copy = new ForwardExtentCopy(EditSession.this, region, EditSession.this, to); copy.setCopyingEntities(copyEntities); copy.setCopyBiomes(copyBiomes); @@ -1898,28 +1957,28 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @param dir the direction * @param distance the distance to move * @param copyAir true to copy air blocks - * @param replacement the replacement block to fill in after moving, or null to use air + * @param replacement the replacement pattern to fill in after moving, or null to use air * @return number of blocks moved * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int moveRegion(final Region region, final Vector dir, final int distance, final boolean copyAir, final BlockStateHolder replacement) { + public int moveRegion(final Region region, final BlockVector3 dir, final int distance, final boolean copyAir, final BlockStateHolder replacement) { return moveRegion(region, dir, distance, copyAir, true, false, replacement); } - public int moveRegion(final Region region, final Vector dir, final int distance, final boolean copyAir, final boolean copyEntities, final boolean copyBiomes, BlockStateHolder replacement) { + public int moveRegion(final Region region, final BlockVector3 dir, final int distance, final boolean copyAir, final boolean copyEntities, final boolean copyBiomes, BlockStateHolder replacement) { return moveRegion(region, dir, distance, copyAir, copyEntities, copyBiomes, (Pattern) replacement); } - public int moveRegion(final Region region, final Vector dir, final int distance, final boolean copyAir, final boolean copyEntities, final boolean copyBiomes, Pattern replacement) { + public int moveRegion(final Region region, final BlockVector3 dir, final int distance, final boolean copyAir, final boolean copyEntities, final boolean copyBiomes, Pattern replacement) { checkNotNull(region); checkNotNull(dir); checkArgument(distance >= 1, "distance >= 1 required"); - final Vector displace = dir.multiply(distance); + final BlockVector3 displace = dir.multiply(distance); - final Vector size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); - final Vector to = region.getMinimumPoint().add(dir.multiply(distance)); + final BlockVector3 size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); + final BlockVector3 to = region.getMinimumPoint().add(dir.multiply(distance)); - Vector disAbs = displace.positive(); + BlockVector3 disAbs = displace.abs(); if (disAbs.getBlockX() < size.getBlockX() && disAbs.getBlockY() < size.getBlockY() && disAbs.getBlockZ() < size.getBlockZ()) { // Buffer if overlapping @@ -1955,12 +2014,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @param dir the direction * @param distance the distance to move * @param copyAir true to copy air blocks - * @param replacement the replacement block to fill in after moving, or null to use air + * @param replacement the replacement pattern to fill in after moving, or null to use air * @return number of blocks moved * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int moveCuboidRegion(final Region region, final Vector dir, final int distance, final boolean copyAir, final BlockStateHolder replacement) { - return this.moveRegion(region, dir, distance, copyAir, replacement); + public int moveCuboidRegion(final Region region, final BlockVector3 dir, final int distance, final boolean copyAir, final Pattern replacement) { + return this.moveRegion(region, dir, distance, copyAir, true, false, replacement); } /** @@ -1971,7 +2030,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int drainArea(final Vector origin, final double radius) { + public int drainArea(final BlockVector3 origin, final double radius) { checkNotNull(origin); checkArgument(radius >= 0, "radius >= 0 required"); Mask liquidMask; @@ -1987,13 +2046,27 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, new BoundedHeightMask(0, EditSession.this.getMaximumPoint().getBlockY()), new RegionMask( new EllipsoidRegion(null, origin, - new Vector(radius, radius, radius))), liquidMask); + Vector3.at(radius, radius, radius))), liquidMask); final BlockReplace replace = new BlockReplace(EditSession.this, BlockTypes.AIR.getDefaultState()); final RecursiveVisitor visitor = new RecursiveVisitor(mask, replace, (int) (radius * 2 + 1), this); // Around the origin in a 3x3 block - for (final BlockVector position : CuboidRegion.fromCenter(origin, 1)) { + for (final BlockVector3 position : CuboidRegion.fromCenter(origin, 1)) { +// public int drainArea(BlockVector3 origin, double radius) throws MaxChangedBlocksException { +// checkNotNull(origin); +// checkArgument(radius >= 0, "radius >= 0 required"); +// +// MaskIntersection mask = new MaskIntersection( +// new BoundedHeightMask(0, getWorld().getMaxY()), +// new RegionMask(new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), +// getWorld().createLiquidMask()); +// +// BlockReplace replace = new BlockReplace(this, new BlockPattern(BlockTypes.AIR.getDefaultState())); +// RecursiveVisitor visitor = new RecursiveVisitor(mask, replace); +// +// // Around the origin in a 3x3 block +// for (BlockVector3 position : CuboidRegion.fromCenter(origin, 1)) { if (mask.test(position)) { visitor.visit(position); } @@ -2011,21 +2084,21 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int fixLiquid(final Vector origin, final double radius, Mask liquidMask, Pattern pattern) { + public int fixLiquid(final BlockVector3 origin, final double radius, Mask liquidMask, Pattern pattern) { checkNotNull(origin); checkArgument(radius >= 0, "radius >= 0 required"); // There are boundaries that the routine needs to stay in MaskIntersection mask = new MaskIntersection( new BoundedHeightMask(0, Math.min(origin.getBlockY(), getMaximumPoint().getBlockY())), - new RegionMask(new EllipsoidRegion(null, origin, new Vector(radius, radius, radius))), + new RegionMask(new EllipsoidRegion(null, origin, Vector3.at(radius, radius, radius))), liquidMask); BlockReplace replace = new BlockReplace(this, pattern); NonRisingVisitor visitor = new NonRisingVisitor(mask, replace, (int) (radius * 2 + 1), this); // Around the origin in a 3x3 block - for (BlockVector position : CuboidRegion.fromCenter(origin, 1)) { + for (BlockVector3 position : CuboidRegion.fromCenter(origin, 1)) { if (liquidMask.test(position)) { visitor.visit(position); } @@ -2046,8 +2119,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makeCylinder(final Vector pos, final Pattern block, final double radius, final int height, final boolean filled) { - return this.makeCylinder(pos, block, radius, radius, height, filled); + public int makeCylinder(BlockVector3 pos, Pattern block, double radius, int height, boolean filled) throws MaxChangedBlocksException { + return makeCylinder(pos, block, radius, radius, height, filled); } /** @@ -2062,38 +2135,38 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makeCylinder(Vector pos, final Pattern block, double radiusX, double radiusZ, int height, final boolean filled) { + public int makeCylinder(BlockVector3 pos, final Pattern block, double radiusX, double radiusZ, int height, final boolean filled) { return makeCylinder(pos, block, radiusX, radiusZ, height, 0, filled); } - public int makeHollowCylinder(Vector pos, final Pattern block, double radiusX, double radiusZ, int height, double thickness) { + public int makeHollowCylinder(BlockVector3 pos, final Pattern block, double radiusX, double radiusZ, int height, double thickness) { return makeCylinder(pos, block, radiusX, radiusZ, height, thickness, false); } - private int makeCylinder(Vector pos, final Pattern block, double radiusX, double radiusZ, int height, double thickness, final boolean filled) { + private int makeCylinder(BlockVector3 pos, final Pattern block, double radiusX, double radiusZ, int height, double thickness, final boolean filled) { radiusX += 0.5; radiusZ += 0.5; - + MutableBlockVector3 posv = new MutableBlockVector3(pos); if (height == 0) { return this.changes; } else if (height < 0) { height = -height; - pos.mutY(pos.getY() - height); + posv.mutY(posv.getY() - height); } - if (pos.getBlockY() < 0) { - pos.mutY(0); - } else if (((pos.getBlockY() + height) - 1) > maxY) { - height = (maxY - pos.getBlockY()) + 1; + if (posv.getBlockY() < 0) { + posv.mutY(0); + } else if (((posv.getBlockY() + height) - 1) > maxY) { + height = (maxY - posv.getBlockY()) + 1; } final double invRadiusX = 1 / (radiusX); final double invRadiusZ = 1 / (radiusZ); - int px = pos.getBlockX(); - int py = pos.getBlockY(); - int pz = pos.getBlockZ(); - MutableBlockVector mutable = new MutableBlockVector(); + int px = posv.getBlockX(); + int py = posv.getBlockY(); + int pz = posv.getBlockZ(); + MutableBlockVector3 mutable = new MutableBlockVector3(); final int ceilRadiusX = (int) Math.ceil(radiusX); final int ceilRadiusZ = (int) Math.ceil(radiusZ); @@ -2179,7 +2252,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return this.changes; } - public int makeCircle(Vector pos, final Pattern block, double radiusX, double radiusY, double radiusZ, boolean filled, Vector normal) { + public int makeCircle(BlockVector3 pos, final Pattern block, double radiusX, double radiusY, double radiusZ, boolean filled, Vector3 normal) { radiusX += 0.5; radiusY += 0.5; radiusZ += 0.5; @@ -2197,7 +2270,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, int px = pos.getBlockX(); int py = pos.getBlockY(); int pz = pos.getBlockZ(); - MutableBlockVector mutable = new MutableBlockVector(); + MutableBlockVector3 mutable = new MutableBlockVector3(); final int ceilRadiusX = (int) Math.ceil(radiusX); final int ceilRadiusY = (int) Math.ceil(radiusY); @@ -2276,7 +2349,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makeSphere(final Vector pos, final Pattern block, final double radius, final boolean filled) { + public int makeSphere(final BlockVector3 pos, final Pattern block, final double radius, final boolean filled) { return makeSphere(pos, block, radius, radius, radius, filled); } @@ -2292,7 +2365,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makeSphere(final Vector pos, final Pattern block, double radiusX, double radiusY, double radiusZ, final boolean filled) { + public int makeSphere(final BlockVector3 pos, final Pattern block, double radiusX, double radiusY, double radiusZ, final boolean filled) { radiusX += 0.5; radiusY += 0.5; radiusZ += 0.5; @@ -2371,18 +2444,28 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makePyramid(final Vector position, final Pattern block, int size, final boolean filled) { - final int height = size; + public int makePyramid(BlockVector3 position, Pattern block, int size, boolean filled) throws MaxChangedBlocksException { + int affected = 0; + int height = size; for (int y = 0; y <= height; ++y) { size--; for (int x = 0; x <= size; ++x) { for (int z = 0; z <= size; ++z) { - if ((filled && (z <= size) && (x <= size)) || (z == size) || (x == size)) { - this.setBlock(position.add(x, y, z), block); - this.setBlock(position.add(-x, y, z), block); - this.setBlock(position.add(x, y, -z), block); - this.setBlock(position.add(-x, y, -z), block); + if ((filled && z <= size && x <= size) || z == size || x == size) { + + if (setBlock(position.add(x, y, z), block)) { + ++affected; + } + if (setBlock(position.add(-x, y, z), block)) { + ++affected; + } + if (setBlock(position.add(x, y, -z), block)) { + ++affected; + } + if (setBlock(position.add(-x, y, -z), block)) { + ++affected; + } } } } @@ -2399,38 +2482,36 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int thaw(final Vector position, final double radius) { - final double radiusSq = radius * radius; + public int thaw(BlockVector3 position, double radius) + throws MaxChangedBlocksException { + int affected = 0; + double radiusSq = radius * radius; - final int ox = position.getBlockX(); - final int oy = position.getBlockY(); - final int oz = position.getBlockZ(); - - final int ceilRadius = (int) Math.ceil(radius); - for (int x = ox - ceilRadius; x <= (ox + ceilRadius); ++x) { - int dx = x - ox; - int dx2 = dx * dx; - for (int z = oz - ceilRadius; z <= (oz + ceilRadius); ++z) { - int dz = z - oz; - int dz2 = dz * dz; - if (dx2 + dz2 > radiusSq) { + int ox = position.getBlockX(); + int oy = position.getBlockY(); + int oz = position.getBlockZ(); + BlockState air = BlockTypes.AIR.getDefaultState(); + BlockState water = BlockTypes.WATER.getDefaultState(); + int ceilRadius = (int) Math.ceil(radius); + for (int x = ox - ceilRadius; x <= ox + ceilRadius; ++x) { + for (int z = oz - ceilRadius; z <= oz + ceilRadius; ++z) { + if ((BlockVector3.at(x, oy, z)).distanceSq(position) > radiusSq) { continue; } - for (int y = maxY; y >= 1; --y) { - final BlockType type = getBlockType(x, y, z); - switch (type.getTypeEnum()) { - case ICE: - this.setBlock(x, y, z, BlockTypes.WATER.getDefaultState()); - break; - case SNOW: - this.setBlock(x, y, z, BlockTypes.AIR.getDefaultState()); - break; - case CAVE_AIR: - case VOID_AIR: - case AIR: + for (int y = world.getMaxY(); y >= 1; --y) { + BlockVector3 pt = BlockVector3.at(x, y, z); + BlockType id = getBlock(pt).getBlockType(); + + if (id == BlockTypes.ICE) { + if (setBlock(pt, water)) { + ++affected; + } + } else if (id == BlockTypes.SNOW) { + if (setBlock(pt, air)) { + ++affected; + } + } else if (id.getMaterial().isAir()) { continue; - default: - break; } break; } @@ -2448,56 +2529,55 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int simulateSnow(final Vector position, final double radius) { + public int simulateSnow(BlockVector3 position, double radius) throws MaxChangedBlocksException { + int affected = 0; + double radiusSq = radius * radius; - final double radiusSq = radius * radius; + int ox = position.getBlockX(); + int oy = position.getBlockY(); + int oz = position.getBlockZ(); - final int ox = position.getBlockX(); - final int oy = position.getBlockY(); - final int oz = position.getBlockZ(); + BlockState ice = BlockTypes.ICE.getDefaultState(); + BlockState snow = BlockTypes.SNOW.getDefaultState(); - final int ceilRadius = (int) Math.ceil(radius); - for (int x = ox - ceilRadius; x <= (ox + ceilRadius); ++x) { - int dx = x - ox; - int dx2 = dx * dx; - for (int z = oz - ceilRadius; z <= (oz + ceilRadius); ++z) { - int dz = z - oz; - int dz2 = dz * dz; - if (dx2 + dz2 > radiusSq) { + int ceilRadius = (int) Math.ceil(radius); + for (int x = ox - ceilRadius; x <= ox + ceilRadius; ++x) { + for (int z = oz - ceilRadius; z <= oz + ceilRadius; ++z) { + if ((BlockVector3.at(x, oy, z)).distanceSq(position) > radiusSq) { continue; } - outer: - for (int y = maxY; y >= 1; --y) { - BlockType type = getBlockType(x, y, z); - switch (type.getTypeEnum()) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - continue; - case WATER: - this.setBlock(x, y, z, BlockTypes.ICE.getDefaultState()); - break outer; - case ACACIA_LEAVES: // TODO FIXME get leaves dynamically - case BIRCH_LEAVES: - case DARK_OAK_LEAVES: - case JUNGLE_LEAVES: - case OAK_LEAVES: - case SPRUCE_LEAVES: + for (int y = world.getMaxY(); y >= 1; --y) { + BlockVector3 pt = BlockVector3.at(x, y, z); + BlockType id = getBlock(pt).getBlockType(); + if (id.getMaterial().isAir()) { + continue; + } + // Ice! + if (id == BlockTypes.WATER) { + if (setBlock(pt, ice)) { + ++affected; + } + break; + } + + // Snow should not cover these blocks + if (id.getMaterial().isTranslucent()) { + // Add snow on leaves + if (!BlockCategories.LEAVES.contains(id)) { break; - default: - if (type.getMaterial().isTranslucent()) { - break outer; } } // Too high? - if (y == maxY) { - break outer; + if (y == world.getMaxY()) { + break; } // add snow cover - this.setBlock(x, y + 1, z, BlockTypes.SNOW.getDefaultState()); - break outer; + if (setBlock(pt.add(0, 1, 0), snow)) { + ++affected; + } + break; } } } @@ -2513,7 +2593,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int green(final Vector position, final double radius) { + public int green(final BlockVector3 position, final double radius) { + return this.green(position, radius, false); +} + public int green(BlockVector3 position, double radius, boolean onlyNormalDirt) + throws MaxChangedBlocksException { + int affected = 0; final double radiusSq = radius * radius; final int ox = position.getBlockX(); @@ -2533,17 +2618,37 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, loop: for (int y = maxY; y >= 1; --y) { BlockType block = getBlockType(x, y, z); - switch (block.getTypeEnum()) { - case DIRT: + switch (block.getResource().toUpperCase()) { + case "DIRT": this.setBlock(x, y, z, BlockTypes.GRASS_BLOCK.getDefaultState()); break loop; - case WATER: - case LAVA: + case "WATER": + case "LAVA": break loop; default: if (block.getMaterial().isMovementBlocker()) { break loop; } +// for (int x = ox - ceilRadius; x <= ox + ceilRadius; ++x) { +// for (int z = oz - ceilRadius; z <= oz + ceilRadius; ++z) { +// if ((BlockVector3.at(x, oy, z)).distanceSq(position) > radiusSq) { +// continue; +// } +// +// for (int y = world.getMaxY(); y >= 1; --y) { +// final BlockVector3 pt = BlockVector3.at(x, y, z); +// final BlockState block = getBlock(pt); +// +// if (block.getBlockType() == BlockTypes.DIRT || +// (!onlyNormalDirt && block.getBlockType() == BlockTypes.COARSE_DIRT)) { +// if (setBlock(pt, grass)) { +// ++affected; +// } +// break; +// } else if (block.getBlockType() == BlockTypes.WATER || block.getBlockType() == BlockTypes.LAVA) { +// break; +// } else if (block.getBlockType().getMaterial().isMovementBlocker()) { +// break; } } } @@ -2560,7 +2665,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of patches created * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makePumpkinPatches(final Vector position, final int apothem) { + public int makePumpkinPatches(final BlockVector3 position, final int apothem) { return makePumpkinPatches(position, apothem, 0.02); } @@ -2572,7 +2677,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of patches created * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makePumpkinPatches(final Vector position, final int apothem, double density) { + public int makePumpkinPatches(final BlockVector3 position, final int apothem, double density) { // We want to generate pumpkins final GardenPatchGenerator generator = new GardenPatchGenerator(EditSession.this); generator.setPlant(GardenPatchGenerator.getPumpkinPattern()); @@ -2598,7 +2703,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of trees created * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int makeForest(final Vector basePosition, final int size, final double density, TreeGenerator.TreeType treeType) { + public int makeForest(final BlockVector3 basePosition, final int size, final double density, TreeGenerator.TreeType treeType) { try { for (int x = basePosition.getBlockX() - size; x <= (basePosition.getBlockX() + size); ++x) { for (int z = basePosition.getBlockZ() - size; z <= (basePosition.getBlockZ() + size); ++z) { @@ -2613,22 +2718,42 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, this.changes++; for (int y = basePosition.getBlockY(); y >= (basePosition.getBlockY() - 10); --y) { BlockType type = getBlockType(x, y, z); - switch (type.getTypeEnum()) { - case GRASS: - case DIRT: - treeType.generate(this, new Vector(x, y + 1, z)); - this.changes++; - break; - case SNOW: - setBlock(new Vector(x, y, z), BlockTypes.AIR.getDefaultState()); - break; - case AIR: - case CAVE_AIR: - case VOID_AIR: - continue; - default: - break; + String s = type.getResource().toUpperCase(); + if (type == BlockTypes.GRASS || type == BlockTypes.DIRT) { + treeType.generate(this, BlockVector3.at(x, y + 1, z)); + this.changes++; + } else if (type == BlockTypes.SNOW) { + setBlock(BlockVector3.at(x, y, z), BlockTypes.AIR.getDefaultState()); + } else if (type.getMaterial().isAir()) { + continue; } +// public int makeForest(BlockVector3 basePosition, int size, double density, TreeGenerator.TreeType treeType) throws MaxChangedBlocksException { +// int affected = 0; +// +// for (int x = basePosition.getBlockX() - size; x <= basePosition.getBlockX() +// + size; ++x) { +// for (int z = basePosition.getBlockZ() - size; z <= basePosition.getBlockZ() +// + size; ++z) { +// // Don't want to be in the ground +// if (!getBlock(BlockVector3.at(x, basePosition.getBlockY(), z)).getBlockType().getMaterial().isAir()) { +// continue; +// } +// // The gods don't want a tree here +// if (Math.random() >= density) { +// continue; +// } // def 0.05 +// +// for (int y = basePosition.getBlockY(); y >= basePosition.getBlockY() - 10; --y) { +// // Check if we hit the ground +// BlockType t = getBlock(BlockVector3.at(x, y, z)).getBlockType(); +// if (t == BlockTypes.GRASS_BLOCK || t == BlockTypes.DIRT) { +// treeType.generate(this, BlockVector3.at(x, y + 1, z)); +// ++affected; +// break; +// } else if (t == BlockTypes.SNOW) { +// setBlock(BlockVector3.at(x, y, z), BlockTypes.AIR.getDefaultState()); +// } else if (!t.getMaterial().isAir()) { // Trees won't grow on this! +// break; } } } @@ -2648,8 +2773,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, if (region instanceof CuboidRegion) { // Doing this for speed - final Vector min = region.getMinimumPoint(); - final Vector max = region.getMaximumPoint(); + final BlockVector3 min = region.getMinimumPoint(); + final BlockVector3 max = region.getMaximumPoint(); final int minX = min.getBlockX(); final int minY = min.getBlockY(); @@ -2658,7 +2783,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, final int maxY = max.getBlockY(); final int maxZ = max.getBlockZ(); - MutableBlockVector mutable = new MutableBlockVector(minX, minY, minZ); + MutableBlockVector3 mutable = new MutableBlockVector3(minX, minY, minZ); for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { for (int z = minZ; z <= maxZ; ++z) { @@ -2668,7 +2793,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } } } else { - for (final Vector pt : region) { + for (final BlockVector3 pt : region) { BlockType type = getBlockType(pt); counter[type.getInternalId()]++; } @@ -2695,8 +2820,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, if (region instanceof CuboidRegion) { // Doing this for speed - final Vector min = region.getMinimumPoint(); - final Vector max = region.getMaximumPoint(); + final BlockVector3 min = region.getMinimumPoint(); + final BlockVector3 max = region.getMaximumPoint(); final int minX = min.getBlockX(); final int minY = min.getBlockY(); @@ -2719,7 +2844,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } } } else { - for (final Vector pt : region) { + for (final BlockVector3 pt : region) { BlockStateHolder blk = this.getBlock(pt); BlockType type = blk.getBlockType(); int[] stateCounter = counter[type.getInternalId()]; @@ -2748,7 +2873,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return distribution; } - public int makeShape(final Region region, final Vector zero, final Vector unit, final Pattern pattern, final String expressionString, final boolean hollow) throws ExpressionException, + public int makeShape(final Region region, final Vector3 zero, final Vector3 unit, final Pattern pattern, final String expressionString, final boolean hollow) throws ExpressionException, MaxChangedBlocksException { final Expression expression = Expression.compile(expressionString, "x", "y", "z", "type", "data"); expression.optimize(); @@ -2761,11 +2886,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, final ArbitraryShape shape = new ArbitraryShape(region) { @Override - public BlockStateHolder getMaterial(final int x, final int y, final int z, final BlockStateHolder defaultMaterial) { + public BaseBlock getMaterial(final int x, final int y, final int z, final BaseBlock defaultMaterial) { //TODO Optimize - avoid vector creation (math) - final Vector current = mutable.setComponents(x, y, z); +// final Vector3 current = mutablev.setComponents(x, y, z); +// protected BlockStateHolder getMaterial(int x, int y, int z, BlockStateHolder defaultMaterial) { + final Vector3 current = Vector3.at(x, y, z); environment.setCurrentBlock(current); - final Vector scaled = current.subtract(zero).divide(unit); + final Vector3 scaled = current.subtract(zero).divide(unit); try { if (expression.evaluate(scaled.getX(), scaled.getY(), scaled.getZ(), defaultMaterial.getBlockType().getInternalId(), defaultMaterial.getInternalPropertiesId()) <= 0) { @@ -2773,7 +2900,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return null; } - return BlockTypes.get((int) typeVariable.getValue()).withPropertyId((int) dataVariable.getValue()); + return BlockTypes.get((int) typeVariable.getValue()).withPropertyId((int) dataVariable.getValue()).toBaseBlock(); } catch (final Exception e) { Fawe.debug("Failed to create shape: " + e); return null; @@ -2788,7 +2915,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } } - public int deformRegion(final Region region, final Vector zero, final Vector unit, final String expressionString) throws ExpressionException, MaxChangedBlocksException { + public int deformRegion(final Region region, final Vector3 zero, final Vector3 unit, final String expressionString) throws ExpressionException, MaxChangedBlocksException { final Expression expression = Expression.compile(expressionString, "x", "y", "z"); expression.optimize(); final RValue x = expression.getVariable("x", false).optimize(); @@ -2796,14 +2923,24 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, final RValue z = expression.getVariable("z", false).optimize(); final WorldEditExpressionEnvironment environment = new WorldEditExpressionEnvironment(this, unit, zero); expression.setEnvironment(environment); - final Vector zero2 = zero.add(0.5, 0.5, 0.5); + final Vector3 zero2 = zero.add(0.5, 0.5, 0.5); RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { +// final DoubleArrayList queue = new DoubleArrayList<>(false); +// +// for (BlockVector3 position : region) { +// // offset, scale +// final Vector3 scaled = position.subtract(zero).divide(unit); +// +// // transform +// expression.evaluate(scaled.getX(), scaled.getY(), scaled.getZ()); +// +// final BlockVector3 sourcePosition = environment.toWorld(x.getValue(), y.getValue(), z.getValue()); - private MutableBlockVector mutable = new MutableBlockVector(); + private MutableBlockVector3 mutable = new MutableBlockVector3(); @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { try { // offset, scale double sx = (position.getX() - zero.getX()) / unit.getX(); @@ -2819,6 +2956,18 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } catch (EvaluationException e) { throw new RuntimeException(e); } +// // queue operation +// queue.put(position, material); +// } +// +// int affected = 0; +// for (Map.Entry entry : queue) { +// BlockVector3 position = entry.getKey(); +// BaseBlock material = entry.getValue(); +// +// // set at new position +// if (setBlock(position, material)) { +// ++affected; } }, this); Operations.completeBlindly(visitor); @@ -2836,12 +2985,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @throws MaxChangedBlocksException thrown if too many blocks are changed */ public int hollowOutRegion(final Region region, final int thickness, final Pattern pattern) { - - + try { final Set outside = new LocalBlockVectorSet(); - final Vector min = region.getMinimumPoint(); - final Vector max = region.getMaximumPoint(); + final BlockVector3 min = region.getMinimumPoint(); + final BlockVector3 max = region.getMaximumPoint(); final int minX = min.getBlockX(); final int minY = min.getBlockY(); @@ -2852,32 +3000,30 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { - this.recurseHollow(region, new BlockVector(x, y, minZ), outside); - this.recurseHollow(region, new BlockVector(x, y, maxZ), outside); + recurseHollow(region, BlockVector3.at(x, y, minZ), outside); + recurseHollow(region, BlockVector3.at(x, y, maxZ), outside); } } for (int y = minY; y <= maxY; ++y) { for (int z = minZ; z <= maxZ; ++z) { - this.recurseHollow(region, new BlockVector(minX, y, z), outside); - this.recurseHollow(region, new BlockVector(maxX, y, z), outside); + recurseHollow(region, BlockVector3.at(minX, y, z), outside); + recurseHollow(region, BlockVector3.at(maxX, y, z), outside); } } for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { - this.recurseHollow(region, new BlockVector(x, minY, z), outside); - this.recurseHollow(region, new BlockVector(x, maxY, z), outside); + recurseHollow(region, BlockVector3.at(x, minY, z), outside); + recurseHollow(region, BlockVector3.at(x, maxY, z), outside); } } for (int i = 1; i < thickness; ++i) { final Set newOutside = new LocalBlockVectorSet(); - outer: - for (final BlockVector position : region) { - for (final Vector recurseDirection : this.recurseDirections) { - final BlockVector neighbor = position.add(recurseDirection).toBlockVector(); - + outer: for (BlockVector3 position : region) { + for (BlockVector3 recurseDirection : recurseDirections) { + BlockVector3 neighbor = position.add(recurseDirection); if (outside.contains(neighbor)) { newOutside.add(position); continue outer; @@ -2887,12 +3033,9 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, outside.addAll(newOutside); } - try { - outer: - for (final BlockVector position : region) { - for (final Vector recurseDirection : this.recurseDirections) { - final BlockVector neighbor = position.add(recurseDirection).toBlockVector(); - + outer: for (BlockVector3 position : region) { + for (BlockVector3 recurseDirection : recurseDirections) { + BlockVector3 neighbor = position.add(recurseDirection); if (outside.contains(neighbor)) { continue outer; } @@ -2907,7 +3050,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return changes; } - public int drawLine(final Pattern pattern, final Vector pos1, final Vector pos2, final double radius, final boolean filled) { + public int drawLine(final Pattern pattern, final BlockVector3 pos1, final BlockVector3 pos2, final double radius, final boolean filled) { return drawLine(pattern, pos1, pos2, radius, filled, false); } @@ -2923,51 +3066,54 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int drawLine(final Pattern pattern, final Vector pos1, final Vector pos2, final double radius, final boolean filled, boolean flat) { + public int drawLine(final Pattern pattern, final BlockVector3 pos1, final BlockVector3 pos2, final double radius, final boolean filled, boolean flat) { LocalBlockVectorSet vset = new LocalBlockVectorSet(); boolean notdrawn = true; - final int x1 = pos1.getBlockX(), y1 = pos1.getBlockY(), z1 = pos1.getBlockZ(); - final int x2 = pos2.getBlockX(), y2 = pos2.getBlockY(), z2 = pos2.getBlockZ(); + 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; - final int dx = Math.abs(x2 - x1), dy = Math.abs(y2 - y1), dz = Math.abs(z2 - z1); + int dx = Math.abs(x2 - x1), dy = Math.abs(y2 - y1), dz = Math.abs(z2 - z1); - if ((dx + dy + dz) == 0) { - vset.add(tipx, tipy, tipz); + if (dx + dy + dz == 0) { + vset.add(BlockVector3.at(tipx, tipy, tipz)); notdrawn = false; } - if ((Math.max(Math.max(dx, dy), dz) == dx) && notdrawn) { + if (Math.max(Math.max(dx, dy), dz) == dx && notdrawn) { for (int domstep = 0; domstep <= dx; domstep++) { - tipx = x1 + (domstep * ((x2 - x1) > 0 ? 1 : -1)); - tipy = (int) Math.round(y1 + (((domstep * ((double) dy)) / (dx)) * ((y2 - y1) > 0 ? 1 : -1))); - tipz = (int) Math.round(z1 + (((domstep * ((double) dz)) / (dx)) * ((z2 - z1) > 0 ? 1 : -1))); - vset.add(tipx, tipy, tipz); + tipx = x1 + domstep * (x2 - x1 > 0 ? 1 : -1); + tipy = (int) Math.round(y1 + domstep * ((double) dy) / ((double) dx) * (y2 - y1 > 0 ? 1 : -1)); + tipz = (int) Math.round(z1 + domstep * ((double) dz) / ((double) dx) * (z2 - z1 > 0 ? 1 : -1)); + + vset.add(BlockVector3.at(tipx, tipy, tipz)); } notdrawn = false; } - if ((Math.max(Math.max(dx, dy), dz) == dy) && notdrawn) { + if (Math.max(Math.max(dx, dy), dz) == dy && notdrawn) { for (int domstep = 0; domstep <= dy; domstep++) { - tipy = y1 + (domstep * ((y2 - y1) > 0 ? 1 : -1)); - tipx = (int) Math.round(x1 + (((domstep * ((double) dx)) / (dy)) * ((x2 - x1) > 0 ? 1 : -1))); - tipz = (int) Math.round(z1 + (((domstep * ((double) dz)) / (dy)) * ((z2 - z1) > 0 ? 1 : -1))); + tipy = y1 + domstep * (y2 - y1 > 0 ? 1 : -1); + tipx = (int) Math.round(x1 + domstep * ((double) dx) / ((double) dy) * (x2 - x1 > 0 ? 1 : -1)); + tipz = (int) Math.round(z1 + domstep * ((double) dz) / ((double) dy) * (z2 - z1 > 0 ? 1 : -1)); - vset.add(tipx, tipy, tipz); + vset.add(BlockVector3.at(tipx, tipy, tipz)); } notdrawn = false; } - if ((Math.max(Math.max(dx, dy), dz) == dz) && notdrawn) { + if (Math.max(Math.max(dx, dy), dz) == 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)) / (dz)) * ((y2 - y1) > 0 ? 1 : -1))); - tipx = (int) Math.round(x1 + (((domstep * ((double) dx)) / (dz)) * ((x2 - x1) > 0 ? 1 : -1))); - vset.add(tipx, tipy, tipz); + 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)); + + vset.add(BlockVector3.at(tipx, tipy, tipz)); } + notdrawn = false; } - Set newVset; + Set newVset; if (flat) { newVset = this.getStretched(vset, radius); if (!filled) { @@ -2997,14 +3143,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, * @return number of blocks affected * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - public int drawSpline(final Pattern pattern, final List nodevectors, final double tension, final double bias, final double continuity, final double quality, final double radius, final boolean filled) throws WorldEditException { + public int drawSpline(final Pattern pattern, final List nodevectors, final double tension, final double bias, final double continuity, final double quality, final double radius, final boolean filled) throws WorldEditException { LocalBlockVectorSet vset = new LocalBlockVectorSet(); - final List nodes = new ArrayList(nodevectors.size()); + final List nodes = new ArrayList<>(nodevectors.size()); final KochanekBartelsInterpolation interpol = new KochanekBartelsInterpolation(); - - for (final Vector nodevector : nodevectors) { - final Node n = new Node(nodevector); + for (BlockVector3 nodevector : nodevectors) { + Node n = new Node(nodevector.toVector3()); n.setTension(tension); n.setBias(bias); n.setContinuity(continuity); @@ -3014,14 +3159,14 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, interpol.setNodes(nodes); final double splinelength = interpol.arcLength(0, 1); for (double loop = 0; loop <= 1; loop += 1D / splinelength / quality) { - final Vector tipv = interpol.getPosition(loop); + final BlockVector3 tipv = interpol.getPosition(loop).toBlockPoint(); if (radius == 0) { pattern.apply(this, tipv, tipv); } else { vset.add(tipv); } } - Set newVset; + Set newVset; if (radius != 0) { newVset = this.getBallooned(vset, radius); if (!filled) { @@ -3032,13 +3177,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return changes; } - private Set getBallooned(final Set vset, final double radius) { + private Set getBallooned(final Set vset, final double radius) { if (radius < 1) { return vset; } final LocalBlockVectorSet returnset = new LocalBlockVectorSet(); final int ceilrad = (int) Math.ceil(radius); - for (final Vector v : vset) { + for (final BlockVector3 v : vset) { final int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ(); for (int loopx = tipx - ceilrad; loopx <= (tipx + ceilrad); loopx++) { for (int loopy = tipy - ceilrad; loopy <= (tipy + ceilrad); loopy++) { @@ -3053,13 +3198,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return returnset; } - public Set getStretched(final Set vset, final double radius) { + public Set getStretched(final Set vset, final double radius) { if (radius < 1) { return vset; } final LocalBlockVectorSet returnset = new LocalBlockVectorSet(); final int ceilrad = (int) Math.ceil(radius); - for (final Vector v : vset) { + for (final BlockVector3 v : vset) { final int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ(); for (int loopx = tipx - ceilrad; loopx <= (tipx + ceilrad); loopx++) { for (int loopz = tipz - ceilrad; loopz <= (tipz + ceilrad); loopz++) { @@ -3072,44 +3217,47 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return returnset; } - public Set getOutline(final Set vset) { - // TODO optimize - vset instanceof LocalBlockVectorSet -> avoid Vector creation + public Set getOutline(final Set vset) { final LocalBlockVectorSet returnset = new LocalBlockVectorSet(); - for (final Vector v : vset) { - final double x = v.getX(), y = v.getY(), z = v.getZ(); - if (!(vset.contains(new Vector(x + 1, y, z)) - && vset.contains(new Vector(x - 1, y, z)) - && vset.contains(new Vector(x, y, z + 1)) && vset.contains(new Vector(x, y, z - 1)))) { + final LocalBlockVectorSet newset = new LocalBlockVectorSet(); + newset.addAll(vset); + for (final 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))) { returnset.add(v); } } return returnset; } - public Set getHollowed(final Set vset) { - //TODO Optimize - avoid vector creation + public Set getHollowed(final Set vset) { final Set returnset = new LocalBlockVectorSet(); - for (final Vector v : vset) { - final double x = v.getX(), y = v.getY(), z = v.getZ(); - if (!(vset.contains(new Vector(x + 1, y, z)) - && vset.contains(new Vector(x - 1, y, z)) - && vset.contains(new Vector(x, y + 1, z)) - && vset.contains(new Vector(x, y - 1, z)) - && vset.contains(new Vector(x, y, z + 1)) && vset.contains(new Vector(x, y, z - 1)))) { + final LocalBlockVectorSet newset = new LocalBlockVectorSet(); + newset.addAll(vset); + for (final 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))) { returnset.add(v); } } return returnset; } - public void recurseHollow(final Region region, final BlockVector origin, final Set outside) { + public void recurseHollow(final Region region, final BlockVector3 origin, final Set outside) { //TODO FIXME Optimize - avoid vector creation - final ArrayDeque queue = new ArrayDeque(); + final ArrayDeque queue = new ArrayDeque<>(); queue.addLast(origin); while (!queue.isEmpty()) { - final BlockVector current = queue.removeFirst(); - if (this.getBlockType(current).getMaterial().isMovementBlocker()) { + final BlockVector3 current = queue.removeFirst(); + final BlockState block = getBlock(current); + if (block.getBlockType().getMaterial().isMovementBlocker()) { continue; } @@ -3121,15 +3269,15 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, continue; } - for (final Vector recurseDirection : this.recurseDirections) { - queue.addLast(current.add(recurseDirection).toBlockVector()); + for (BlockVector3 recurseDirection : recurseDirections) { + queue.addLast(current.add(recurseDirection)); } } // while } - public int makeBiomeShape(final Region region, final Vector zero, final Vector unit, final BaseBiome biomeType, final String expressionString, final boolean hollow) throws ExpressionException { - final Vector2D zero2D = zero.toVector2D(); - final Vector2D unit2D = unit.toVector2D(); + public int makeBiomeShape(final Region region, final Vector3 zero, final Vector3 unit, final BaseBiome biomeType, final String expressionString, final boolean hollow) throws ExpressionException, MaxChangedBlocksException { + final Vector2 zero2D = zero.toVector2(); + final Vector2 unit2D = unit.toVector2(); final Expression expression = Expression.compile(expressionString, "x", "z"); expression.optimize(); @@ -3141,12 +3289,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, final ArbitraryBiomeShape shape = new ArbitraryBiomeShape(region) { @Override protected BaseBiome getBiome(final int x, final int z, final BaseBiome defaultBiomeType) { - final Vector2D current = new Vector2D(x, z); - environment.setCurrentBlock(current.toVector(0)); - final Vector2D scaled = current.subtract(zero2D).divide(unit2D); + environment.setCurrentBlock(x, 0, z); + double scaledX = (x - zero2D.getX()) / unit2D.getX(); + double scaledZ = (z - zero2D.getZ()) / unit2D.getZ(); try { - if (expression.evaluate(scaled.getX(), scaled.getZ()) <= 0) { + if (expression.evaluate(scaledX, scaledZ) <= 0) { return null; } @@ -3160,7 +3308,14 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return shape.generate(this, biomeType, hollow); } - + private static final BlockVector3[] recurseDirections = { + Direction.NORTH.toBlockVector(), + Direction.EAST.toBlockVector(), + Direction.SOUTH.toBlockVector(), + Direction.WEST.toBlockVector(), + Direction.UP.toBlockVector(), + Direction.DOWN.toBlockVector(), + }; private double lengthSq(final double x, final double y, final double z) { return (x * x) + (y * y) + (z * z); } @@ -3176,13 +3331,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, } @Override - public int getBlockLightLevel(Vector position) { + public int getBlockLightLevel(BlockVector3 position) { return queue.getEmmittedLight(position.getBlockX(), position.getBlockY(), position.getBlockZ()); } @Override - public boolean clearContainerBlockContents(Vector pos) { - BlockStateHolder block = getFullBlock(pos); + public boolean clearContainerBlockContents(BlockVector3 pos) { + BaseBlock block = getFullBlock(pos); CompoundTag nbt = block.getNbtData(); if (nbt != null) { if (nbt.containsKey("items")) { @@ -3202,7 +3357,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return session.regenerate(region, null, null); } - private void setExistingBlocks(Vector pos1, Vector pos2) { + private void setExistingBlocks(BlockVector3 pos1, BlockVector3 pos2) { for (int x = (int) pos1.getX(); x <= (int) pos2.getX(); x++) { for (int z = pos1.getBlockZ(); z <= pos2.getBlockZ(); z++) { for (int y = (int) pos1.getY(); y <= (int) pos2.getY(); y++) { @@ -3227,22 +3382,22 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, final FaweRegionExtent fe = this.getRegionExtent(); final boolean cuboid = region instanceof CuboidRegion; if (fe != null && cuboid) { - Vector max = region.getMaximumPoint(); - Vector min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); + BlockVector3 min = region.getMinimumPoint(); if (!fe.contains(max.getBlockX(), max.getBlockY(), max.getBlockZ()) && !fe.contains(min.getBlockX(), min.getBlockY(), min.getBlockZ())) { throw new FaweException(BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION); } } - final Set chunks = region.getChunks(); - MutableBlockVector mutable = new MutableBlockVector(); - MutableBlockVector2D mutable2D = new MutableBlockVector2D(); - for (Vector2D chunk : chunks) { + final Set chunks = region.getChunks(); + MutableBlockVector3 mutable = new MutableBlockVector3(); + MutableBlockVector2 mutable2D = new MutableBlockVector2(); + for (BlockVector2 chunk : chunks) { final int cx = chunk.getBlockX(); final int cz = chunk.getBlockZ(); final int bx = cx << 4; final int bz = cz << 4; - final Vector cmin = new Vector(bx, 0, bz); - final Vector cmax = cmin.add(15, getMaxY(), 15); + final BlockVector3 cmin = BlockVector3.at(bx, 0, bz); + final BlockVector3 cmax = cmin.add(15, getMaxY(), 15); final boolean containsBot1 = (fe == null || fe.contains(cmin.getBlockX(), cmin.getBlockY(), cmin.getBlockZ())); final boolean containsBot2 = region.contains(cmin); final boolean containsTop1 = (fe == null || fe.contains(cmax.getBlockX(), cmax.getBlockY(), cmax.getBlockZ())); @@ -3255,27 +3410,30 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, boolean containsAny = false; if (cuboid && containsBot1 && containsBot2 && containsTop1 && containsTop2 && conNextX && conNextZ) { containsAny = true; + BlockVector3 mbv = mutable; if (fcs != null) { for (int x = 0; x < 16; x++) { int xx = x + bx; for (int z = 0; z < 16; z++) { int zz = z + bz; for (int y = 0; y < getMaxY() + 1; y++) { - BlockStateHolder block = getFullBlock(mutable.setComponents(xx, y, zz)); - fcs.add(mutable, block, BlockTypes.AIR.getDefaultState()); +// BlockStateHolder block = getFullBlock(mutable.setComponents(xx, y, zz)); + BlockVector3 bv = BlockVector3.at(xx, y, zz); + BaseBlock block = getFullBlock(bv); + fcs.add(mbv, block, BlockTypes.AIR.getDefaultState().toBaseBlock()); } } } } } else { if (!conNextX) { - setExistingBlocks(new Vector(bx + 16, 0, bz), new Vector(bx + 31, getMaxY(), bz + 15)); + setExistingBlocks(BlockVector3.at(bx + 16, 0, bz), BlockVector3.at(bx + 31, getMaxY(), bz + 15)); } if (!conNextZ) { - setExistingBlocks(new Vector(bx, 0, bz + 16), new Vector(bx + 15, getMaxY(), bz + 31)); + setExistingBlocks(BlockVector3.at(bx, 0, bz + 16), BlockVector3.at(bx + 15, getMaxY(), bz + 31)); } if (!chunks.contains(mutable2D.setComponents(cx + 1, cz + 1)) && !conNextX && !conNextZ) { - setExistingBlocks(new Vector(bx + 16, 0, bz + 16), new Vector(bx + 31, getMaxY(), bz + 31)); + setExistingBlocks(BlockVector3.at(bx + 16, 0, bz + 16), BlockVector3.at(bx + 31, getMaxY(), bz + 31)); } for (int x = 0; x < 16; x++) { int xx = x + bx; @@ -3285,17 +3443,18 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, mutable.mutZ(zz); for (int y = 0; y < getMaxY() + 1; y++) { mutable.mutY(y); - boolean contains = (fe == null || fe.contains(xx, y, zz)) && region.contains(mutable); + BlockVector3 mbv = BlockVector3.at(xx, y, zz); + boolean contains = (fe == null || fe.contains(xx, y, zz)) && region.contains(mbv); if (contains) { containsAny = true; if (fcs != null) { - BlockStateHolder block = getFullBlock(mutable.setComponents(xx, y, zz)); - fcs.add(mutable, block, BlockTypes.AIR.getDefaultState()); + BaseBlock block = getFullBlock(mbv); + fcs.add(mbv, block, BlockTypes.AIR.getDefaultState().toBaseBlock()); } } else { - BlockStateHolder block = getFullBlock(mutable.setComponents(xx, y, zz)); + BlockStateHolder block = getFullBlock(mbv); try { - setBlock(mutable, block); + setBlock(mbv, block); } catch (MaxChangedBlocksException e) { throw new RuntimeException(e); } @@ -3323,27 +3482,26 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, return false; } - @Override - public void dropItem(Vector position, BaseItemStack item) { - if (getWorld() != null) { - getWorld().dropItem(position, item); - } - } +// public void dropItem(BlockVector3 position, BaseItemStack item) { +// if (getWorld() != null) { +// getWorld().dropItem(position, item); +// } +// } @Override - public void simulateBlockMine(Vector position) { + public void simulateBlockMine(BlockVector3 position) { TaskManager.IMP.sync((Supplier) () -> { world.simulateBlockMine(position); return null; }); } - public boolean generateTree(TreeGenerator.TreeType type, Vector position) { + public boolean generateTree(TreeGenerator.TreeType type, BlockVector3 position) { return generateTree(type, this, position); } @Override - public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, Vector position) { + public boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) { if (getWorld() != null) { try { return getWorld().generateTree(type, editSession, position); @@ -3374,5 +3532,24 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue, world.setWeather(weatherType, duration); } + @Override + public void dropItem(Vector3 position, BaseItemStack item) { + world.dropItem(position, item); + } + + @Override + public boolean playEffect(Vector3 position, int type, int data) { + return world.playEffect(position, type, data); + } + + @Override + public boolean notifyAndLightBlock(BlockVector3 position, BlockState previousType) throws WorldEditException { + return world.notifyAndLightBlock(position, previousType); + } + + @Override + public BlockVector3 getSpawnPosition() { + return world.getSpawnPosition(); + } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/LocalConfiguration.java b/worldedit-core/src/main/java/com/sk89q/worldedit/LocalConfiguration.java index f9d8a088d..d1902be8b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/LocalConfiguration.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/LocalConfiguration.java @@ -1,88 +1,177 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit; - -import com.sk89q.worldedit.util.logging.LogFormat; -import com.sk89q.worldedit.world.block.BlockType; -import com.sk89q.worldedit.world.block.BlockTypes; -import com.sk89q.worldedit.world.item.ItemTypes; -import com.sk89q.worldedit.world.registry.LegacyMapper; -import com.sk89q.worldedit.world.snapshot.SnapshotRepository; - -import java.io.File; -import java.util.HashSet; -import java.util.Set; - -/** - * Represents WorldEdit's configuration. - */ -public abstract class LocalConfiguration { - protected static final String[] defaultDisallowedBlocks = new String[] {}; - - public boolean profile = false; - public Set disallowedBlocks = new HashSet<>(); - public int defaultChangeLimit = -1; - public int maxChangeLimit = -1; - public int defaultMaxPolygonalPoints = -1; - public int maxPolygonalPoints = 20; - public int defaultMaxPolyhedronPoints = -1; - public int maxPolyhedronPoints = 20; - public String shellSaveType = ""; - public SnapshotRepository snapshotRepo = null; - public int maxRadius = -1; - public int maxSuperPickaxeSize = 5; - public int maxBrushRadius = 100; - public boolean logCommands = false; - public String logFile = ""; - public String logFormat = LogFormat.DEFAULT_FORMAT; - public boolean registerHelp = true; // what is the point of this, it's not even used - public ItemTypes wandItem = ItemTypes.WOODEN_AXE; - public boolean superPickaxeDrop = true; - public boolean superPickaxeManyDrop = true; - public boolean noDoubleSlash = false; - public boolean useInventory = false; - public boolean useInventoryOverride = false; - public boolean useInventoryCreativeOverride = false; - public boolean navigationUseGlass = true; - public ItemTypes navigationWand = ItemTypes.COMPASS; - public int navigationWandMaxDistance = 50; - public int scriptTimeout = 3000; - public Set allowedDataCycleBlocks = new HashSet<>(); - public String saveDir = "schematics"; - public String scriptsDir = "craftscripts"; - public boolean showHelpInfo = true; - public int butcherDefaultRadius = -1; - public int butcherMaxRadius = -1; - public boolean allowSymlinks = false; - - /** - * Load the configuration. - */ - public abstract void load(); - - /** - * Get the working directory to work from. - * - * @return a working directory - */ - public File getWorkingDirectory() { - return new File("."); - } -} +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit; + +import com.google.common.collect.Lists; +import com.sk89q.worldedit.util.logging.LogFormat; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.world.registry.LegacyMapper; +import com.sk89q.worldedit.world.snapshot.SnapshotRepository; + +import java.io.File; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +/** + * Represents WorldEdit's configuration. + */ +public abstract class LocalConfiguration { + + public boolean profile = false; + public Set disallowedBlocks = new HashSet<>(); + public int defaultChangeLimit = -1; + public int maxChangeLimit = -1; + public int defaultMaxPolygonalPoints = -1; + public int maxPolygonalPoints = 20; + public int defaultMaxPolyhedronPoints = -1; + public int maxPolyhedronPoints = 20; + public String shellSaveType = ""; + public SnapshotRepository snapshotRepo = null; + public int maxRadius = -1; + public int maxSuperPickaxeSize = 5; + public int maxBrushRadius = 6; + public boolean logCommands = false; + public String logFile = ""; + public String logFormat = LogFormat.DEFAULT_FORMAT; + public boolean registerHelp = true; // what is the point of this, it's not even used + public String wandItem = "minecraft:wooden_axe"; + public boolean superPickaxeDrop = true; + public boolean superPickaxeManyDrop = true; + public boolean noDoubleSlash = false; + public boolean useInventory = false; + public boolean useInventoryOverride = false; + public boolean useInventoryCreativeOverride = false; + public boolean navigationUseGlass = true; + public String navigationWand = "minecraft:compass"; + public int navigationWandMaxDistance = 50; + public int scriptTimeout = 3000; + public Set allowedDataCycleBlocks = new HashSet<>(); + public String saveDir = "schematics"; + public String scriptsDir = "craftscripts"; + public boolean showHelpInfo = true; + public int butcherDefaultRadius = -1; + public int butcherMaxRadius = -1; + public boolean allowSymlinks = false; + public boolean serverSideCUI = true; + + protected String[] getDefaultDisallowedBlocks() { + List blockTypes = Lists.newArrayList( +// BlockTypes.OAK_SAPLING, +// BlockTypes.JUNGLE_SAPLING, +// BlockTypes.DARK_OAK_SAPLING, +// BlockTypes.SPRUCE_SAPLING, +// BlockTypes.BIRCH_SAPLING, +// BlockTypes.ACACIA_SAPLING, +// BlockTypes.BLACK_BED, +// BlockTypes.BLUE_BED, +// BlockTypes.BROWN_BED, +// BlockTypes.CYAN_BED, +// BlockTypes.GRAY_BED, +// BlockTypes.GREEN_BED, +// BlockTypes.LIGHT_BLUE_BED, +// BlockTypes.LIGHT_GRAY_BED, +// BlockTypes.LIME_BED, +// BlockTypes.MAGENTA_BED, +// BlockTypes.ORANGE_BED, +// BlockTypes.PINK_BED, +// BlockTypes.PURPLE_BED, +// BlockTypes.RED_BED, +// BlockTypes.WHITE_BED, +// BlockTypes.YELLOW_BED, +// BlockTypes.POWERED_RAIL, +// BlockTypes.DETECTOR_RAIL, +// BlockTypes.GRASS, +// BlockTypes.DEAD_BUSH, +// BlockTypes.MOVING_PISTON, +// BlockTypes.PISTON_HEAD, +// BlockTypes.SUNFLOWER, +// BlockTypes.ROSE_BUSH, +// BlockTypes.DANDELION, +// BlockTypes.POPPY, +// BlockTypes.BROWN_MUSHROOM, +// BlockTypes.RED_MUSHROOM, +// BlockTypes.TNT, +// BlockTypes.TORCH, +// BlockTypes.FIRE, +// BlockTypes.REDSTONE_WIRE, +// BlockTypes.WHEAT, +// BlockTypes.POTATOES, +// BlockTypes.CARROTS, +// BlockTypes.MELON_STEM, +// BlockTypes.PUMPKIN_STEM, +// BlockTypes.BEETROOTS, +// BlockTypes.RAIL, +// BlockTypes.LEVER, +// BlockTypes.REDSTONE_TORCH, +// BlockTypes.REDSTONE_WALL_TORCH, +// BlockTypes.REPEATER, +// BlockTypes.COMPARATOR, +// BlockTypes.STONE_BUTTON, +// BlockTypes.BIRCH_BUTTON, +// BlockTypes.ACACIA_BUTTON, +// BlockTypes.DARK_OAK_BUTTON, +// BlockTypes.JUNGLE_BUTTON, +// BlockTypes.OAK_BUTTON, +// BlockTypes.SPRUCE_BUTTON, +// BlockTypes.CACTUS, +// BlockTypes.SUGAR_CANE, +// // ores and stuff +// BlockTypes.BEDROCK + ); + return blockTypes.stream().filter(Objects::nonNull).map(BlockType::getId).toArray(String[]::new); + } + + /** + * Load the configuration. + */ + public abstract void load(); + + /** + * Get the working directory to work from. + * + * @return a working directory + */ + public File getWorkingDirectory() { + return new File("."); + } + + public String convertLegacyItem(String legacy) { + String item = legacy; + try { + String[] splitter = item.split(":", 2); + int id = 0; + byte data = 0; + if (splitter.length == 1) { + id = Integer.parseInt(item); + } else { + id = Integer.parseInt(splitter[0]); + data = Byte.parseByte(splitter[1]); + } + item = LegacyMapper.getInstance().getItemFromLegacy(id, data).getId(); + } catch (Throwable e) { + } + + return item; + } + +} 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 04c438305..a4cefa188 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/LocalSession.java @@ -20,7 +20,6 @@ package com.sk89q.worldedit; import com.boydti.fawe.Fawe; -import com.boydti.fawe.FaweCache; import com.boydti.fawe.config.Settings; import com.boydti.fawe.object.FaweInputStream; import com.boydti.fawe.object.FaweLimit; @@ -40,8 +39,9 @@ import com.sk89q.jchronic.Chronic; import com.sk89q.jchronic.Options; import com.sk89q.jchronic.utils.Span; import com.sk89q.jchronic.utils.Time; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.jnbt.IntTag; +import com.sk89q.jnbt.Tag; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.command.tool.*; @@ -49,12 +49,13 @@ import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.function.mask.Mask; -import com.sk89q.worldedit.function.mask.Masks; import com.sk89q.worldedit.function.operation.ChangeSetExecutor; import com.sk89q.worldedit.history.changeset.ChangeSet; import com.sk89q.worldedit.internal.cui.CUIEvent; import com.sk89q.worldedit.internal.cui.CUIRegion; import com.sk89q.worldedit.internal.cui.SelectionShapeEvent; +import com.sk89q.worldedit.internal.cui.ServerCUIHandler; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.regions.selector.CuboidRegionSelector; @@ -63,7 +64,6 @@ import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.world.World; -import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemTypes; import com.sk89q.worldedit.world.snapshot.Snapshot; @@ -128,16 +128,17 @@ public class LocalSession implements TextureHolder { private transient TextureUtil texture; private transient ResettableExtent transform = null; private transient TimeZone timezone = TimeZone.getDefault(); - private transient World currentWorld; private transient UUID uuid; private transient volatile long historySize = 0; private transient VirtualWorld virtual; + private transient BlockVector3 cuiTemporaryBlock; // Saved properties private String lastScript; private RegionSelectorType defaultSelector; + private boolean useServerCUI = false; // Save this to not annoy players. /** * Construct the object. @@ -870,10 +871,10 @@ public class LocalSession implements TextureHolder { * @return the position to use * @throws IncompleteRegionException thrown if a region is not fully selected */ - public Vector getPlacementPosition(Player player) throws IncompleteRegionException { + public BlockVector3 getPlacementPosition(Player player) throws IncompleteRegionException { checkNotNull(player); if (!placeAtPos1) { - return player.getBlockIn(); + return player.getBlockIn().toBlockPoint(); } return selector.getPrimaryPosition(); @@ -1025,12 +1026,12 @@ public class LocalSession implements TextureHolder { } public void setTool(BaseItem item, @Nullable Tool tool, Player player) throws InvalidToolBindException { - ItemTypes type = item.getType(); + ItemType type = item.getType(); if (type.hasBlockType() && type.getBlockType().getMaterial().isAir()) { throw new InvalidToolBindException(type, "Blocks can't be used"); - } else if (type == config.wandItem) { + } else if (type.getId().equalsIgnoreCase(config.wandItem)) { throw new InvalidToolBindException(type, "Already used for the wand"); - } else if (type == config.navigationWand) { + } else if (type.getId().equalsIgnoreCase(config.navigationWand)) { throw new InvalidToolBindException(type, "Already used for the navigation wand"); } Tool previous; @@ -1105,6 +1106,62 @@ public class LocalSession implements TextureHolder { public void tellVersion(Actor player) { } + + public boolean shouldUseServerCUI() { + return this.useServerCUI; + } + + public void setUseServerCUI(boolean useServerCUI) { + this.useServerCUI = useServerCUI; + setDirty(); + } + + /** + * Update server-side WorldEdit CUI. + * + * @param actor The player + */ + public void updateServerCUI(Actor actor) { + if (!actor.isPlayer()) { + return; // This is for players only. + } + + if (!config.serverSideCUI) { + return; // Disabled in config. + } + + Player player = (Player) actor; + + if (!useServerCUI || hasCUISupport) { + if (cuiTemporaryBlock != null) { + player.sendFakeBlock(cuiTemporaryBlock, null); + cuiTemporaryBlock = null; + } + return; // If it's not enabled, ignore this. + } + + BaseBlock block = ServerCUIHandler.createStructureBlock(player); + if (block != null) { + // If it's null, we don't need to do anything. The old was already removed. + Map tags = block.getNbtData().getValue(); + BlockVector3 tempCuiTemporaryBlock = BlockVector3.at( + ((IntTag) tags.get("x")).getValue(), + ((IntTag) tags.get("y")).getValue(), + ((IntTag) tags.get("z")).getValue() + ); + if (cuiTemporaryBlock != null && !tempCuiTemporaryBlock.equals(cuiTemporaryBlock)) { + // Update the existing block if it's the same location + player.sendFakeBlock(cuiTemporaryBlock, null); + } + cuiTemporaryBlock = tempCuiTemporaryBlock; + player.sendFakeBlock(cuiTemporaryBlock, block); + } else if (cuiTemporaryBlock != null) { + // Remove the old block + player.sendFakeBlock(cuiTemporaryBlock, null); + cuiTemporaryBlock = null; + } + } + /** * Dispatch a CUI event but only if the actor has CUI support. * @@ -1141,6 +1198,12 @@ public class LocalSession implements TextureHolder { */ public void dispatchCUISelection(Actor actor) { checkNotNull(actor); + + if (!hasCUISupport && useServerCUI) { + updateServerCUI(actor); + return; + } + if (selector instanceof CUIRegion) { CUIRegion tempSel = (CUIRegion) selector; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/MutableBlockVector.java b/worldedit-core/src/main/java/com/sk89q/worldedit/MutableBlockVector.java deleted file mode 100644 index afb087087..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/MutableBlockVector.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.sk89q.worldedit; - -import com.boydti.fawe.util.MathMan; -import java.io.IOException; -import java.io.Serializable; - -public class MutableBlockVector extends BlockVector implements Serializable { - private transient int x, y, z; - - private static ThreadLocal MUTABLE_CACHE = new ThreadLocal() { - @Override - protected MutableBlockVector initialValue() { - return new MutableBlockVector(); - } - }; - - public static MutableBlockVector get(int x, int y, int z) { - return MUTABLE_CACHE.get().setComponents(x, y, z); - } - - public MutableBlockVector(Vector v) { - this(v.getBlockX(), v.getBlockY(), v.getBlockZ()); - } - - public MutableBlockVector(int x, int y, int z) { - super(0, 0, 0); - this.x = x; - this.y = y; - this.z = z; - } - - public MutableBlockVector() { - super(0, 0, 0); - } - - public MutableBlockVector setComponents(Vector other) { - return setComponents(other.getBlockX(), other.getBlockY(), other.getBlockZ()); - } - - @Override - public MutableBlockVector setComponents(double x, double y, double z) { - return this.setComponents((int) x, (int) y, (int) z); - } - - @Override - public MutableBlockVector setComponents(int x, int y, int z) { - this.mutX(x); - this.mutY(y); - this.mutZ(z); - return this; - } - - @Override - public final void mutX(double x) { - this.x = MathMan.roundInt(x); - } - - @Override - public final void mutY(double y) { - this.y = MathMan.roundInt(y); - } - - @Override - public final void mutZ(double z) { - this.z = MathMan.roundInt(z); - } - - @Override - public final void mutX(int x) { - this.x = x; - } - - @Override - public final void mutY(int y) { - this.y = y; - } - - @Override - public final void mutZ(int z) { - this.z = z; - } - - @Override - public final double getX() { - return x; - } - - @Override - public final double getY() { - return y; - } - - @Override - public final double getZ() { - return z; - } - - @Override - public int getBlockX() { - return this.x; - } - - @Override - public int getBlockY() { - return this.y; - } - - @Override - public int getBlockZ() { - return this.z; - } - - private void writeObject(java.io.ObjectOutputStream stream) throws IOException { - stream.writeInt(x); - stream.writeByte((byte) y); - stream.writeInt(z); - } - - private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { - this.x = stream.readInt(); - this.y = stream.readByte() & 0xFF; - this.z = stream.readInt(); - } -} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/MutableBlockVector2D.java b/worldedit-core/src/main/java/com/sk89q/worldedit/MutableBlockVector2D.java deleted file mode 100644 index 4141fd6ba..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/MutableBlockVector2D.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.sk89q.worldedit; - -import java.io.IOException; -import java.io.Serializable; - -public final class MutableBlockVector2D extends BlockVector2D implements Serializable { - private static ThreadLocal MUTABLE_CACHE = new ThreadLocal() { - @Override - protected MutableBlockVector2D initialValue() { - return new MutableBlockVector2D(); - } - }; - - public static MutableBlockVector2D get(int x, int z) { - return MUTABLE_CACHE.get().setComponents(x, z); - } - - private transient int x, z; - - public MutableBlockVector2D() { - super(0, 0); - this.x = 0; - this.z = 0; - } - - @Override - public double getX() { - return x; - } - - @Override - public double getZ() { - return z; - } - - @Override - public int getBlockX() { - return x; - } - - @Override - public int getBlockZ() { - return z; - } - - public MutableBlockVector2D setComponents(int x, int z) { - this.x = x; - this.z = z; - return this; - } - - public MutableBlockVector2D setComponents(double x, double z) { - return setComponents((int) x, (int) z); - } - - public final void mutX(int x) { - this.x = x; - } - - public void mutZ(int z) { - this.z = z; - } - - public final void mutX(double x) { - this.x = (int) x; - } - - public void mutZ(double z) { - this.z = (int) z; - } - - private void writeObject(java.io.ObjectOutputStream stream) throws IOException { - stream.writeInt(x); - stream.writeInt(z); - } - - private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { - this.x = stream.readInt(); - this.z = stream.readInt(); - } - - public MutableBlockVector2D nextPosition() { - int absX = Math.abs(x); - int absY = Math.abs(z); - if (absX > absY) { - if (x > 0) { - return setComponents(x, z + 1); - } else { - return setComponents(x, z - 1); - } - } else if (absY > absX) { - if (z > 0) { - return setComponents(x - 1, z); - } else { - return setComponents(x + 1, z); - } - } else { - if (x == z && x > 0) { - return setComponents(x, z + 1); - } - if (x == absX) { - return setComponents(x, z + 1); - } - if (z == absY) { - return setComponents(x, z - 1); - } - return setComponents(x + 1, z); - } - } -} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/PlayerDirection.java b/worldedit-core/src/main/java/com/sk89q/worldedit/PlayerDirection.java deleted file mode 100644 index 2a82fea88..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/PlayerDirection.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit; - -import com.sk89q.worldedit.util.Direction; - -/** - * The player's direction. - * - *

In the future, this class will be replaced with {@link Direction}.

- */ -public enum PlayerDirection { - - NORTH(new Vector(0, 0, -1), true), - NORTH_EAST((new Vector(1, 0, -1)).normalize(), false), - EAST(new Vector(1, 0, 0), true), - SOUTH_EAST((new Vector(1, 0, 1)).normalize(), false), - SOUTH(new Vector(0, 0, 1), true), - SOUTH_WEST((new Vector(-1, 0, 1)).normalize(), false), - WEST(new Vector(-1, 0, 0), true), - NORTH_WEST((new Vector(-1, 0, -1)).normalize(), false), - UP(new Vector(0, 1, 0), true), - DOWN(new Vector(0, -1, 0), true); - - private final Vector dir; - private final boolean isOrthogonal; - - PlayerDirection(Vector vec, boolean isOrthogonal) { - this.dir = vec; - this.isOrthogonal = isOrthogonal; - } - - public Vector vector() { - return dir; - } - - public boolean isOrthogonal() { - return isOrthogonal; - } - -} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/Vector.java b/worldedit-core/src/main/java/com/sk89q/worldedit/Vector.java deleted file mode 100644 index 7dc557852..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/Vector.java +++ /dev/null @@ -1,916 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit; - -import com.boydti.fawe.util.MathMan; -import com.sk89q.worldedit.math.transform.AffineTransform; - -import java.io.IOException; -import java.io.Serializable; -import javax.annotation.Nullable; - -/** - * An immutable 3-dimensional vector. - */ -public class Vector extends Vector2D implements Comparable, Serializable { - - public static final Vector ZERO = new Vector(0, 0, 0); - public static final Vector UNIT_X = new Vector(1, 0, 0); - public static final Vector UNIT_Y = new Vector(0, 1, 0); - public static final Vector UNIT_Z = new Vector(0, 0, 1); - public static final Vector ONE = new Vector(1, 1, 1); - - private transient double y; - - /** - * Construct an instance. - * - * @param x the X coordinate - * @param y the Y coordinate - * @param z the Z coordinate - */ - public Vector(double x, double y, double z) { - this.mutX(x); - this.mutY(y); - this.mutZ(z); - } - - /** - * Construct an instance. - * - * @param x the X coordinate - * @param y the Y coordinate - * @param z the Z coordinate - */ - public Vector(int x, int y, int z) { - this.mutX(x); - this.mutY(y); - this.mutZ(z); - } - - /** - * Construct an instance. - * - * @param x the X coordinate - * @param y the Y coordinate - * @param z the Z coordinate - */ - public Vector(float x, float y, float z) { - this.mutX(x); - this.mutY(y); - this.mutZ(z); - } - - /** - * Copy another vector. - * - * @param other another vector to make a copy of - */ - public Vector(Vector other) { - this.mutX(other.getX()); - this.mutY(other.getY()); - this.mutZ(other.getZ()); - } - - public Vector(double[] arr) { - this.mutX(arr[0]); - this.mutY(arr[1]); - this.mutZ(arr[2]); - } - - /** - * Construct a new instance with X, Y, and Z coordinates set to 0. - * - *

One can also refer to a static {@link #ZERO}.

- */ - public Vector() { - this.mutX(0); - this.mutY(0); - this.mutZ(0); - } - - public Vector setComponents(int x, int y, int z) { - this.mutX(x); - this.mutY(y); - this.mutZ(z); - return this; - } - - public Vector setComponents(double x, double y, double z) { - this.mutX(x); - this.mutY(y); - this.mutZ(z); - return this; - } - - public void mutX(int x) { - this.x = x; - } - - public void mutY(int y) { - this.y = y; - } - - public void mutZ(int z) { - this.z = z; - } - - public void mutX(double x) { - this.x = x; - } - - public void mutY(double y) { - this.y = y; - } - - public void mutZ(double z) { - this.z = z; - } - - /** - * Get the X coordinate. - * - * @return the x coordinate - */ - public double getX() { - return x; - } - - /** - * Get the X coordinate rounded. - * - * @return the x coordinate - */ - public int getBlockX() { - return MathMan.roundInt(getX()); - } - - /** - * Set the X coordinate. - * - * @param x the new X - * @return a new vector - */ - public Vector setX(double x) { - return new Vector(x, getY(), getZ()); - } - - /** - * Set the X coordinate. - * - * @param x the X coordinate - * @return new vector - */ - public Vector setX(int x) { - return new Vector(x, getY(), getZ()); - } - - /** - * Get the Y coordinate. - * - * @return the y coordinate - */ - public double getY() { - return y; - } - - /** - * Get the Y coordinate rounded. - * - * @return the y coordinate - */ - public int getBlockY() { - return MathMan.roundInt(getY()); - } - - /** - * Set the Y coordinate. - * - * @param y the new Y - * @return a new vector - */ - public Vector setY(double y) { - return new Vector(getX(), y, getZ()); - } - - /** - * Set the Y coordinate. - * - * @param y the new Y - * @return a new vector - */ - public Vector setY(int y) { - return new Vector(getX(), y, getZ()); - } - - /** - * Get the Z coordinate. - * - * @return the z coordinate - */ - public double getZ() { - return z; - } - - /** - * Get the Z coordinate rounded. - * - * @return the z coordinate - */ - public int getBlockZ() { - return MathMan.roundInt(getZ()); - } - - /** - * Set the Z coordinate. - * - * @param z the new Z - * @return a new vector - */ - public Vector setZ(double z) { - return new Vector(getX(), getY(), z); - } - - /** - * Set the Z coordinate. - * - * @param z the new Z - * @return a new vector - */ - public Vector setZ(int z) { - return new Vector(getX(), getY(), z); - } - - /** - * Add another vector to this vector and return the result as a new vector. - * - * @param other the other vector - * @return a new vector - */ - public Vector add(Vector other) { - return new Vector(getX() + other.getX(), getY() + other.getY(), getZ() + other.getZ()); - } - - /** - * Add another vector to this vector and return the result as a new vector. - * - * @param x the value to add - * @param y the value to add - * @param z the value to add - * @return a new vector - */ - public Vector add(double x, double y, double z) { - return new Vector(this.getX() + x, this.getY() + y, this.getZ() + z); - } - - /** - * Add another vector to this vector and return the result as a new vector. - * - * @param x the value to add - * @param y the value to add - * @param z the value to add - * @return a new vector - */ - public Vector add(int x, int y, int z) { - return new Vector(this.getX() + x, this.getY() + y, this.getZ() + z); - } - - /** - * Add a list of vectors to this vector and return the - * result as a new vector. - * - * @param others an array of vectors - * @return a new vector - */ - public Vector add(Vector... others) { - double newX = getX(), newY = getY(), newZ = getZ(); - - for (Vector other : others) { - newX += other.getX(); - newY += other.getY(); - newZ += other.getZ(); - } - - return new Vector(newX, newY, newZ); - } - - /** - * Subtract another vector from this vector and return the result - * as a new vector. - * - * @param other the other vector - * @return a new vector - */ - public Vector subtract(Vector other) { - return new Vector(getX() - other.getX(), getY() - other.getY(), getZ() - other.getZ()); - } - - /** - * Subtract another vector from this vector and return the result - * as a new vector. - * - * @param x the value to subtract - * @param y the value to subtract - * @param z the value to subtract - * @return a new vector - */ - public Vector subtract(double x, double y, double z) { - return new Vector(this.getX() - x, this.getY() - y, this.getZ() - z); - } - - /** - * Subtract another vector from this vector and return the result - * as a new vector. - * - * @param x the value to subtract - * @param y the value to subtract - * @param z the value to subtract - * @return a new vector - */ - public Vector subtract(int x, int y, int z) { - return new Vector(this.getX() - x, this.getY() - y, this.getZ() - z); - } - - /** - * Subtract a list of vectors from this vector and return the result - * as a new vector. - * - * @param others an array of vectors - * @return a new vector - */ - public Vector subtract(Vector... others) { - double newX = getX(), newY = getY(), newZ = getZ(); - - for (Vector other : others) { - newX -= other.getX(); - newY -= other.getY(); - newZ -= other.getZ(); - } - - return new Vector(newX, newY, newZ); - } - - /** - * Multiply this vector by another vector on each component. - * - * @param other the other vector - * @return a new vector - */ - public Vector multiply(Vector other) { - return new Vector(getX() * other.getX(), getY() * other.getY(), getZ() * other.getZ()); - } - - /** - * Multiply this vector by another vector on each component. - * - * @param x the value to multiply - * @param y the value to multiply - * @param z the value to multiply - * @return a new vector - */ - public Vector multiply(double x, double y, double z) { - return new Vector(this.getX() * x, this.getY() * y, this.getZ() * z); - } - - /** - * Multiply this vector by another vector on each component. - * - * @param x the value to multiply - * @param y the value to multiply - * @param z the value to multiply - * @return a new vector - */ - public Vector multiply(int x, int y, int z) { - return new Vector(this.getX() * x, this.getY() * y, this.getZ() * z); - } - - /** - * Multiply this vector by zero or more vectors on each component. - * - * @param others an array of vectors - * @return a new vector - */ - public Vector multiply(Vector... others) { - double newX = getX(), newY = getY(), newZ = getZ(); - - for (Vector other : others) { - newX *= other.getX(); - newY *= other.getY(); - newZ *= other.getZ(); - } - - return new Vector(newX, newY, newZ); - } - - /** - * Perform scalar multiplication and return a new vector. - * - * @param n the value to multiply - * @return a new vector - */ - public Vector multiply(double n) { - return new Vector(this.getX() * n, this.getY() * n, this.getZ() * n); - } - - /** - * Perform scalar multiplication and return a new vector. - * - * @param n the value to multiply - * @return a new vector - */ - public Vector multiply(float n) { - return new Vector(this.getX() * n, this.getY() * n, this.getZ() * n); - } - - /** - * Perform scalar multiplication and return a new vector. - * - * @param n the value to multiply - * @return a new vector - */ - public Vector multiply(int n) { - return new Vector(this.getX() * n, this.getY() * n, this.getZ() * n); - } - - /** - * Divide this vector by another vector on each component. - * - * @param other the other vector - * @return a new vector - */ - public Vector divide(Vector other) { - return new Vector(getX() / other.getX(), getY() / other.getY(), getZ() / other.getZ()); - } - - /** - * Divide this vector by another vector on each component. - * - * @param x the value to divide by - * @param y the value to divide by - * @param z the value to divide by - * @return a new vector - */ - public Vector divide(double x, double y, double z) { - return new Vector(this.getX() / x, this.getY() / y, this.getZ() / z); - } - - /** - * Divide this vector by another vector on each component. - * - * @param x the value to divide by - * @param y the value to divide by - * @param z the value to divide by - * @return a new vector - */ - public Vector divide(int x, int y, int z) { - return new Vector(this.getX() / x, this.getY() / y, this.getZ() / z); - } - - /** - * Perform scalar division and return a new vector. - * - * @param n the value to divide by - * @return a new vector - */ - public Vector divide(int n) { - return new Vector(getX() / n, getY() / n, getZ() / n); - } - - /** - * Perform scalar division and return a new vector. - * - * @param n the value to divide by - * @return a new vector - */ - public Vector divide(double n) { - return new Vector(getX() / n, getY() / n, getZ() / n); - } - - /** - * Perform scalar division and return a new vector. - * - * @param n the value to divide by - * @return a new vector - */ - public Vector divide(float n) { - return new Vector(getX() / n, getY() / n, getZ() / n); - } - - /** - * Get the length of the vector. - * - * @return length - */ - public double length() { - return Math.sqrt(getX() * getX() + getY() * getY() + getZ() * getZ()); - } - - /** - * Get the length, squared, of the vector. - * - * @return length, squared - */ - public double lengthSq() { - return getX() * getX() + getY() * getY() + getZ() * getZ(); - } - - public double volume() { - return getX() * getY() * getZ(); - } - - /** - * Get the distance between this vector and another vector. - * - * @param other the other vector - * @return distance - */ - public double distance(Vector other) { - return Math.sqrt(Math.pow(other.getX() - getX(), 2) + - Math.pow(other.getY() - getY(), 2) + - Math.pow(other.getZ() - getZ(), 2)); - } - - /** - * Get the distance between this vector and another vector, squared. - * - * @param other the other vector - * @return distance - */ - public double distanceSq(Vector other) { - return Math.pow(other.getX() - getX(), 2) + - Math.pow(other.getY() - getY(), 2) + - Math.pow(other.getZ() - getZ(), 2); - } - - /** - * Get the normalized vector, which is the vector divided by its - * length, as a new vector. - * - * @return a new vector - */ - public Vector normalize() { - return divide(length()); - } - - /** - * Gets the dot product of this and another vector. - * - * @param other the other vector - * @return the dot product of this and the other vector - */ - public double dot(Vector other) { - return getX() * other.getX() + getY() * other.getY() + getZ() * other.getZ(); - } - - /** - * Gets the cross product of this and another vector. - * - * @param other the other vector - * @return the cross product of this and the other vector - */ - public Vector cross(Vector other) { - return new Vector( - getY() * other.getZ() - getZ() * other.getY(), - getZ() * other.getX() - getX() * other.getZ(), - getX() * other.getY() - getY() * other.getX() - ); - } - - /** - * Checks to see if a vector is contained with another. - * - * @param min the minimum point (X, Y, and Z are the lowest) - * @param max the maximum point (X, Y, and Z are the lowest) - * @return true if the vector is contained - */ - public boolean containedWithin(Vector min, Vector max) { - return getX() >= min.getX() && getX() <= max.getX() && getY() >= min.getY() && getY() <= max.getY() && getZ() >= min.getZ() && getZ() <= max.getZ(); - } - - /** - * Checks to see if a vector is contained with another, comparing - * using discrete comparisons, inclusively. - * - * @param min the minimum point (X, Y, and Z are the lowest) - * @param max the maximum point (X, Y, and Z are the lowest) - * @return true if the vector is contained - */ - public boolean containedWithinBlock(Vector min, Vector max) { - return getBlockX() >= min.getBlockX() && getBlockX() <= max.getBlockX() - && getBlockY() >= min.getBlockY() && getBlockY() <= max.getBlockY() - && getBlockZ() >= min.getBlockZ() && getBlockZ() <= max.getBlockZ(); - } - - /** - * Clamp the Y component. - * - * @param min the minimum value - * @param max the maximum value - * @return a new vector - */ - public Vector clampY(int min, int max) { - return new Vector(getX(), Math.max(min, Math.min(max, getY())), getZ()); - } - - /** - * Floors the values of all components. - * - * @return a new vector - */ - public Vector floor() { - return new Vector(Math.floor(getX()), Math.floor(getY()), Math.floor(getZ())); - } - - /** - * Rounds all components up. - * - * @return a new vector - */ - public Vector ceil() { - return new Vector(Math.ceil(getX()), Math.ceil(getY()), Math.ceil(getZ())); - } - - /** - * Rounds all components to the closest integer. - * - *

Components < 0.5 are rounded down, otherwise up.

- * - * @return a new vector - */ - public Vector round() { - return new Vector(Math.floor(getX() + 0.5), Math.floor(getY() + 0.5), Math.floor(getZ() + 0.5)); - } - - /** - * Returns a vector with the absolute values of the components of - * this vector. - * - * @return a new vector - */ - public Vector positive() { - return new Vector(Math.abs(getX()), Math.abs(getY()), Math.abs(getZ())); - } - - /** - * Perform a 2D transformation on this vector and return a new one. - * - * @param angle in degrees - * @param aboutX about which x coordinate to rotate - * @param aboutZ about which z coordinate to rotate - * @param translateX what to add after rotation - * @param translateZ what to add after rotation - * @return a new vector - * @see AffineTransform another method to transform vectors - */ - public Vector transform2D(double angle, double aboutX, double aboutZ, double translateX, double translateZ) { - angle = Math.toRadians(angle); - double x = this.getX() - aboutX; - double z = this.getZ() - aboutZ; - double x2 = x * Math.cos(angle) - z * Math.sin(angle); - double z2 = x * Math.sin(angle) + z * Math.cos(angle); - - return new Vector( - x2 + aboutX + translateX, - getY(), - z2 + aboutZ + translateZ - ); - } - - /** - * Returns whether this vector is collinear with another vector. - * - * @param other the other vector - * @return true if collinear - */ - public boolean isCollinearWith(Vector other) { - if (getX() == 0 && getY() == 0 && getZ() == 0) { - // this is a zero vector - return true; - } - - final double otherX = other.getX(); - final double otherY = other.getY(); - final double otherZ = other.getZ(); - - if (otherX == 0 && otherY == 0 && otherZ == 0) { - // other is a zero vector - return true; - } - - if ((getX() == 0) != (otherX == 0)) return false; - if ((getY() == 0) != (otherY == 0)) return false; - if ((getZ() == 0) != (otherZ == 0)) return false; - - final double quotientX = otherX / getX(); - if (!Double.isNaN(quotientX)) { - return other.equals(multiply(quotientX)); - } - - final double quotientY = otherY / getY(); - if (!Double.isNaN(quotientY)) { - return other.equals(multiply(quotientY)); - } - - final double quotientZ = otherZ / getZ(); - if (!Double.isNaN(quotientZ)) { - return other.equals(multiply(quotientZ)); - } - - throw new RuntimeException("This should not happen"); - } - - /** - * Get this vector's pitch as used within the game. - * - * @return pitch in radians - */ - public float toPitch() { - double x = getX(); - double z = getZ(); - - if (x == 0 && z == 0) { - return getY() > 0 ? -90 : 90; - } else { - double x2 = x * x; - double z2 = z * z; - double xz = Math.sqrt(x2 + z2); - return (float) Math.toDegrees(Math.atan(-getY() / xz)); - } - } - - /** - * Get this vector's yaw as used within the game. - * - * @return yaw in radians - */ - public float toYaw() { - double x = getX(); - double z = getZ(); - - double t = Math.atan2(-x, z); - double _2pi = 2 * Math.PI; - - return (float) Math.toDegrees(((t + _2pi) % _2pi)); - } - - /** - * Create a new {@code BlockVector} using the given components. - * - * @param x the X coordinate - * @param y the Y coordinate - * @param z the Z coordinate - * @return a new {@code BlockVector} - */ - public static BlockVector toBlockPoint(double x, double y, double z) { - return new BlockVector( - Math.floor(x), - Math.floor(y), - Math.floor(z) - ); - } - - /** - * Create a new {@code BlockVector} from this vector. - * - * @return a new {@code BlockVector} - */ - public BlockVector toBlockPoint() { - return new BlockVector( - Math.floor(getX()), - Math.floor(getY()), - Math.floor(getZ()) - ); - } - - /** - * Create a new {@code BlockVector} from this vector. - * - * @return a new {@code BlockVector} - */ - public BlockVector toBlockVector() { - return new BlockVector(this); - } - - /** - * Creates a 2D vector by dropping the Y component from this vector. - * - * @return a new {@code Vector2D} - */ - public Vector2D toVector2D() { - return new Vector2D(getX(), getZ()); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) return true; - if (!(obj instanceof Vector)) { - return false; - } - - Vector other = (Vector) obj; - return other.getX() == this.getX() && other.getZ() == this.getZ() && other.getY() == this.getY(); - } - - @Override - public int compareTo(@Nullable Vector other) { - if (other == null) { - throw new IllegalArgumentException("null not supported"); - } - if (getY() != other.getY()) return Double.compare(getY(), other.getY()); - if (getZ() != other.getZ()) return Double.compare(getZ(), other.getZ()); - if (getX() != other.getX()) return Double.compare(getX(), other.getX()); - return 0; - } - - @Override - public int hashCode() { - return ((int) getX() ^ ((int) getZ() << 16)) ^ ((int) getY() << 30); - } - - @Override - public String toString() { - String x = (getX() == getBlockX() ? "" + getBlockX() : "" + getX()); - String y = (getY() == getBlockY() ? "" + getBlockY() : "" + getY()); - String z = (getZ() == getBlockZ() ? "" + getBlockZ() : "" + getZ()); - return "(" + x + ", " + y + ", " + z + ")"; - } - - /** - * Gets the minimum components of two vectors. - * - * @param v1 the first vector - * @param v2 the second vector - * @return minimum - */ - public static Vector getMinimum(Vector v1, Vector v2) { - return new Vector( - Math.min(v1.getX(), v2.getX()), - Math.min(v1.getY(), v2.getY()), - Math.min(v1.getZ(), v2.getZ()) - ); - } - - /** - * Gets the maximum components of two vectors. - * - * @param v1 the first vector - * @param v2 the second vector - * @return maximum - */ - public static Vector getMaximum(Vector v1, Vector v2) { - return new Vector( - Math.max(v1.getX(), v2.getX()), - Math.max(v1.getY(), v2.getY()), - Math.max(v1.getZ(), v2.getZ()) - ); - } - - /** - * Gets the midpoint of two vectors. - * - * @param v1 the first vector - * @param v2 the second vector - * @return maximum - */ - public static Vector getMidpoint(Vector v1, Vector v2) { - return new Vector( - (v1.getX() + v2.getX()) / 2, - (v1.getY() + v2.getY()) / 2, - (v1.getZ() + v2.getZ()) / 2 - ); - } - - private void writeObject(java.io.ObjectOutputStream stream) throws IOException { - if (!(this instanceof MutableBlockVector)) { - stream.writeDouble(x); - stream.writeDouble(y); - stream.writeDouble(z); - } - } - - private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { - if (this instanceof MutableBlockVector) return; - this.x = stream.readDouble(); - this.y = stream.readDouble(); - this.z = stream.readDouble(); - } - - -} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/Vector2D.java b/worldedit-core/src/main/java/com/sk89q/worldedit/Vector2D.java deleted file mode 100644 index b75fdda04..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/Vector2D.java +++ /dev/null @@ -1,681 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit; - -import com.boydti.fawe.util.MathMan; -import com.sk89q.worldedit.math.transform.AffineTransform; -import java.io.IOException; -import java.io.Serializable; - -/** - * An immutable 2-dimensional vector. - */ -public class Vector2D implements Serializable { - public static final Vector2D ZERO = new Vector2D(0, 0); - public static final Vector2D UNIT_X = new Vector2D(1, 0); - public static final Vector2D UNIT_Z = new Vector2D(0, 1); - public static final Vector2D ONE = new Vector2D(1, 1); - - public transient double x, z; - - /** - * Construct an instance. - * - * @param x the X coordinate - * @param z the Z coordinate - */ - public Vector2D(double x, double z) { - this.x = x; - this.z = z; - } - - /** - * Construct an instance. - * - * @param x the X coordinate - * @param z the Z coordinate - */ - public Vector2D(int x, int z) { - this.x = (double) x; - this.z = (double) z; - } - - /** - * Construct an instance. - * - * @param x the X coordinate - * @param z the Z coordinate - */ - public Vector2D(float x, float z) { - this.x = (double) x; - this.z = (double) z; - } - - /** - * Copy another vector. - * - * @param other the other vector - */ - public Vector2D(Vector2D other) { - this.x = other.getX(); - this.z = other.getZ(); - } - - /** - * Construct a new instance with X and Z coordinates set to 0. - * - *

One can also refer to a static {@link #ZERO}.

- */ - public Vector2D() { - this.x = 0; - this.z = 0; - } - - /** - * Get the X coordinate. - * - * @return the x coordinate - */ - public double getX() { - return x; - } - - /** - * Get the X coordinate rounded. - * - * @return the x coordinate - */ - public int getBlockX() { - return MathMan.roundInt(getX()); - } - - /** - * Set the X coordinate. - * - * @param x the new X - * @return a new vector - */ - public Vector2D setX(double x) { - return new Vector2D(x, getZ()); - } - - /** - * Set the X coordinate. - * - * @param x the new X - * @return a new vector - */ - public Vector2D setX(int x) { - return new Vector2D(x, getZ()); - } - - /** - * Get the Z coordinate. - * - * @return the z coordinate - */ - public double getZ() { - return z; - } - - /** - * Get the Z coordinate rounded. - * - * @return the z coordinate - */ - public int getBlockZ() { - return MathMan.roundInt(getZ()); - } - - /** - * Set the Z coordinate. - * - * @param z the new Z - * @return a new vector - */ - public Vector2D setZ(double z) { - return new Vector2D(getX(), z); - } - - /** - * Set the Z coordinate. - * - * @param z the new Z - * @return a new vector - */ - public Vector2D setZ(int z) { - return new Vector2D(getX(), z); - } - - /** - * Add another vector to this vector and return the result as a new vector. - * - * @param other the other vector - * @return a new vector - */ - public Vector2D add(Vector2D other) { - return new Vector2D(getX() + other.getX(), getZ() + other.getZ()); - } - - /** - * Add another vector to this vector and return the result as a new vector. - * - * @param x the value to add - * @param z the value to add - * @return a new vector - */ - public Vector2D add(double x, double z) { - return new Vector2D(this.getX() + x, this.getZ() + z); - } - - /** - * Add another vector to this vector and return the result as a new vector. - * - * @param x the value to add - * @param z the value to add - * @return a new vector - */ - public Vector2D add(int x, int z) { - return new Vector2D(this.getX() + x, this.getZ() + z); - } - - /** - * Add a list of vectors to this vector and return the - * result as a new vector. - * - * @param others an array of vectors - * @return a new vector - */ - public Vector2D add(Vector2D... others) { - double newX = getX(), newZ = getZ(); - - for (Vector2D other : others) { - newX += other.getX(); - newZ += other.getZ(); - } - - return new Vector2D(newX, newZ); - } - - /** - * Subtract another vector from this vector and return the result - * as a new vector. - * - * @param other the other vector - * @return a new vector - */ - public Vector2D subtract(Vector2D other) { - return new Vector2D(getX() - other.getX(), getZ() - other.getZ()); - } - - /** - * Subtract another vector from this vector and return the result - * as a new vector. - * - * @param x the value to subtract - * @param z the value to subtract - * @return a new vector - */ - public Vector2D subtract(double x, double z) { - return new Vector2D(this.getX() - x, this.getZ() - z); - } - - /** - * Subtract another vector from this vector and return the result - * as a new vector. - * - * @param x the value to subtract - * @param z the value to subtract - * @return a new vector - */ - public Vector2D subtract(int x, int z) { - return new Vector2D(this.getX() - x, this.getZ() - z); - } - - /** - * Subtract a list of vectors from this vector and return the result - * as a new vector. - * - * @param others an array of vectors - * @return a new vector - */ - public Vector2D subtract(Vector2D... others) { - double newX = getX(), newZ = getZ(); - - for (Vector2D other : others) { - newX -= other.getX(); - newZ -= other.getZ(); - } - - return new Vector2D(newX, newZ); - } - - /** - * Multiply this vector by another vector on each component. - * - * @param other the other vector - * @return a new vector - */ - public Vector2D multiply(Vector2D other) { - return new Vector2D(getX() * other.getX(), getZ() * other.getZ()); - } - - /** - * Multiply this vector by another vector on each component. - * - * @param x the value to multiply - * @param z the value to multiply - * @return a new vector - */ - public Vector2D multiply(double x, double z) { - return new Vector2D(this.getX() * x, this.getZ() * z); - } - - /** - * Multiply this vector by another vector on each component. - * - * @param x the value to multiply - * @param z the value to multiply - * @return a new vector - */ - public Vector2D multiply(int x, int z) { - return new Vector2D(this.getX() * x, this.getZ() * z); - } - - /** - * Multiply this vector by zero or more vectors on each component. - * - * @param others an array of vectors - * @return a new vector - */ - public Vector2D multiply(Vector2D... others) { - double newX = getX(), newZ = getZ(); - - for (Vector2D other : others) { - newX *= other.getX(); - newZ *= other.getZ(); - } - - return new Vector2D(newX, newZ); - } - - /** - * Perform scalar multiplication and return a new vector. - * - * @param n the value to multiply - * @return a new vector - */ - public Vector2D multiply(double n) { - return new Vector2D(this.getX() * n, this.getZ() * n); - } - - /** - * Perform scalar multiplication and return a new vector. - * - * @param n the value to multiply - * @return a new vector - */ - public Vector2D multiply(float n) { - return new Vector2D(this.getX() * n, this.getZ() * n); - } - - /** - * Perform scalar multiplication and return a new vector. - * - * @param n the value to multiply - * @return a new vector - */ - public Vector2D multiply(int n) { - return new Vector2D(this.getX() * n, this.getZ() * n); - } - - /** - * Divide this vector by another vector on each component. - * - * @param other the other vector - * @return a new vector - */ - public Vector2D divide(Vector2D other) { - return new Vector2D(getX() / other.getX(), getZ() / other.getZ()); - } - - /** - * Divide this vector by another vector on each component. - * - * @param x the value to divide by - * @param z the value to divide by - * @return a new vector - */ - public Vector2D divide(double x, double z) { - return new Vector2D(this.getX() / x, this.getZ() / z); - } - - /** - * Divide this vector by another vector on each component. - * - * @param x the value to divide by - * @param z the value to divide by - * @return a new vector - */ - public Vector2D divide(int x, int z) { - return new Vector2D(this.getX() / x, this.getZ() / z); - } - - /** - * Perform scalar division and return a new vector. - * - * @param n the value to divide by - * @return a new vector - */ - public Vector2D divide(int n) { - return new Vector2D(getX() / n, getZ() / n); - } - - /** - * Perform scalar division and return a new vector. - * - * @param n the value to divide by - * @return a new vector - */ - public Vector2D divide(double n) { - return new Vector2D(getX() / n, getZ() / n); - } - - /** - * Perform scalar division and return a new vector. - * - * @param n the value to divide by - * @return a new vector - */ - public Vector2D divide(float n) { - return new Vector2D(getX() / n, getZ() / n); - } - - /** - * Get the length of the vector. - * - * @return length - */ - public double length() { - return Math.sqrt(getX() * getX() + getZ() * getZ()); - } - - /** - * Get the length, squared, of the vector. - * - * @return length, squared - */ - public double lengthSq() { - return getX() * getX() + getZ() * getZ(); - } - - /** - * Get the distance between this vector and another vector. - * - * @param other the other vector - * @return distance - */ - public double distance(Vector2D other) { - return Math.sqrt(Math.pow(other.getX() - getX(), 2) + Math.pow(other.getZ() - getZ(), 2)); - } - - /** - * Get the distance between this vector and another vector, squared. - * - * @param other the other vector - * @return distance - */ - public double distanceSq(Vector2D other) { - return Math.pow(other.getX() - getX(), 2) + - Math.pow(other.getZ() - getZ(), 2); - } - - /** - * Get the normalized vector, which is the vector divided by its - * length, as a new vector. - * - * @return a new vector - */ - public Vector2D normalize() { - return divide(length()); - } - - /** - * Gets the dot product of this and another vector. - * - * @param other the other vector - * @return the dot product of this and the other vector - */ - public double dot(Vector2D other) { - return getX() * other.getX() + getZ() * other.getZ(); - } - - /** - * Checks to see if a vector is contained with another. - * - * @param min the minimum point (X, Y, and Z are the lowest) - * @param max the maximum point (X, Y, and Z are the lowest) - * @return true if the vector is contained - */ - public boolean containedWithin(Vector2D min, Vector2D max) { - return getX() >= min.getX() && getX() <= max.getX() - && getZ() >= min.getZ() && getZ() <= max.getZ(); - } - - /** - * Checks to see if a vector is contained with another. - * - * @param min the minimum point (X, Y, and Z are the lowest) - * @param max the maximum point (X, Y, and Z are the lowest) - * @return true if the vector is contained - */ - public boolean containedWithinBlock(Vector2D min, Vector2D max) { - return getBlockX() >= min.getBlockX() && getBlockX() <= max.getBlockX() - && getBlockZ() >= min.getBlockZ() && getBlockZ() <= max.getBlockZ(); - } - - /** - * Floors the values of all components. - * - * @return a new vector - */ - public Vector2D floor() { - return new Vector2D(Math.floor(getX()), Math.floor(getZ())); - } - - /** - * Rounds all components up. - * - * @return a new vector - */ - public Vector2D ceil() { - return new Vector2D(Math.ceil(getX()), Math.ceil(getZ())); - } - - /** - * Rounds all components to the closest integer. - * - *

Components < 0.5 are rounded down, otherwise up.

- * - * @return a new vector - */ - public Vector2D round() { - return new Vector2D(Math.floor(getX() + 0.5), Math.floor(getZ() + 0.5)); - } - - /** - * Returns a vector with the absolute values of the components of - * this vector. - * - * @return a new vector - */ - public Vector2D positive() { - return new Vector2D(Math.abs(getX()), Math.abs(getZ())); - } - - /** - * Perform a 2D transformation on this vector and return a new one. - * - * @param angle in degrees - * @param aboutX about which x coordinate to rotate - * @param aboutZ about which z coordinate to rotate - * @param translateX what to add after rotation - * @param translateZ what to add after rotation - * @return a new vector - * @see AffineTransform another method to transform vectors - */ - public Vector2D transform2D(double angle, double aboutX, double aboutZ, double translateX, double translateZ) { - angle = Math.toRadians(angle); - double x = this.getX() - aboutX; - double z = this.getZ() - aboutZ; - double x2 = x * Math.cos(angle) - z * Math.sin(angle); - double z2 = x * Math.sin(angle) + z * Math.cos(angle); - return new Vector2D( - x2 + aboutX + translateX, - z2 + aboutZ + translateZ - ); - } - - /** - * Returns whether this vector is collinear with another vector. - * - * @param other the other vector - * @return true if collinear - */ - public boolean isCollinearWith(Vector2D other) { - if (getX() == 0 && getZ() == 0) { - // this is a zero vector - return true; - } - - final double otherX = other.getX(); - final double otherZ = other.getZ(); - - if (otherX == 0 && otherZ == 0) { - // other is a zero vector - return true; - } - - if ((getX() == 0) != (otherX == 0)) return false; - if ((getZ() == 0) != (otherZ == 0)) return false; - - final double quotientX = otherX / getX(); - if (!Double.isNaN(quotientX)) { - return other.equals(multiply(quotientX)); - } - - final double quotientZ = otherZ / getZ(); - if (!Double.isNaN(quotientZ)) { - return other.equals(multiply(quotientZ)); - } - - throw new RuntimeException("This should not happen"); - } - - /** - * Create a new {@code BlockVector2D} from this vector. - * - * @return a new {@code BlockVector2D} - */ - public BlockVector2D toBlockVector2D() { - return new BlockVector2D(this); - } - - /** - * Creates a 3D vector by adding a zero Y component to this vector. - * - * @return a new vector - */ - public Vector toVector() { - return new Vector(getX(), 0, getZ()); - } - - /** - * Creates a 3D vector by adding the specified Y component to this vector. - * - * @param y the Y component - * @return a new vector - */ - public Vector toVector(double y) { - return new Vector(getX(), y, getZ()); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Vector2D)) { - return false; - } - - Vector2D other = (Vector2D) obj; - return other.getX() == this.getX() && other.getZ() == this.getZ(); - - } - - @Override - public int hashCode() { - return ((new Double(getX())).hashCode() >> 13) ^ - (new Double(getZ())).hashCode(); - } - - @Override - public String toString() { - return "(" + getX() + ", " + getZ() + ")"; - } - - /** - * Gets the minimum components of two vectors. - * - * @param v1 the first vector - * @param v2 the second vector - * @return minimum - */ - public static Vector2D getMinimum(Vector2D v1, Vector2D v2) { - return new Vector2D( - Math.min(v1.getX(), v2.getX()), - Math.min(v1.getZ(), v2.getZ()) - ); - } - - /** - * Gets the maximum components of two vectors. - * - * @param v1 the first vector - * @param v2 the second vector - * @return maximum - */ - public static Vector2D getMaximum(Vector2D v1, Vector2D v2) { - return new Vector2D( - Math.max(v1.getX(), v2.getX()), - Math.max(v1.getZ(), v2.getZ()) - ); - } - - private void writeObject(java.io.ObjectOutputStream stream) throws IOException { - if (this instanceof MutableBlockVector2D) return; - stream.writeDouble(x); - stream.writeDouble(z); - } - - private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { - if (this instanceof MutableBlockVector2D) return; - this.x = stream.readDouble(); - this.z = stream.readDouble(); - } -} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEdit.java b/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEdit.java index e520a2e8a..3ec352d07 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEdit.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/WorldEdit.java @@ -1,694 +1,733 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit; - -import static com.sk89q.worldedit.event.platform.Interaction.HIT; -import static com.sk89q.worldedit.event.platform.Interaction.OPEN; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.sk89q.worldedit.blocks.BaseItem; -import com.sk89q.worldedit.entity.Player; -import com.sk89q.worldedit.event.platform.BlockInteractEvent; -import com.sk89q.worldedit.event.platform.InputType; -import com.sk89q.worldedit.event.platform.PlayerInputEvent; -import com.sk89q.worldedit.extension.factory.BlockFactory; -import com.sk89q.worldedit.extension.factory.ItemFactory; -import com.sk89q.worldedit.extension.factory.MaskFactory; -import com.sk89q.worldedit.extension.factory.PatternFactory; -import com.sk89q.worldedit.extension.platform.Actor; -import com.sk89q.worldedit.extension.platform.Capability; -import com.sk89q.worldedit.extension.platform.Platform; -import com.sk89q.worldedit.extension.platform.PlatformManager; -import com.sk89q.worldedit.extent.inventory.BlockBag; -import com.sk89q.worldedit.internal.expression.Expression; -import com.sk89q.worldedit.internal.expression.runtime.Constant; -import com.sk89q.worldedit.internal.expression.runtime.RValue; -import com.sk89q.worldedit.scripting.CraftScriptContext; -import com.sk89q.worldedit.scripting.CraftScriptEngine; -import com.sk89q.worldedit.scripting.RhinoCraftScriptEngine; -import com.sk89q.worldedit.session.SessionManager; -import com.sk89q.worldedit.session.request.Request; -import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.util.eventbus.EventBus; -import com.sk89q.worldedit.util.io.file.FileSelectionAbortedException; -import com.sk89q.worldedit.util.io.file.FilenameException; -import com.sk89q.worldedit.util.io.file.FilenameResolutionException; -import com.sk89q.worldedit.util.io.file.InvalidFilenameException; -import com.sk89q.worldedit.util.logging.WorldEditPrefixHandler; -import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockType; -import com.sk89q.worldedit.world.registry.BundledBlockData; -import com.sk89q.worldedit.world.registry.BundledItemData; -import com.sk89q.worldedit.world.registry.LegacyMapper; - -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.script.ScriptException; - -/** - * The entry point and container for a working implementation of WorldEdit. - * - *

An instance handles event handling; block, mask, pattern, etc. registration; - * the management of sessions; the creation of {@link EditSession}s; and more. - * In order to use WorldEdit, at least one {@link Platform} must be registered - * with WorldEdit using {@link PlatformManager#register(Platform)} on the - * manager retrieved using {@link WorldEdit#getPlatformManager()}.

- * - *

An instance of WorldEdit can be retrieved using the static - * method {@link WorldEdit#getInstance()}, which is shared among all - * platforms within the same classloader hierarchy.

- */ -public class WorldEdit { - - public static final Logger logger = Logger.getLogger(WorldEdit.class.getCanonicalName()); - - private final static WorldEdit instance = new WorldEdit(); - private static String version; - - private final EventBus eventBus = new EventBus(); - private final PlatformManager platformManager = new PlatformManager(this); - private final EditSessionFactory editSessionFactory = new EditSessionFactory.EditSessionFactoryImpl(eventBus); - private final SessionManager sessions = new SessionManager(this); - - private final BlockFactory blockFactory = new BlockFactory(this); - private final ItemFactory itemFactory = new ItemFactory(this); - private final MaskFactory maskFactory = new MaskFactory(this); - private final PatternFactory patternFactory = new PatternFactory(this); - - static { - WorldEditPrefixHandler.register("com.sk89q.worldedit"); - getVersion(); - } - - private WorldEdit() { - } - - /** - * Gets the current instance of this class. - * - *

An instance will always be available, but no platform may yet be - * registered with WorldEdit, meaning that a number of operations - * may fail. However, event handlers can be registered.

- * - * @return an instance of WorldEdit. - */ - public static WorldEdit getInstance() { - return instance; - } - - /** - * Get the platform manager, where platforms (that implement WorldEdit) - * can be registered and information about registered platforms can - * be queried. - * - * @return the platform manager - */ - public PlatformManager getPlatformManager() { - return platformManager; - } - - /** - * Get the event bus for WorldEdit. - * - *

Event handlers can be registered on the event bus.

- * - * @return the event bus - */ - public EventBus getEventBus() { - return eventBus; - } - - /** - * Get the block factory from which new {@link BlockStateHolder}s can be - * constructed. - * - * @return the block factory - */ - public BlockFactory getBlockFactory() { - return blockFactory; - } - - /** - * Get the item factory from which new {@link BaseItem}s can be - * constructed. - * - * @return the item factory - */ - public ItemFactory getItemFactory() { - return itemFactory; - } - - /** - * Get the mask factory from which new {@link com.sk89q.worldedit.function.mask.Mask}s - * can be constructed. - * - * @return the mask factory - */ - public MaskFactory getMaskFactory() { - return maskFactory; - } - - /** - * Get the pattern factory from which new {@link com.sk89q.worldedit.function.pattern.Pattern}s - * can be constructed. - * - * @return the pattern factory - */ - public PatternFactory getPatternFactory() { - return patternFactory; - } - - /** - * Return the session manager. - * - * @return the session manager - */ - public SessionManager getSessionManager() { - return sessions; - } - - /** - * Gets the path to a file. This method will check to see if the filename - * has valid characters and has an extension. It also prevents directory - * traversal exploits by checking the root directory and the file directory. - * On success, a {@code java.io.File} object will be returned. - * - * @param player the player - * @param dir sub-directory to look in - * @param filename filename (user-submitted) - * @param defaultExt append an extension if missing one, null to not use - * @param extensions list of extensions, null for any - * @return a file - * @throws FilenameException thrown if the filename is invalid - */ - public File getSafeSaveFile(Player player, File dir, String filename, String defaultExt, String... extensions) throws FilenameException { - return getSafeFile(player, dir, filename, defaultExt, extensions, true); - } - - /** - * Gets the path to a file. This method will check to see if the filename - * has valid characters and has an extension. It also prevents directory - * traversal exploits by checking the root directory and the file directory. - * On success, a {@code java.io.File} object will be returned. - * - * @param player the player - * @param dir sub-directory to look in - * @param filename filename (user-submitted) - * @param defaultExt append an extension if missing one, null to not use - * @param extensions list of extensions, null for any - * @return a file - * @throws FilenameException thrown if the filename is invalid - */ - public File getSafeOpenFile(Player player, File dir, String filename, String defaultExt, String... extensions) throws FilenameException { - return getSafeFile(player, dir, filename, defaultExt, extensions, false); - } - - /** - * Get a safe path to a file. - * - * @param player the player - * @param dir sub-directory to look in - * @param filename filename (user-submitted) - * @param defaultExt append an extension if missing one, null to not use - * @param extensions list of extensions, null for any - * @param isSave true if the purpose is for saving - * @return a file - * @throws FilenameException thrown if the filename is invalid - */ - private File getSafeFile(Player player, File dir, String filename, String defaultExt, String[] extensions, boolean isSave) throws FilenameException { - if (extensions != null && (extensions.length == 1 && extensions[0] == null)) extensions = null; - - File f; - - if (filename.equals("#")) { - if (isSave) { - f = player.openFileSaveDialog(extensions); - } else { - f = player.openFileOpenDialog(extensions); - } - - if (f == null) { - throw new FileSelectionAbortedException("No file selected"); - } - } else { - List exts = extensions == null ? ImmutableList.of(defaultExt) : Lists.asList(defaultExt, extensions); - return getSafeFileWithExtensions(dir, filename, exts, isSave); - } - - try { - String filePath = f.getCanonicalPath(); - String dirPath = dir.getCanonicalPath(); - - if (!filePath.substring(0, dirPath.length()).equals(dirPath) && !getConfiguration().allowSymlinks) { - throw new FilenameResolutionException(filename, - "Path is outside allowable root"); - } - - return f; - } catch (IOException e) { - throw new FilenameResolutionException(filename, - "Failed to resolve path"); - } - } - - private File getSafeFileWithExtensions(File dir, String filename, List exts, boolean isSave) throws InvalidFilenameException { - if (isSave) { - // First is default, only use that. - if (exts.size() != 1) { - exts = exts.subList(0, 1); - } - } - File result = null; - for (Iterator iter = exts.iterator(); iter.hasNext() && (result == null || !result.exists());) { - result = getSafeFileWithExtension(dir, filename, iter.next()); - } - if (result == null) { - throw new InvalidFilenameException(filename, "Invalid characters or extension missing"); - } - return result; - } - - private File getSafeFileWithExtension(File dir, String filename, String extension) { - if (extension != null && filename.lastIndexOf('.') == -1) { - filename += "." + extension; - } - - if (!checkFilename(filename)) { - return null; - } - - return new File(dir, filename); - } - - private boolean checkFilename(String filename) { - return filename.matches("^[A-Za-z0-9_\\- \\./\\\\'\\$@~!%\\^\\*\\(\\)\\[\\]\\+\\{\\},\\?]+\\.[A-Za-z0-9]+$"); - } - - /** - * Load the bundled mappings. - */ - public void loadMappings() { - BundledBlockData.getInstance(); // Load block registry - BundledItemData.getInstance(); // Load item registry - LegacyMapper.getInstance(); // Load item registry - } - - /** - * Checks to see if the specified radius is within bounds. - * - * @param radius the radius - * @throws MaxRadiusException - */ - public void checkMaxRadius(double radius) throws MaxRadiusException { - if (getConfiguration().maxRadius > 0 && radius > getConfiguration().maxRadius) { - throw new MaxRadiusException(); - } - } - - /** - * Checks to see if the specified brush radius is within bounds. - * - * @param radius the radius - * @throws MaxBrushRadiusException - */ - public void checkMaxBrushRadius(double radius) throws MaxBrushRadiusException { - if (getConfiguration().maxBrushRadius > 0 && radius > getConfiguration().maxBrushRadius) { - throw new MaxBrushRadiusException(); - } - } - - public void checkMaxBrushRadius(Expression radius) throws MaxBrushRadiusException { - if (getConfiguration().maxBrushRadius > 0) { - RValue r = radius.getRoot(); - if (r instanceof Constant && ((Constant) r).getValue() > getConfiguration().maxBrushRadius) { - throw new MaxBrushRadiusException(); - } - } - } - - /** - * Get a file relative to the defined working directory. If the specified - * path is absolute, then the working directory is not used. - * - * @param path the subpath under the working directory - * @return a working directory - */ - public File getWorkingDirectoryFile(String path) { - File f = new File(path); - if (f.isAbsolute()) { - return f; - } - - return new File(getConfiguration().getWorkingDirectory(), path); - } - - /** - * Get the direction vector for a player's direction. May return - * null if a direction could not be found. - * - * @param player the player - * @param dirStr the direction string - * @return a direction vector - * @throws UnknownDirectionException thrown if the direction is not known - */ - public Vector getDirection(Player player, String dirStr) throws UnknownDirectionException { - dirStr = dirStr.toLowerCase(); - - final PlayerDirection dir = getPlayerDirection(player, dirStr); - - switch (dir) { - case WEST: - case EAST: - case SOUTH: - case NORTH: - case UP: - case DOWN: - return dir.vector(); - - default: - throw new UnknownDirectionException(dir.name()); - } - } - - /** - * Get the direction vector for a player's direction. May return - * null if a direction could not be found. - * - * @param player the player - * @param dirStr the direction string - * @return a direction enum value - * @throws UnknownDirectionException thrown if the direction is not known - */ - private PlayerDirection getPlayerDirection(Player player, String dirStr) throws UnknownDirectionException { - final PlayerDirection dir; - - switch (dirStr.charAt(0)) { - case 'w': - dir = PlayerDirection.WEST; - break; - - case 'e': - dir = PlayerDirection.EAST; - break; - - case 's': - if (dirStr.indexOf('w') > 0) { - return PlayerDirection.SOUTH_WEST; - } - - if (dirStr.indexOf('e') > 0) { - return PlayerDirection.SOUTH_EAST; - } - dir = PlayerDirection.SOUTH; - break; - - case 'n': - if (dirStr.indexOf('w') > 0) { - return PlayerDirection.NORTH_WEST; - } - - if (dirStr.indexOf('e') > 0) { - return PlayerDirection.NORTH_EAST; - } - dir = PlayerDirection.NORTH; - break; - - case 'u': - dir = PlayerDirection.UP; - break; - - case 'd': - dir = PlayerDirection.DOWN; - break; - - case 'm': // me - case 'f': // forward - dir = player.getCardinalDirection(0); - break; - - case 'b': // back - dir = player.getCardinalDirection(180); - break; - - case 'l': // left - dir = player.getCardinalDirection(-90); - break; - - case 'r': // right - dir = player.getCardinalDirection(90); - break; - - default: - throw new UnknownDirectionException(dirStr); - } - return dir; - } - - /** - * Flush a block bag's changes to a player. - * - * @param actor the actor - * @param editSession the edit session - */ - public void flushBlockBag(Actor actor, EditSession editSession) { - BlockBag blockBag = editSession.getBlockBag(); - - if (blockBag != null) { - blockBag.flushChanges(); - } - - Map missingBlocks = editSession.popMissingBlocks(); - - if (!missingBlocks.isEmpty()) { - StringBuilder str = new StringBuilder(); - str.append("Missing these blocks: "); - int size = missingBlocks.size(); - int i = 0; - - for (Map.Entry blockTypeIntegerEntry : missingBlocks.entrySet()) { - str.append((blockTypeIntegerEntry.getKey()).getName()); - - str.append(" [Amt: ").append(blockTypeIntegerEntry.getValue()).append("]"); - - ++i; - - if (i != size) { - str.append(", "); - } - } - - actor.printError(str.toString()); - } - } - - /** - * Called on arm swing. - * - * @param player the player - * @return true if the swing was handled - */ - public boolean handleArmSwing(Player player) { - PlayerInputEvent event = new PlayerInputEvent(player, InputType.PRIMARY); - getEventBus().post(event); - return event.isCancelled(); - } - - /** - * Called on right click (not on a block). - * - * @param player the player - * @return true if the right click was handled - */ - public boolean handleRightClick(Player player) { - PlayerInputEvent event = new PlayerInputEvent(player, InputType.SECONDARY); - getEventBus().post(event); - return event.isCancelled(); - } - - /** - * Called on right click. - * - * @param player the player - * @param clicked the clicked block - * @return false if you want the action to go through - */ - public boolean handleBlockRightClick(Player player, Location clicked) { - BlockInteractEvent event = new BlockInteractEvent(player, clicked, OPEN); - getEventBus().post(event); - return event.isCancelled(); - } - - /** - * Called on left click. - * - * @param player the player - * @param clicked the clicked block - * @return false if you want the action to go through - */ - public boolean handleBlockLeftClick(Player player, Location clicked) { - BlockInteractEvent event = new BlockInteractEvent(player, clicked, HIT); - getEventBus().post(event); - return event.isCancelled(); - } - - /** - * Executes a WorldEdit script. - * - * @param player the player - * @param f the script file to execute - * @param args arguments for the script - * @throws WorldEditException - */ - public void runScript(Player player, File f, String[] args) throws WorldEditException { - Request.reset(); - - String filename = f.getPath(); - int index = filename.lastIndexOf('.'); - String ext = filename.substring(index + 1); - - if (!ext.equalsIgnoreCase("js")) { - player.printError("Only .js scripts are currently supported"); - return; - } - - String script; - - try { - InputStream file; - - if (!f.exists()) { - file = WorldEdit.class.getResourceAsStream("craftscripts/" + filename); - - if (file == null) { - player.printError("Script does not exist: " + filename); - return; - } - } else { - file = new FileInputStream(f); - } - - DataInputStream in = new DataInputStream(file); - byte[] data = new byte[in.available()]; - in.readFully(data); - in.close(); - script = new String(data, 0, data.length, "utf-8"); - } catch (IOException e) { - player.printError("Script read error: " + e.getMessage()); - return; - } - - LocalSession session = getSessionManager().get(player); - CraftScriptContext scriptContext = new CraftScriptContext(this, getPlatformManager().queryCapability(Capability.USER_COMMANDS), - getConfiguration(), session, player, args); - - CraftScriptEngine engine; - - try { - engine = new RhinoCraftScriptEngine(); - } catch (NoClassDefFoundError e) { - player.printError("Failed to find an installed script engine."); - player.printError("Please see http://wiki.sk89q.com/wiki/WorldEdit/Installation"); - return; - } - - engine.setTimeLimit(getConfiguration().scriptTimeout); - - Map vars = new HashMap<>(); - vars.put("argv", args); - vars.put("context", scriptContext); - vars.put("player", player); - - try { - engine.evaluate(script, filename, vars); - } catch (ScriptException e) { - player.printError("Failed to execute:"); - player.printRaw(e.getMessage()); - logger.log(Level.WARNING, "Failed to execute script", e); - } catch (NumberFormatException | WorldEditException e) { - throw e; - } catch (Throwable e) { - player.printError("Failed to execute (see console):"); - player.printRaw(e.getClass().getCanonicalName()); - logger.log(Level.WARNING, "Failed to execute script", e); - } finally { - for (EditSession editSession : scriptContext.getEditSessions()) { - editSession.flushQueue(); - session.remember(editSession); - } - } - } - - /** - * Get Worldedit's configuration. - * - * @return a configuration - */ - public LocalConfiguration getConfiguration() { - return getPlatformManager().getConfiguration(); - } - - /** - * Get a factory for {@link EditSession}s. - */ - public EditSessionFactory getEditSessionFactory() { - return editSessionFactory; - } - - /** - * Get the version. - * - * @return the version of WorldEdit - */ - public static String getVersion() { - if (version != null) { - return version; - } - - Package p = WorldEdit.class.getPackage(); - - if (p == null) { - p = Package.getPackage("com.sk89q.worldedit"); - } - - if (p == null) { - version = "(unknown)"; - } else { - version = p.getImplementationVersion(); - - if (version == null) { - version = "(unknown)"; - } - } - - return version; - } - -} +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import com.sk89q.worldedit.blocks.BaseItem; +import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.event.platform.BlockInteractEvent; +import com.sk89q.worldedit.event.platform.InputType; +import com.sk89q.worldedit.event.platform.PlayerInputEvent; +import com.sk89q.worldedit.extension.factory.BlockFactory; +import com.sk89q.worldedit.extension.factory.ItemFactory; +import com.sk89q.worldedit.extension.factory.MaskFactory; +import com.sk89q.worldedit.extension.factory.PatternFactory; +import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.extension.platform.Capability; +import com.sk89q.worldedit.extension.platform.Platform; +import com.sk89q.worldedit.extension.platform.PlatformManager; +import com.sk89q.worldedit.extent.inventory.BlockBag; +import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.internal.expression.Expression; +import com.sk89q.worldedit.internal.expression.runtime.Constant; +import com.sk89q.worldedit.internal.expression.runtime.RValue; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.scripting.CraftScriptContext; +import com.sk89q.worldedit.scripting.CraftScriptEngine; +import com.sk89q.worldedit.scripting.RhinoCraftScriptEngine; +import com.sk89q.worldedit.session.SessionManager; +import com.sk89q.worldedit.session.request.Request; +import com.sk89q.worldedit.util.Direction; +import com.sk89q.worldedit.util.Location; +import com.sk89q.worldedit.util.eventbus.EventBus; +import com.sk89q.worldedit.util.io.file.FileSelectionAbortedException; +import com.sk89q.worldedit.util.io.file.FilenameException; +import com.sk89q.worldedit.util.io.file.FilenameResolutionException; +import com.sk89q.worldedit.util.io.file.InvalidFilenameException; +import com.sk89q.worldedit.util.logging.WorldEditPrefixHandler; +import com.sk89q.worldedit.util.task.SimpleSupervisor; +import com.sk89q.worldedit.util.task.Supervisor; +import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.registry.BundledBlockData; +import com.sk89q.worldedit.world.registry.BundledItemData; +import com.sk89q.worldedit.world.registry.LegacyMapper; + +import javax.annotation.Nullable; +import javax.script.ScriptException; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static com.sk89q.worldedit.event.platform.Interaction.HIT; +import static com.sk89q.worldedit.event.platform.Interaction.OPEN; + +/** + * The entry point and container for a working implementation of WorldEdit. + * + *

An instance handles event handling; block, mask, pattern, etc. registration; + * the management of sessions; the creation of {@link EditSession}s; and more. + * In order to use WorldEdit, at least one {@link Platform} must be registered + * with WorldEdit using {@link PlatformManager#register(Platform)} on the + * manager retrieved using {@link WorldEdit#getPlatformManager()}.

+ * + *

An instance of WorldEdit can be retrieved using the static + * method {@link WorldEdit#getInstance()}, which is shared among all + * platforms within the same classloader hierarchy.

+ */ +public final class WorldEdit { + + public static final Logger logger = Logger.getLogger(WorldEdit.class.getCanonicalName()); + + private final static WorldEdit instance = new WorldEdit(); + private static String version; + + private final EventBus eventBus = new EventBus(); + private final PlatformManager platformManager = new PlatformManager(this); + private final EditSessionFactory editSessionFactory = new EditSessionFactory.EditSessionFactoryImpl(eventBus); + private final SessionManager sessions = new SessionManager(this); + private final Supervisor supervisor = new SimpleSupervisor(); + + private final BlockFactory blockFactory = new BlockFactory(this); + private final ItemFactory itemFactory = new ItemFactory(this); + private final MaskFactory maskFactory = new MaskFactory(this); + private final PatternFactory patternFactory = new PatternFactory(this); + + static { + WorldEditPrefixHandler.register("com.sk89q.worldedit"); + getVersion(); + } + + private WorldEdit() { + } + + /** + * Gets the current instance of this class. + * + *

An instance will always be available, but no platform may yet be + * registered with WorldEdit, meaning that a number of operations + * may fail. However, event handlers can be registered.

+ * + * @return an instance of WorldEdit. + */ + public static WorldEdit getInstance() { + return instance; + } + + /** + * Get the platform manager, where platforms (that implement WorldEdit) + * can be registered and information about registered platforms can + * be queried. + * + * @return the platform manager + */ + public PlatformManager getPlatformManager() { + return platformManager; + } + + /** + * Get the event bus for WorldEdit. + * + *

Event handlers can be registered on the event bus.

+ * + * @return the event bus + */ + public EventBus getEventBus() { + return eventBus; + } + + /** + * Get the supervisor. + * + * @return the supervisor + */ + public Supervisor getSupervisor() { + return supervisor; + } + + /** + * Get the block factory from which new {@link BlockStateHolder}s can be + * constructed. + * + * @return the block factory + */ + public BlockFactory getBlockFactory() { + return blockFactory; + } + + /** + * Get the item factory from which new {@link BaseItem}s can be + * constructed. + * + * @return the item factory + */ + public ItemFactory getItemFactory() { + return itemFactory; + } + + /** + * Get the mask factory from which new {@link Mask}s + * can be constructed. + * + * @return the mask factory + */ + public MaskFactory getMaskFactory() { + return maskFactory; + } + + /** + * Get the pattern factory from which new {@link Pattern}s + * can be constructed. + * + * @return the pattern factory + */ + public PatternFactory getPatternFactory() { + return patternFactory; + } + + /** + * Return the session manager. + * + * @return the session manager + */ + public SessionManager getSessionManager() { + return sessions; + } + + /** + * Gets the path to a file. This method will check to see if the filename + * has valid characters and has an extension. It also prevents directory + * traversal exploits by checking the root directory and the file directory. + * On success, a {@code java.io.File} object will be returned. + * + * @param player the player + * @param dir sub-directory to look in + * @param filename filename (user-submitted) + * @param defaultExt append an extension if missing one, null to not use + * @param extensions list of extensions, null for any + * @return a file + * @throws FilenameException thrown if the filename is invalid + */ + public File getSafeSaveFile(Player player, File dir, String filename, String defaultExt, String... extensions) throws FilenameException { + return getSafeFile(player, dir, filename, defaultExt, extensions, true); + } + + /** + * Gets the path to a file. This method will check to see if the filename + * has valid characters and has an extension. It also prevents directory + * traversal exploits by checking the root directory and the file directory. + * On success, a {@code java.io.File} object will be returned. + * + * @param player the player + * @param dir sub-directory to look in + * @param filename filename (user-submitted) + * @param defaultExt append an extension if missing one, null to not use + * @param extensions list of extensions, null for any + * @return a file + * @throws FilenameException thrown if the filename is invalid + */ + public File getSafeOpenFile(Player player, File dir, String filename, String defaultExt, String... extensions) throws FilenameException { + return getSafeFile(player, dir, filename, defaultExt, extensions, false); + } + + /** + * Get a safe path to a file. + * + * @param player the player + * @param dir sub-directory to look in + * @param filename filename (user-submitted) + * @param defaultExt append an extension if missing one, null to not use + * @param extensions list of extensions, null for any + * @param isSave true if the purpose is for saving + * @return a file + * @throws FilenameException thrown if the filename is invalid + */ + private File getSafeFile(@Nullable Player player, File dir, String filename, String defaultExt, String[] extensions, boolean isSave) throws FilenameException { + if (extensions != null && (extensions.length == 1 && extensions[0] == null)) extensions = null; + + File f; + + if (filename.equals("#") && player != null) { + if (isSave) { + f = player.openFileSaveDialog(extensions); + } else { + f = player.openFileOpenDialog(extensions); + } + + if (f == null) { + throw new FileSelectionAbortedException("No file selected"); + } + } else { + List exts = extensions == null ? ImmutableList.of(defaultExt) : Lists.asList(defaultExt, extensions); + f = getSafeFileWithExtensions(dir, filename, exts, isSave); + } + + try { + Path filePath = Paths.get(f.toURI()).normalize(); + Path dirPath = Paths.get(dir.toURI()).normalize(); + + boolean inDir = filePath.startsWith(dirPath); + Path existingParent = filePath; + do { + existingParent = existingParent.getParent(); + } while (existingParent != null && !existingParent.toFile().exists()); + + boolean isSym = existingParent != null && !existingParent.toRealPath().equals(existingParent); + if (!inDir || (!getConfiguration().allowSymlinks && isSym)) { + throw new FilenameResolutionException(filename, "Path is outside allowable root"); + } + + return filePath.toFile(); + } catch (IOException e) { + throw new FilenameResolutionException(filename, "Failed to resolve path"); + } + } + + private File getSafeFileWithExtensions(File dir, String filename, List exts, boolean isSave) throws InvalidFilenameException { + if (isSave) { + // First is default, only use that. + if (exts.size() != 1) { + exts = exts.subList(0, 1); + } + } + File result = null; + for (Iterator iter = exts.iterator(); iter.hasNext() && (result == null || (!isSave && !result.exists()));) { + result = getSafeFileWithExtension(dir, filename, iter.next()); + } + if (result == null) { + throw new InvalidFilenameException(filename, "Invalid characters or extension missing"); + } + return result; + } + + private File getSafeFileWithExtension(File dir, String filename, String extension) { + if (extension != null) { + int dot = filename.lastIndexOf('.'); + if (dot < 0 || !filename.substring(dot).equalsIgnoreCase(extension)) { + filename += "." + extension; + } + } + + if (!checkFilename(filename)) { + return null; + } + + return new File(dir, filename); + } + + private boolean checkFilename(String filename) { + return filename.matches("^[A-Za-z0-9_\\- \\./\\\\'\\$@~!%\\^\\*\\(\\)\\[\\]\\+\\{\\},\\?]+\\.[A-Za-z0-9]+$"); + } + + /** + * Load the bundled mappings. + */ + public void loadMappings() { + BundledBlockData.getInstance(); // Load block registry + BundledItemData.getInstance(); // Load item registry + LegacyMapper.getInstance(); // Load item registry + } + + /** + * Checks to see if the specified radius is within bounds. + * + * @param radius the radius + * @throws MaxRadiusException + */ + public void checkMaxRadius(double radius) throws MaxRadiusException { + if (getConfiguration().maxRadius > 0 && radius > getConfiguration().maxRadius) { + throw new MaxRadiusException(); + } + } + + /** + * Checks to see if the specified brush radius is within bounds. + * + * @param radius the radius + * @throws MaxBrushRadiusException + */ + public void checkMaxBrushRadius(double radius) throws MaxBrushRadiusException { + if (getConfiguration().maxBrushRadius > 0 && radius > getConfiguration().maxBrushRadius) { + throw new MaxBrushRadiusException(); + } + } + + public void checkMaxBrushRadius(Expression radius) throws MaxBrushRadiusException { + if (getConfiguration().maxBrushRadius > 0) { + RValue r = radius.getRoot(); + if (r instanceof Constant && ((Constant) r).getValue() > getConfiguration().maxBrushRadius) { + throw new MaxBrushRadiusException(); + } + } + } + + /** + * Get a file relative to the defined working directory. If the specified + * path is absolute, then the working directory is not used. + * + * @param path the subpath under the working directory + * @return a working directory + */ + public File getWorkingDirectoryFile(String path) { + File f = new File(path); + if (f.isAbsolute()) { + return f; + } + + return new File(getConfiguration().getWorkingDirectory(), path); + } + + /** + * Get the direction vector for a player's direction. May return + * null if a direction could not be found. + * + * @param player the player + * @param dirStr the direction string + * @return a direction vector + * @throws UnknownDirectionException thrown if the direction is not known + */ + public BlockVector3 getDirection(Player player, String dirStr) throws UnknownDirectionException { + dirStr = dirStr.toLowerCase(); + + final Direction dir = getPlayerDirection(player, dirStr); + + if (dir.isUpright() || dir.isCardinal()) { + return dir.toBlockVector(); + } else { + throw new UnknownDirectionException(dir.name()); + } + } + + /** + * Get the direction vector for a player's direction. May return + * null if a direction could not be found. + * + * @param player the player + * @param dirStr the direction string + * @return a direction vector + * @throws UnknownDirectionException thrown if the direction is not known + */ + public BlockVector3 getDiagonalDirection(Player player, String dirStr) throws UnknownDirectionException { + dirStr = dirStr.toLowerCase(); + + final Direction dir = getPlayerDirection(player, dirStr); + + if (dir.isCardinal() || dir.isOrdinal() || dir.isUpright()) { + return dir.toBlockVector(); + } + + throw new UnknownDirectionException(dir.name()); + } + + /** + * Get the direction vector for a player's direction. May return + * null if a direction could not be found. + * + * @param player the player + * @param dirStr the direction string + * @return a direction enum value + * @throws UnknownDirectionException thrown if the direction is not known + */ + private Direction getPlayerDirection(Player player, String dirStr) throws UnknownDirectionException { + final Direction dir; + + switch (dirStr.charAt(0)) { + case 'w': + dir = Direction.WEST; + break; + + case 'e': + dir = Direction.EAST; + break; + + case 's': + if (dirStr.indexOf('w') > 0) { + return Direction.SOUTHWEST; + } + + if (dirStr.indexOf('e') > 0) { + return Direction.SOUTHEAST; + } + dir = Direction.SOUTH; + break; + + case 'n': + if (dirStr.indexOf('w') > 0) { + return Direction.NORTHWEST; + } + + if (dirStr.indexOf('e') > 0) { + return Direction.NORTHEAST; + } + dir = Direction.NORTH; + break; + + case 'u': + dir = Direction.UP; + break; + + case 'd': + dir = Direction.DOWN; + break; + + case 'm': // me + case 'f': // forward + dir = player.getCardinalDirection(0); + break; + + case 'b': // back + dir = player.getCardinalDirection(180); + break; + + case 'l': // left + dir = player.getCardinalDirection(-90); + break; + + case 'r': // right + dir = player.getCardinalDirection(90); + break; + + default: + throw new UnknownDirectionException(dirStr); + } + return dir; + } + + /** + * Flush a block bag's changes to a player. + * + * @param actor the actor + * @param editSession the edit session + */ + public void flushBlockBag(Actor actor, EditSession editSession) { + BlockBag blockBag = editSession.getBlockBag(); + + if (blockBag != null) { + blockBag.flushChanges(); + } + + Map missingBlocks = editSession.popMissingBlocks(); + + if (!missingBlocks.isEmpty()) { + StringBuilder str = new StringBuilder(); + str.append("Missing these blocks: "); + int size = missingBlocks.size(); + int i = 0; + + for (Map.Entry blockTypeIntegerEntry : missingBlocks.entrySet()) { + str.append((blockTypeIntegerEntry.getKey()).getName()); + + str.append(" [Amt: ").append(blockTypeIntegerEntry.getValue()).append("]"); + + ++i; + + if (i != size) { + str.append(", "); + } + } + + actor.printError(str.toString()); + } + } + + /** + * Called on arm swing. + * + * @param player the player + * @return true if the swing was handled + */ + public boolean handleArmSwing(Player player) { + PlayerInputEvent event = new PlayerInputEvent(player, InputType.PRIMARY); + getEventBus().post(event); + return event.isCancelled(); + } + + /** + * Called on right click (not on a block). + * + * @param player the player + * @return true if the right click was handled + */ + public boolean handleRightClick(Player player) { + PlayerInputEvent event = new PlayerInputEvent(player, InputType.SECONDARY); + getEventBus().post(event); + return event.isCancelled(); + } + + /** + * Called on right click. + * + * @param player the player + * @param clicked the clicked block + * @return false if you want the action to go through + */ + public boolean handleBlockRightClick(Player player, Location clicked) { + BlockInteractEvent event = new BlockInteractEvent(player, clicked, OPEN); + getEventBus().post(event); + return event.isCancelled(); + } + + /** + * Called on left click. + * + * @param player the player + * @param clicked the clicked block + * @return false if you want the action to go through + */ + public boolean handleBlockLeftClick(Player player, Location clicked) { + BlockInteractEvent event = new BlockInteractEvent(player, clicked, HIT); + getEventBus().post(event); + return event.isCancelled(); + } + + /** + * Executes a WorldEdit script. + * + * @param player the player + * @param f the script file to execute + * @param args arguments for the script + * @throws WorldEditException + */ + public void runScript(Player player, File f, String[] args) throws WorldEditException { + String filename = f.getPath(); + int index = filename.lastIndexOf('.'); + String ext = filename.substring(index + 1); + + if (!ext.equalsIgnoreCase("js")) { + player.printError("Only .js scripts are currently supported"); + return; + } + + String script; + + try { + InputStream file; + + if (!f.exists()) { + file = WorldEdit.class.getResourceAsStream("craftscripts/" + filename); + + if (file == null) { + player.printError("Script does not exist: " + filename); + return; + } + } else { + file = new FileInputStream(f); + } + + DataInputStream in = new DataInputStream(file); + byte[] data = new byte[in.available()]; + in.readFully(data); + in.close(); + script = new String(data, 0, data.length, StandardCharsets.UTF_8); + } catch (IOException e) { + player.printError("Script read error: " + e.getMessage()); + return; + } + + LocalSession session = getSessionManager().get(player); + CraftScriptContext scriptContext = new CraftScriptContext(this, getPlatformManager().queryCapability(Capability.USER_COMMANDS), + getConfiguration(), session, player, args); + + CraftScriptEngine engine; + + try { + engine = new RhinoCraftScriptEngine(); + } catch (NoClassDefFoundError e) { + player.printError("Failed to find an installed script engine."); + player.printError("Please see http://wiki.sk89q.com/wiki/WorldEdit/Installation"); + return; + } + + engine.setTimeLimit(getConfiguration().scriptTimeout); + + Map vars = new HashMap<>(); + vars.put("argv", args); + vars.put("context", scriptContext); + vars.put("player", player); + + try { + engine.evaluate(script, filename, vars); + } catch (ScriptException e) { + player.printError("Failed to execute:"); + player.printRaw(e.getMessage()); + logger.log(Level.WARNING, "Failed to execute script", e); + } catch (NumberFormatException | WorldEditException e) { + throw e; + } catch (Throwable e) { + player.printError("Failed to execute (see console):"); + player.printRaw(e.getClass().getCanonicalName()); + logger.log(Level.WARNING, "Failed to execute script", e); + } finally { + for (EditSession editSession : scriptContext.getEditSessions()) { + editSession.flushQueue(); + session.remember(editSession); + } + } + } + + /** + * Get Worldedit's configuration. + * + * @return a configuration + */ + public LocalConfiguration getConfiguration() { + return getPlatformManager().getConfiguration(); + } + + /** + * Get a factory for {@link EditSession}s. + */ + public EditSessionFactory getEditSessionFactory() { + return editSessionFactory; + } + + /** + * Get the version. + * + * @return the version of WorldEdit + */ + public static String getVersion() { + if (version != null) { + return version; + } + + Package p = WorldEdit.class.getPackage(); + + if (p == null) { + p = Package.getPackage("com.sk89q.worldedit"); + } + + if (p == null) { + version = "(unknown)"; + } else { + version = p.getImplementationVersion(); + + if (version == null) { + version = "(unknown)"; + } + } + + return version; + } + +} 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 38d70cfe2..47283f582 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 @@ -69,8 +69,8 @@ public class BaseItem implements NbtValued { * * @return the type */ - public ItemTypes getType() { - return (ItemTypes) this.itemType; + public ItemType getType() { + return this.itemType; } /** diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BlockType.java b/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BlockType.java deleted file mode 100644 index e76f61aa0..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BlockType.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.blocks; - -import com.sk89q.worldedit.registry.state.PropertyGroup; -import com.sk89q.worldedit.registry.state.PropertyKey; -import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockTypes; - -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Block types. - * - * {@deprecated Please use {@link com.sk89q.worldedit.world.block.BlockType }} - */ -@Deprecated -public class BlockType { - - public static double centralTopLimit(com.sk89q.worldedit.world.block.BlockType type) { - checkNotNull(type); - return centralTopLimit(type.getDefaultState()); - } - - public static double centralBottomLimit(BlockStateHolder block) { - checkNotNull(block); - BlockTypes type = block.getBlockType(); - switch (type) { - case CREEPER_WALL_HEAD: - case DRAGON_WALL_HEAD: - case PLAYER_WALL_HEAD: - case ZOMBIE_WALL_HEAD: return 0.25; - case ACACIA_SLAB: - case BIRCH_SLAB: - case BRICK_SLAB: - case COBBLESTONE_SLAB: - case DARK_OAK_SLAB: - case DARK_PRISMARINE_SLAB: - case JUNGLE_SLAB: - case NETHER_BRICK_SLAB: - case OAK_SLAB: - case PETRIFIED_OAK_SLAB: - case PRISMARINE_BRICK_SLAB: - case PRISMARINE_SLAB: - case PURPUR_SLAB: - case QUARTZ_SLAB: - case RED_SANDSTONE_SLAB: - case SANDSTONE_SLAB: - case SPRUCE_SLAB: - case STONE_BRICK_SLAB: - case STONE_SLAB: { - String state = (String) block.getState(PropertyKey.TYPE); - if (state == null) return 0; - switch (state) { - case "double": - case "bottom": - return 0; - case "top": - return 0.5; - } - } - case ACACIA_TRAPDOOR: - case BIRCH_TRAPDOOR: - case DARK_OAK_TRAPDOOR: - case IRON_TRAPDOOR: - case JUNGLE_TRAPDOOR: - case OAK_TRAPDOOR: - case SPRUCE_TRAPDOOR: - if (block.getState(PropertyKey.OPEN) == Boolean.TRUE) { - return 1; - } else if ("bottom".equals(block.getState(PropertyKey.HALF))) { - return 0.8125; - } else { - return 0; - } - case ACACIA_FENCE_GATE: - case BIRCH_FENCE_GATE: - case DARK_OAK_FENCE_GATE: - case JUNGLE_FENCE_GATE: - case OAK_FENCE_GATE: - case SPRUCE_FENCE_GATE: return block.getState(PropertyKey.OPEN) == Boolean.TRUE ? 1 : 0; - default: - if (type.getMaterial().isMovementBlocker()) return 0; - return 1; - } - } - - /** - * Returns the y offset a player falls to when falling onto the top of a block at xp+0.5/zp+0.5. - * - * @param block the block - * @return the y offset - */ - public static double centralTopLimit(BlockStateHolder block) { - checkNotNull(block); - BlockTypes type = block.getBlockType(); - switch (type) { - case BLACK_BED: - case BLUE_BED: - case BROWN_BED: - case CYAN_BED: - case GRAY_BED: - case GREEN_BED: - case LIGHT_BLUE_BED: - case LIGHT_GRAY_BED: - case LIME_BED: - case MAGENTA_BED: - case ORANGE_BED: - case PINK_BED: - case PURPLE_BED: - case RED_BED: - case WHITE_BED: - case YELLOW_BED: return 0.5625; - case BREWING_STAND: return 0.875; - case CAKE: return (block.getState(PropertyKey.BITES) == (Integer) 6) ? 0 : 0.4375; - case CAULDRON: return 0.3125; - case COCOA: return 0.750; - case ENCHANTING_TABLE: return 0.75; - case END_PORTAL_FRAME: return block.getState(PropertyKey.EYE) == Boolean.TRUE ? 1 : 0.8125; - case CREEPER_HEAD: - case DRAGON_HEAD: - case PISTON_HEAD: - case PLAYER_HEAD: - case ZOMBIE_HEAD: return 0.5; - case CREEPER_WALL_HEAD: - case DRAGON_WALL_HEAD: - case PLAYER_WALL_HEAD: - case ZOMBIE_WALL_HEAD: return 0.75; - case ACACIA_FENCE: - case BIRCH_FENCE: - case DARK_OAK_FENCE: - case JUNGLE_FENCE: - case NETHER_BRICK_FENCE: - case OAK_FENCE: - case SPRUCE_FENCE: return 1.5; - case ACACIA_SLAB: - case BIRCH_SLAB: - case BRICK_SLAB: - case COBBLESTONE_SLAB: - case DARK_OAK_SLAB: - case DARK_PRISMARINE_SLAB: - case JUNGLE_SLAB: - case NETHER_BRICK_SLAB: - case OAK_SLAB: - case PETRIFIED_OAK_SLAB: - case PRISMARINE_BRICK_SLAB: - case PRISMARINE_SLAB: - case PURPUR_SLAB: - case QUARTZ_SLAB: - case RED_SANDSTONE_SLAB: - case SANDSTONE_SLAB: - case SPRUCE_SLAB: - case STONE_BRICK_SLAB: - case STONE_SLAB: { - String state = (String) block.getState(PropertyKey.TYPE); - if (state == null) return 0.5; - switch (state) { - case "bottom": - return 0.5; - case "top": - case "double": - return 1; - } - } - case LILY_PAD: return 0.015625; - case REPEATER: return 0.125; - case SOUL_SAND: return 0.875; - case COBBLESTONE_WALL: - case MOSSY_COBBLESTONE_WALL: return 1.5; - case FLOWER_POT: return 0.375; - case COMPARATOR: return 0.125; - case DAYLIGHT_DETECTOR: return 0.375; - case HOPPER: return 0.625; - case ACACIA_TRAPDOOR: - case BIRCH_TRAPDOOR: - case DARK_OAK_TRAPDOOR: - case IRON_TRAPDOOR: - case JUNGLE_TRAPDOOR: - case OAK_TRAPDOOR: - case SPRUCE_TRAPDOOR: - if (block.getState(PropertyKey.OPEN) == Boolean.TRUE) { - return 0; - } else if ("top".equals(block.getState(PropertyKey.HALF))) { - return 1; - } else { - return 0.1875; - } - case ACACIA_FENCE_GATE: - case BIRCH_FENCE_GATE: - case DARK_OAK_FENCE_GATE: - case JUNGLE_FENCE_GATE: - case OAK_FENCE_GATE: - case 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; - return 1; - - } - } -} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/Blocks.java b/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/Blocks.java index 09bd50ff2..83ebddc85 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/Blocks.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/Blocks.java @@ -36,6 +36,28 @@ public final class Blocks { private Blocks() { } + /** + * HashSet for shouldPlaceLate. + */ + private static final Set shouldPlaceLate = new HashSet<>(); + static { + shouldPlaceLate.add(BlockTypes.WATER); + shouldPlaceLate.add(BlockTypes.LAVA); + shouldPlaceLate.add(BlockTypes.GRAVEL); + shouldPlaceLate.add(BlockTypes.SAND); + } + /** + * Checks to see whether a block should be placed in the final queue. + * + * This applies to blocks that can be attached to other blocks that have an attachment. + * + * @param type the type of the block + * @return whether the block is in the late queue + */ + public static boolean shouldPlaceLate(BlockType type) { + return shouldPlaceLate.contains(type); + } + /** * HashSet for shouldPlaceLast. */ @@ -158,9 +180,9 @@ public final class Blocks { * @param o the block * @return true if the collection contains the given block */ - public static boolean containsFuzzy(Collection collection, BlockStateHolder o) { + public static > boolean containsFuzzy(Collection> collection, B o) { // Allow masked data in the searchBlocks to match various types - for (BlockStateHolder b : collection) { + for (BlockStateHolder b : collection) { if (b.equalsFuzzy(o)) { return true; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/BiomeCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/BiomeCommands.java index 3f91f0a56..8c14f4614 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/BiomeCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/BiomeCommands.java @@ -30,8 +30,6 @@ import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.Logging; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.Player; @@ -45,6 +43,8 @@ import com.sk89q.worldedit.function.mask.Mask2D; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.visitor.FlatRegionVisitor; import com.sk89q.worldedit.function.visitor.RegionVisitor; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.FlatRegion; import com.sk89q.worldedit.regions.Region; @@ -150,11 +150,11 @@ public class BiomeCommands extends MethodCommands { return; } - BaseBiome biome = player.getWorld().getBiome(blockPosition.toVector().toVector2D()); + BaseBiome biome = player.getWorld().getBiome(blockPosition.toBlockPoint().toBlockVector2()); biomes[biome.getId()]++; size = 1; } else if (args.hasFlag('p')) { - BaseBiome biome = player.getWorld().getBiome(player.getLocation().toVector().toVector2D()); + BaseBiome biome = player.getWorld().getBiome(player.getLocation().toBlockPoint().toBlockVector2()); biomes[biome.getId()]++; size = 1; } else { @@ -162,15 +162,15 @@ public class BiomeCommands extends MethodCommands { Region region = session.getSelection(world); if (region instanceof FlatRegion) { - for (Vector2D pt : new Fast2DIterator(((FlatRegion) region).asFlatRegion(), editSession)) { + for (BlockVector2 pt : new Fast2DIterator(((FlatRegion) region).asFlatRegion(), editSession)) { biomes[editSession.getBiome(pt).getId()]++; size++; } } else { RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { @Override - public boolean apply(Vector position) throws WorldEditException { - biomes[editSession.getBiome(position.toVector2D()).getId()]++; + public boolean apply(BlockVector3 position) throws WorldEditException { + biomes[editSession.getBiome(position.toBlockVector2()).getId()]++; return true; } }, editSession); @@ -185,7 +185,7 @@ public class BiomeCommands extends MethodCommands { for (int i = 0; i < biomes.length; i++) { int count = biomes[i]; if (count != 0) { - distribution.add(new Countable(new BaseBiome(i), count)); + distribution.add(new Countable<>(new BaseBiome(i), count)); } } Collections.sort(distribution); @@ -219,7 +219,7 @@ public class BiomeCommands extends MethodCommands { Mask2D mask2d = mask != null ? mask.toMask2D() : null; if (atPosition) { - region = new CuboidRegion(player.getLocation().toVector(), player.getLocation().toVector()); + region = new CuboidRegion(player.getLocation().toBlockPoint(), player.getLocation().toBlockPoint()); } else { region = session.getSelection(world); } 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 9af1ef1aa..030395cb1 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 @@ -39,17 +39,32 @@ import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.Step; import com.sk89q.worldedit.*; import com.sk89q.worldedit.command.tool.brush.*; +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.LocalConfiguration; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.command.tool.brush.ButcherBrush; +import com.sk89q.worldedit.command.tool.brush.ClipboardBrush; +import com.sk89q.worldedit.command.tool.brush.CylinderBrush; +import com.sk89q.worldedit.command.tool.brush.GravityBrush; +import com.sk89q.worldedit.command.tool.brush.HollowCylinderBrush; +import com.sk89q.worldedit.command.tool.brush.HollowSphereBrush; +import com.sk89q.worldedit.command.tool.brush.SmoothBrush; +import com.sk89q.worldedit.command.tool.brush.SphereBrush; import com.sk89q.worldedit.command.util.CreatureButcher; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.function.mask.ExistingBlockMask; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.SingleBlockTypeMask; -import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.internal.expression.Expression; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.util.command.InvalidUsageException; import com.sk89q.worldedit.util.command.binding.Range; @@ -63,9 +78,6 @@ import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.net.URI; -import java.net.URL; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.List; @@ -268,8 +280,8 @@ public class BrushCommands extends BrushProcessor { max = 5 ) @CommandPermissions("worldedit.brush.rock") - public BrushSettings blobBrush(Player player, EditSession editSession, LocalSession session, Pattern fill, @Optional("10") Vector radius, @Optional("100") double sphericity, @Optional("30") double frequency, @Optional("50") double amplitude, CommandContext context) throws WorldEditException { - double max = MathMan.max(radius.getBlockX(), radius.getBlockY(), radius.getBlockZ()); + public BrushSettings blobBrush(Player player, EditSession editSession, LocalSession session, Pattern fill, @Optional("10") Vector3 radius, @Optional("100") double sphericity, @Optional("30") double frequency, @Optional("50") double amplitude, CommandContext context) throws WorldEditException { + double max = MathMan.max(radius.getX(), radius.getY(), radius.getZ()); getWorldEdit().checkMaxBrushRadius(max); Brush brush = new BlobBrush(radius.divide(max), frequency / 100, amplitude / 100, sphericity / 100); return set(session, context, @@ -458,7 +470,7 @@ public class BrushCommands extends BrushProcessor { try { - MultiClipboardHolder clipboards = ClipboardFormat.SCHEMATIC.loadAllFromInput(player, clipboard, null, true); + MultiClipboardHolder clipboards = ClipboardFormats.loadAllFromInput(player, clipboard, null, true); if (clipboards == null) { BBC.SCHEMATIC_NOT_FOUND.send(player, clipboard); return null; @@ -600,7 +612,7 @@ public class BrushCommands extends BrushProcessor { ClipboardHolder holder = session.getClipboard(); Clipboard clipboard = holder.getClipboard(); - Vector size = clipboard.getDimensions(); + BlockVector3 size = clipboard.getDimensions(); getWorldEdit().checkMaxBrushRadius(size.getBlockX()); getWorldEdit().checkMaxBrushRadius(size.getBlockY()); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/BrushOptionsCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/BrushOptionsCommands.java index 1076a0d6b..e37098f12 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/BrushOptionsCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/BrushOptionsCommands.java @@ -18,7 +18,7 @@ import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.command.tool.BrushTool; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ChunkCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ChunkCommands.java index 26d5a6f39..542aef756 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ChunkCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ChunkCommands.java @@ -24,13 +24,13 @@ import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.Logging; +import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.MathUtils; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.storage.LegacyChunkStore; @@ -78,7 +78,7 @@ public class ChunkCommands { player.print(BBC.getPrefix() + "Chunk: " + chunkX + ", " + chunkZ); player.print(BBC.getPrefix() + "Old format: " + folder1 + "/" + folder2 + "/" + filename); player.print(BBC.getPrefix() + "McRegion: region/" + McRegionChunkStore.getFilename( - new Vector2D(chunkX, chunkZ))); + BlockVector2.at(chunkX, chunkZ))); } @Command( @@ -89,10 +89,10 @@ public class ChunkCommands { max = 0 ) @CommandPermissions("worldedit.listchunks") - public void listChunks(Player player, LocalSession session, CommandContext args) throws WorldEditException { - Set chunks = session.getSelection(player.getWorld()).getChunks(); + public void listChunks(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { + Set chunks = session.getSelection(player.getWorld()).getChunks(); - for (Vector2D chunk : chunks) { + for (BlockVector2 chunk : chunks) { player.print(BBC.getPrefix() + LegacyChunkStore.getFilename(chunk)); } } @@ -110,7 +110,7 @@ public class ChunkCommands { player.print(BBC.getPrefix() + "Note that this command does not yet support the mcregion format."); LocalConfiguration config = worldEdit.getConfiguration(); - Set chunks = session.getSelection(player.getWorld()).getChunks(); + Set chunks = session.getSelection(player.getWorld()).getChunks(); FileOutputStream out = null; if (config.shellSaveType == null) { @@ -127,7 +127,7 @@ public class ChunkCommands { writer.write("ECHO.\r\n"); writer.write("PAUSE\r\n"); - for (Vector2D chunk : chunks) { + for (BlockVector2 chunk : chunks) { String filename = LegacyChunkStore.getFilename(chunk); writer.write("ECHO " + filename + "\r\n"); writer.write("DEL \"world/" + filename + "\"\r\n"); @@ -159,7 +159,7 @@ public class ChunkCommands { writer.write("echo\n"); writer.write("read -p \"Press any key to continue...\"\n"); - for (Vector2D chunk : chunks) { + for (BlockVector2 chunk : chunks) { String filename = LegacyChunkStore.getFilename(chunk); writer.write("echo " + filename + "\n"); writer.write("rm \"world/" + filename + "\"\n"); 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 798eb9577..d5e63ba85 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 @@ -36,15 +36,26 @@ import com.boydti.fawe.object.schematic.Schematic; import com.boydti.fawe.util.ImgurUtility; import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.MaskTraverser; -import com.boydti.fawe.util.gui.FormBuilder; -import com.boydti.fawe.wrappers.FakePlayer; import com.sk89q.minecraft.util.commands.*; import com.sk89q.worldedit.*; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.sk89q.minecraft.util.commands.Logging.LogMode.PLACEMENT; +import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION; + +import com.sk89q.minecraft.util.commands.Command; +import com.sk89q.minecraft.util.commands.CommandPermissions; +import com.sk89q.minecraft.util.commands.Logging; +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.extent.PasteEvent; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter; import com.sk89q.worldedit.function.block.BlockReplace; import com.sk89q.worldedit.function.mask.Mask; @@ -55,6 +66,8 @@ import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.internal.annotation.Direction; import com.sk89q.worldedit.internal.annotation.Selection; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.regions.Region; @@ -111,15 +124,15 @@ public class ClipboardCommands extends MethodCommands { public void lazyCopy(Player player, LocalSession session, EditSession editSession, @Selection final Region region, @Switch('e') boolean skipEntities, @Switch('m') Mask mask, @Switch('b') boolean copyBiomes) throws WorldEditException { - Vector min = region.getMinimumPoint(); - Vector max = region.getMaximumPoint(); + 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 = FawePlayer.wrap(player).getLimit(); if (volume >= limit.MAX_CHECKS) { throw new FaweException(BBC.WORLDEDIT_CANCEL_REASON_MAX_CHECKS); } session.setClipboard(null); - final Vector origin = region.getMinimumPoint(); + final BlockVector3 origin = region.getMinimumPoint(); final int mx = origin.getBlockX(); final int my = origin.getBlockY(); final int mz = origin.getBlockZ(); @@ -151,14 +164,14 @@ public class ClipboardCommands extends MethodCommands { public void copy(FawePlayer fp, Player player, LocalSession session, EditSession editSession, @Selection Region region, @Switch('e') boolean skipEntities, @Switch('m') Mask mask, CommandContext context, @Switch('b') boolean copyBiomes) throws WorldEditException { - Vector min = region.getMinimumPoint(); - Vector max = region.getMaximumPoint(); + 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 = FawePlayer.wrap(player).getLimit(); if (volume >= limit.MAX_CHECKS) { throw new FaweException(BBC.WORLDEDIT_CANCEL_REASON_MAX_CHECKS); } - Vector pos = session.getPlacementPosition(player); + BlockVector3 pos = session.getPlacementPosition(player); fp.checkConfirmationRegion(() -> { session.setClipboard(null); BlockArrayClipboard clipboard = new BlockArrayClipboard(region, player.getUniqueId()); @@ -201,8 +214,8 @@ public class ClipboardCommands extends MethodCommands { public void lazyCut(Player player, LocalSession session, EditSession editSession, @Selection final Region region, @Switch('e') boolean skipEntities, @Switch('m') Mask mask, @Switch('b') boolean copyBiomes) throws WorldEditException { - Vector min = region.getMinimumPoint(); - Vector max = region.getMaximumPoint(); + 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 = FawePlayer.wrap(player).getLimit(); if (volume >= limit.MAX_CHECKS) { @@ -212,7 +225,7 @@ public class ClipboardCommands extends MethodCommands { throw new FaweException(BBC.WORLDEDIT_CANCEL_REASON_MAX_CHANGES); } session.setClipboard(null); - final Vector origin = region.getMinimumPoint(); + final BlockVector3 origin = region.getMinimumPoint(); final int mx = origin.getBlockX(); final int my = origin.getBlockY(); final int mz = origin.getBlockZ(); @@ -242,8 +255,8 @@ public class ClipboardCommands extends MethodCommands { public void cut(FawePlayer fp, Player player, LocalSession session, EditSession editSession, @Selection Region region, @Optional("air") Pattern leavePattern, @Switch('e') boolean skipEntities, @Switch('m') Mask mask, @Switch('b') boolean copyBiomes, CommandContext context) throws WorldEditException { - Vector min = region.getMinimumPoint(); - Vector max = region.getMaximumPoint(); + 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 = FawePlayer.wrap(player).getLimit(); if (volume >= limit.MAX_CHECKS) { @@ -252,7 +265,7 @@ public class ClipboardCommands extends MethodCommands { if (volume >= limit.MAX_CHANGES) { throw new FaweException(BBC.WORLDEDIT_CANCEL_REASON_MAX_CHANGES); } - Vector pos = session.getPlacementPosition(player); + BlockVector3 pos = session.getPlacementPosition(player); fp.checkConfirmationRegion(() -> { session.setClipboard(null); BlockArrayClipboard clipboard = new BlockArrayClipboard(region, player.getUniqueId()); @@ -283,7 +296,7 @@ public class ClipboardCommands extends MethodCommands { @Deprecated @CommandPermissions({"worldedit.clipboard.download"}) public void download(final Player player, final LocalSession session, @Optional("schematic") final String formatName) throws CommandException, WorldEditException { - final ClipboardFormat format = ClipboardFormat.findByAlias(formatName); + final ClipboardFormat format = ClipboardFormats.findByAlias(formatName); if (format == null) { BBC.CLIPBOARD_INVALID_FORMAT.send(player, formatName); return; @@ -343,8 +356,8 @@ public class ClipboardCommands extends MethodCommands { } else { target = clipboard; } - switch (format) { - case PNG: + switch (format.getName()) { + case "PNG": try { FastByteArrayOutputStream baos = new FastByteArrayOutputStream(Short.MAX_VALUE); ClipboardWriter writer = format.getWriter(baos); @@ -356,7 +369,7 @@ public class ClipboardCommands extends MethodCommands { url = null; } break; - case SCHEMATIC: + case "SCHEMATIC": if (Settings.IMP.WEB.URL.isEmpty()) { BBC.SETTING_DISABLE.send(player, "web.url"); return; @@ -367,30 +380,20 @@ public class ClipboardCommands extends MethodCommands { url = null; break; } - } - if (url == null) { - BBC.GENERATING_LINK_FAILED.send(player); - } else { - String urlText = url.toString(); - if (Settings.IMP.WEB.SHORTEN_URLS) { - try { - urlText = MainUtil.getText("https://empcraft.com/s/?" + URLEncoder.encode(url.toString(), "UTF-8")); - } catch (IOException e) { - e.printStackTrace(); - } - } - if (Fawe.imp().getPlatform().equalsIgnoreCase("nukkit")) { - FormBuilder form = Fawe.imp().getFormBuilder(); - FawePlayer fp = FawePlayer.wrap(player); - if (form != null && fp != FakePlayer.getConsole().toFawePlayer()) { - form.setTitle("Download Clipboard"); - form.addInput("url:", urlText, urlText); - form.display(fp); - return; - } - } - BBC.DOWNLOAD_LINK.send(player, urlText); - } + if (url == null) { + BBC.GENERATING_LINK_FAILED.send(player); + } else { + String urlText = url.toString(); + if (Settings.IMP.WEB.SHORTEN_URLS) { + try { + urlText = MainUtil.getText("https://empcraft.com/s/?" + URLEncoder.encode(url.toString(), "UTF-8")); + } catch (IOException e) { + e.printStackTrace(); + } + } + BBC.DOWNLOAD_LINK.send(player, urlText); + } + } } @Command( @@ -403,7 +406,7 @@ public class ClipboardCommands extends MethodCommands { ) @CommandPermissions({"worldedit.clipboard.asset"}) public void asset(final Player player, final LocalSession session, String category) throws CommandException, WorldEditException { - final ClipboardFormat format = ClipboardFormat.SCHEMATIC; + final ClipboardFormat format = BuiltInClipboardFormat.MCEDIT_SCHEMATIC; ClipboardHolder holder = session.getClipboard(); Clipboard clipboard = holder.getClipboard(); final Transform transform = holder.getTransform(); @@ -417,7 +420,7 @@ public class ClipboardCommands extends MethodCommands { } else { target = clipboard; } - BBC.GENERATING_LINK.send(player, format.name()); + BBC.GENERATING_LINK.send(player, format.getName()); if (Settings.IMP.WEB.ASSETS.isEmpty()) { BBC.SETTING_DISABLE.send(player, "web.assets"); return; @@ -465,9 +468,8 @@ public class ClipboardCommands extends MethodCommands { } Clipboard clipboard = holder.getClipboard(); Region region = clipboard.getRegion(); - Vector to = atOrigin ? clipboard.getOrigin() : session.getPlacementPosition(player); + BlockVector3 to = atOrigin ? clipboard.getOrigin() : session.getPlacementPosition(player); checkPaste(player, editSession, to, holder, clipboard); - Operation operation = holder .createPaste(editSession) .to(to) @@ -478,20 +480,20 @@ public class ClipboardCommands extends MethodCommands { Operations.completeLegacy(operation); if (selectPasted) { - Vector clipboardOffset = clipboard.getRegion().getMinimumPoint().subtract(clipboard.getOrigin()); - Vector realTo = to.add(new Vector(holder.getTransform().apply(clipboardOffset))); - Vector max = realTo.add(new Vector(holder.getTransform().apply(region.getMaximumPoint().subtract(region.getMinimumPoint())))); - RegionSelector selector = new CuboidRegionSelector(player.getWorld(), realTo, max); + BlockVector3 clipboardOffset = clipboard.getRegion().getMinimumPoint().subtract(clipboard.getOrigin()); + Vector3 realTo = to.toVector3().add(holder.getTransform().apply(clipboardOffset.toVector3())); + Vector3 max = realTo.add(holder.getTransform().apply(region.getMaximumPoint().subtract(region.getMinimumPoint()).toVector3())); + RegionSelector selector = new CuboidRegionSelector(player.getWorld(), realTo.toBlockPoint(), max.toBlockPoint()); session.setRegionSelector(player.getWorld(), selector); selector.learnChanges(); selector.explainRegionAdjust(player, session); } - BBC.COMMAND_PASTE.send(player, to.toBlockVector()); + BBC.COMMAND_PASTE.send(player, to); if (!FawePlayer.wrap(player).hasPermission("fawe.tips")) BBC.TIP_COPYPASTE.or(BBC.TIP_SOURCE_MASK, BBC.TIP_REPLACE_MARKER).send(player, to); } - private void checkPaste(Player player, EditSession editSession, Vector to, ClipboardHolder holder, Clipboard clipboard) { + private void checkPaste(Player player, EditSession editSession, BlockVector3 to, ClipboardHolder holder, Clipboard clipboard) { URI uri = null; if (holder instanceof URIClipboardHolder) uri = ((URIClipboardHolder) holder).getURI(clipboard); PasteEvent event = new PasteEvent(player, clipboard, uri, editSession, to); @@ -522,8 +524,8 @@ public class ClipboardCommands extends MethodCommands { @Switch('s') boolean selectPasted) throws WorldEditException { ClipboardHolder holder = session.getClipboard(); final Clipboard clipboard = holder.getClipboard(); - final Vector origin = clipboard.getOrigin(); - final Vector to = atOrigin ? origin : session.getPlacementPosition(player); + final BlockVector3 origin = clipboard.getOrigin(); + final BlockVector3 to = atOrigin ? origin : session.getPlacementPosition(player); checkPaste(player, editSession, to, holder, clipboard); Schematic schem = new Schematic(clipboard); @@ -531,9 +533,9 @@ public class ClipboardCommands extends MethodCommands { Region region = clipboard.getRegion().clone(); if (selectPasted) { - Vector clipboardOffset = clipboard.getRegion().getMinimumPoint().subtract(clipboard.getOrigin()); - Vector realTo = to.add(new Vector(holder.getTransform().apply(clipboardOffset))); - Vector max = realTo.add(new Vector(holder.getTransform().apply(region.getMaximumPoint().subtract(region.getMinimumPoint())))); + BlockVector3 clipboardOffset = clipboard.getRegion().getMinimumPoint().subtract(clipboard.getOrigin()); + BlockVector3 realTo = to.add(holder.getTransform().apply(clipboardOffset.toVector3()).toBlockPoint()); + BlockVector3 max = realTo.add(holder.getTransform().apply(region.getMaximumPoint().subtract(region.getMinimumPoint()).toVector3()).toBlockPoint()); RegionSelector selector = new CuboidRegionSelector(player.getWorld(), realTo, max); session.setRegionSelector(player.getWorld(), selector); selector.learnChanges(); @@ -577,12 +579,11 @@ public class ClipboardCommands extends MethodCommands { max = 1 ) @CommandPermissions("worldedit.clipboard.flip") - public void flip(Player player, LocalSession session, - @Optional(Direction.AIM) @Direction Vector direction) throws WorldEditException { + public void flip(Player player, LocalSession session, EditSession editSession, + @Optional(Direction.AIM) @Direction BlockVector3 direction) throws WorldEditException { ClipboardHolder holder = session.getClipboard(); - Clipboard clipboard = holder.getClipboard(); AffineTransform transform = new AffineTransform(); - transform = transform.scale(direction.positive().multiply(-2).add(1, 1, 1)); + transform = transform.scale(direction.abs().multiply(-2).add(1, 1, 1).toVector3()); holder.setTransform(transform.combine(holder.getTransform())); BBC.COMMAND_FLIPPED.send(player); } 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 c22b3d4c1..01784ee81 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 @@ -19,12 +19,16 @@ package com.sk89q.worldedit.command; -import com.sk89q.worldedit.Vector; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.transform.BlockTransformExtent; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.math.transform.CombinedTransform; import com.sk89q.worldedit.math.transform.Transform; @@ -67,8 +71,8 @@ public class FlattenedClipboardTransform { */ public Region getTransformedRegion() { Region region = original.getRegion(); - Vector minimum = region.getMinimumPoint(); - Vector maximum = region.getMaximumPoint(); + Vector3 minimum = region.getMinimumPoint().toVector3(); + Vector3 maximum = region.getMaximumPoint().toVector3(); Transform transformAround = new CombinedTransform( @@ -76,28 +80,27 @@ public class FlattenedClipboardTransform { transform, new AffineTransform().translate(original.getOrigin())); - // new Vector(minimum.getX(), minimum.getY(), minimum.getZ()) - // new Vector(maximum.getX(), maximum.getY(), maximum.getZ()) - Vector[] corners = new Vector[]{ + Vector3[] corners = new Vector3[] { minimum, maximum, - new Vector(maximum.getX(), minimum.getY(), minimum.getZ()), - new Vector(minimum.getX(), maximum.getY(), minimum.getZ()), - new Vector(minimum.getX(), minimum.getY(), maximum.getZ()), - new Vector(minimum.getX(), maximum.getY(), maximum.getZ()), - new Vector(maximum.getX(), minimum.getY(), maximum.getZ()), - new Vector(maximum.getX(), maximum.getY(), minimum.getZ())}; + minimum.withX(maximum.getX()), + minimum.withY(maximum.getY()), + minimum.withZ(maximum.getZ()), + maximum.withX(minimum.getX()), + maximum.withY(minimum.getY()), + maximum.withZ(minimum.getZ()) }; for (int i = 0; i < corners.length; i++) { - corners[i] = transformAround.apply(new Vector(corners[i])); + corners[i] = transformAround.apply(corners[i]); } - Vector newMinimum = corners[0]; - Vector newMaximum = corners[0]; - + MutableVector3 newMinimum = new MutableVector3(corners[0]); + MutableVector3 newMaximum = new MutableVector3(corners[0]); +// MutableVector3 cbv = new MutableVector3(); for (int i = 1; i < corners.length; i++) { - newMinimum = Vector.getMinimum(newMinimum, corners[i]); - newMaximum = Vector.getMaximum(newMaximum, corners[i]); + MutableVector3 cbv = new MutableVector3(corners[i]); + newMinimum = newMinimum.setComponents(newMinimum.getMinimum(cbv)); + newMaximum = newMaximum.setComponents(newMaximum.getMaximum(cbv)); } // After transformation, the points may not really sit on a block, @@ -106,7 +109,7 @@ public class FlattenedClipboardTransform { newMinimum.mutY(Math.ceil(Math.floor(newMinimum.getY()))); newMinimum.mutZ(Math.ceil(Math.floor(newMinimum.getZ()))); - return new CuboidRegion(newMinimum, newMaximum); + return new CuboidRegion(BlockVector3.at(newMinimum.getX(), newMinimum.getY(), newMinimum.getZ()), BlockVector3.at(newMaximum.getX(), newMaximum.getY(), newMaximum.getZ())); } /** 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 6daf351d0..c2754a935 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 @@ -53,9 +53,9 @@ public class GeneralCommands { @Command( aliases = { "/limit" }, - usage = "", + usage = "[limit]", desc = "Modify block change limit", - min = 1, + min = 0, max = 1 ) @CommandPermissions("worldedit.limit") @@ -64,7 +64,7 @@ public class GeneralCommands { LocalConfiguration config = worldEdit.getConfiguration(); boolean mayDisable = player.hasPermission("worldedit.limit.unrestricted"); - int limit = Math.max(-1, args.getInteger(0)); + int limit = args.argsLength() == 0 ? config.defaultChangeLimit : Math.max(-1, args.getInteger(0)); if (!mayDisable && config.maxChangeLimit > -1) { if (limit > config.maxChangeLimit) { player.printError("Your maximum allowable limit is " + config.maxChangeLimit + "."); @@ -164,7 +164,7 @@ public class GeneralCommands { boolean blocksOnly = args.hasFlag('b'); boolean itemsOnly = args.hasFlag('i'); - ItemType type = ItemTypes.parse(query); + ItemType type = ItemTypes.get(query); if (type != null) { actor.print(type.getId() + " (" + type.getName() + ")"); @@ -187,7 +187,7 @@ public class GeneralCommands { int found = 0; - for (ItemType searchType : ItemTypes.values) { + for (ItemType searchType : ItemTypes.values()) { if (found >= 15) { actor.print(BBC.getPrefix() + "Too many results!"); break; 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 27f80ed27..3e76b61c4 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 @@ -31,9 +31,11 @@ import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.Logging; -import com.sk89q.worldedit.*; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; + +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.mask.Mask; @@ -43,8 +45,10 @@ import com.sk89q.worldedit.function.visitor.RegionVisitor; import com.sk89q.worldedit.internal.annotation.Selection; import com.sk89q.worldedit.internal.expression.ExpressionException; import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.Region; -import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator.TreeType; import com.sk89q.worldedit.util.command.binding.Range; import com.sk89q.worldedit.util.command.binding.Switch; @@ -122,7 +126,7 @@ public class GenerationCommands extends MethodCommands { ) @CommandPermissions("worldedit.generation.image") @Logging(PLACEMENT) - public void image(Player player, LocalSession session, EditSession editSession, String arg, @Optional("true") boolean randomize, @Optional("100") int threshold, @Optional Vector2D dimensions) throws WorldEditException, ParameterException, IOException { + public void image(Player player, LocalSession session, EditSession editSession, String arg, @Optional("true") boolean randomize, @Optional("100") int threshold, @Optional BlockVector2 dimensions) throws WorldEditException, ParameterException, IOException { TextureUtil tu = Fawe.get().getCachedTextureUtil(randomize, 0, threshold); URL url = new URL(arg); if (!url.getHost().equalsIgnoreCase("i.imgur.com") && !url.getHost().equalsIgnoreCase("empcraft.com")) { @@ -134,14 +138,16 @@ public class GenerationCommands extends MethodCommands { image = ImageUtil.getScaledInstance(image, dimensions.getBlockX(), dimensions.getBlockZ(), RenderingHints.VALUE_INTERPOLATION_BILINEAR, false); } - MutableBlockVector pos1 = new MutableBlockVector(player.getLocation().toVector()); - MutableBlockVector pos2 = new MutableBlockVector(pos1.add(image.getWidth() - 1, 0, image.getHeight() - 1)); +// MutableBlockVector3 pos1 = new MutableBlockVector3(player.getLocation().toBlockPoint()); +// MutableBlockVector3 pos2 = new MutableBlockVector3(pos1.add(image.getWidth() - 1, 0, image.getHeight() - 1)); + BlockVector3 pos1 = player.getLocation().toBlockPoint(); + BlockVector3 pos2 = pos1.add(image.getWidth() - 1, 0, image.getHeight() - 1); CuboidRegion region = new CuboidRegion(pos1, pos2); int[] count = new int[1]; final BufferedImage finalImage = image; RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { @Override - public boolean apply(Vector pos) throws WorldEditException { + public boolean apply(BlockVector3 pos) throws WorldEditException { try { int x = pos.getBlockX() - pos1.getBlockX(); int z = pos.getBlockZ() - pos1.getBlockZ(); @@ -191,10 +197,10 @@ public class GenerationCommands extends MethodCommands { ) @CommandPermissions("worldedit.generation.cylinder") @Logging(PLACEMENT) - public void hcyl(FawePlayer fp, Player player, LocalSession session, EditSession editSession, Pattern pattern, Vector2D radius, @Optional("1") int height, @Range(min = 1) @Optional("1") double thickness, CommandContext context) throws WorldEditException, ParameterException { + public void hcyl(FawePlayer fp, Player player, LocalSession session, EditSession editSession, Pattern pattern, BlockVector2 radius, @Optional("1") int height, @Range(min = 1) @Optional("1") double thickness, CommandContext context) throws WorldEditException, ParameterException { double max = MathMan.max(radius.getBlockX(), radius.getBlockZ()); worldEdit.checkMaxRadius(max); - Vector pos = session.getPlacementPosition(player); + BlockVector3 pos = session.getPlacementPosition(player); fp.checkConfirmationRadius(() -> { int affected = editSession.makeHollowCylinder(pos, pattern, radius.getX(), radius.getZ(), Math.min(256, height), thickness - 1); BBC.VISITOR_BLOCK.send(fp, affected); @@ -216,10 +222,10 @@ public class GenerationCommands extends MethodCommands { ) @CommandPermissions("worldedit.generation.cylinder") @Logging(PLACEMENT) - public void cyl(FawePlayer fp, Player player, LocalSession session, EditSession editSession, Pattern pattern, Vector2D radius, @Optional("1") int height, @Switch('h') boolean hollow, CommandContext context) throws WorldEditException, ParameterException { + public void cyl(FawePlayer fp, Player player, LocalSession session, EditSession editSession, Pattern pattern, BlockVector2 radius, @Optional("1") int height, @Switch('h') boolean hollow, CommandContext context) throws WorldEditException, ParameterException { double max = MathMan.max(radius.getBlockX(), radius.getBlockZ()); worldEdit.checkMaxRadius(max); - Vector pos = session.getPlacementPosition(player); + BlockVector3 pos = session.getPlacementPosition(player); fp.checkConfirmationRadius(() -> { int affected = editSession.makeCylinder(pos, pattern, radius.getX(), radius.getZ(), Math.min(256, height), !hollow); BBC.VISITOR_BLOCK.send(fp, affected); @@ -240,7 +246,7 @@ public class GenerationCommands extends MethodCommands { ) @CommandPermissions("worldedit.generation.sphere") @Logging(PLACEMENT) - public void hsphere(FawePlayer fp, Player player, LocalSession session, EditSession editSession, Pattern pattern, Vector radius, @Optional("false") boolean raised, CommandContext context) throws WorldEditException, ParameterException { + public void hsphere(FawePlayer fp, Player player, LocalSession session, EditSession editSession, Pattern pattern, BlockVector3 radius, @Optional("false") boolean raised, CommandContext context) throws WorldEditException, ParameterException { sphere(fp, player, session, editSession, pattern, radius, raised, true, context); } @@ -259,11 +265,11 @@ public class GenerationCommands extends MethodCommands { ) @CommandPermissions("worldedit.generation.sphere") @Logging(PLACEMENT) - public void sphere(FawePlayer fp, Player player, LocalSession session, EditSession editSession, Pattern pattern, Vector radius, @Optional("false") boolean raised, @Switch('h') boolean hollow, CommandContext context) throws WorldEditException, ParameterException { + public void sphere(FawePlayer fp, Player player, LocalSession session, EditSession editSession, Pattern pattern, BlockVector3 radius, @Optional("false") boolean raised, @Switch('h') boolean hollow, CommandContext context) throws WorldEditException, ParameterException { double max = MathMan.max(radius.getBlockX(), radius.getBlockY(), radius.getBlockZ()); worldEdit.checkMaxRadius(max); - Vector pos = session.getPlacementPosition(player); - Vector finalPos = raised ? pos.add(0, radius.getY(), 0) : pos; + BlockVector3 pos = session.getPlacementPosition(player); + BlockVector3 finalPos = raised ? pos.add(0, radius.getY(), 0) : pos; fp.checkConfirmationRadius(() -> { int affected = editSession.makeSphere(finalPos, pattern, radius.getX(), radius.getY(), radius.getZ(), !hollow); player.findFreePosition(); @@ -325,14 +331,15 @@ public class GenerationCommands extends MethodCommands { @CommandPermissions("worldedit.generation.pyramid") @Logging(PLACEMENT) public void pyramid(FawePlayer fp, Player player, LocalSession session, EditSession editSession, Pattern pattern, @Range(min = 1) int size, @Switch('h') boolean hollow, CommandContext context) throws WorldEditException, ParameterException { + BlockVector3 pos = session.getPlacementPosition(player); worldEdit.checkMaxRadius(size); - Vector pos = session.getPlacementPosition(player); fp.checkConfirmationRadius(() -> { int affected = editSession.makePyramid(pos, pattern, size, !hollow); player.findFreePosition(); BBC.VISITOR_BLOCK.send(fp, affected); }, getArguments(context), size, context); } + @Command( aliases = {"/generate", "/gen", "/g"}, @@ -362,38 +369,40 @@ public class GenerationCommands extends MethodCommands { @Switch('h') boolean hollow, @Switch('r') boolean useRawCoords, @Switch('o') boolean offset, - @Switch('c') boolean offsetCenter, - CommandContext context) throws WorldEditException, ParameterException { - final Vector zero; - Vector unit; + @Switch('c') boolean offsetCenter, CommandContext context) throws WorldEditException { + + final Vector3 zero; + Vector3 unit; if (useRawCoords) { - zero = Vector.ZERO; - unit = Vector.ONE; + zero = Vector3.ZERO; + unit = Vector3.ONE; } else if (offset) { - zero = session.getPlacementPosition(player); - unit = Vector.ONE; + zero = session.getPlacementPosition(player).toVector3(); + unit = Vector3.ONE; } else if (offsetCenter) { - final Vector min = region.getMinimumPoint(); - final Vector max = region.getMaximumPoint(); + final Vector3 min = region.getMinimumPoint().toVector3(); + final Vector3 max = region.getMaximumPoint().toVector3(); zero = max.add(min).multiply(0.5); - unit = Vector.ONE; + unit = Vector3.ONE; } else { - final Vector min = region.getMinimumPoint(); - final Vector max = region.getMaximumPoint(); + final Vector3 min = region.getMinimumPoint().toVector3(); + final Vector3 max = region.getMaximumPoint().toVector3(); zero = max.add(min).multiply(0.5); unit = max.subtract(zero); - if (unit.getX() == 0) unit.mutX(1); - if (unit.getY() == 0) unit.mutY(1); - if (unit.getZ() == 0) unit.mutZ(1); + 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; fp.checkConfirmationRegion(() -> { try { - final int affected = editSession.makeShape(region, zero, unit, pattern, expression, hollow); + final int affected = editSession.makeShape(region, zero, unit1, pattern, expression, hollow); player.findFreePosition(); BBC.VISITOR_BLOCK.send(fp, affected); } catch (ExpressionException e) { @@ -430,37 +439,39 @@ public class GenerationCommands extends MethodCommands { @Switch('h') boolean hollow, @Switch('r') boolean useRawCoords, @Switch('o') boolean offset, - @Switch('c') boolean offsetCenter, - CommandContext context) throws WorldEditException, ParameterException { - final Vector zero; - Vector unit; + @Switch('c') boolean offsetCenter, CommandContext context) throws WorldEditException { + final Vector3 zero; + Vector3 unit; if (useRawCoords) { - zero = Vector.ZERO; - unit = Vector.ONE; + zero = Vector3.ZERO; + unit = Vector3.ONE; } else if (offset) { - zero = session.getPlacementPosition(player); - unit = Vector.ONE; + zero = session.getPlacementPosition(player).toVector3(); + unit = Vector3.ONE; } else if (offsetCenter) { - final Vector min = region.getMinimumPoint(); - final Vector max = region.getMaximumPoint(); + final Vector3 min = region.getMinimumPoint().toVector3(); + final Vector3 max = region.getMaximumPoint().toVector3(); zero = max.add(min).multiply(0.5); - unit = Vector.ONE; + unit = Vector3.ONE; } else { - final Vector min = region.getMinimumPoint(); - final Vector max = region.getMaximumPoint(); + final Vector3 min = region.getMinimumPoint().toVector3(); + final Vector3 max = region.getMaximumPoint().toVector3(); zero = max.add(min).multiply(0.5); unit = max.subtract(zero); - if (unit.getX() == 0) unit.mutX(1); - if (unit.getY() == 0) unit.mutY(1); - if (unit.getZ() == 0) unit.mutZ(1); + 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; + fp.checkConfirmationRegion(() -> { try { - final int affected = editSession.makeBiomeShape(region, zero, unit, target, expression, hollow); + final int affected = editSession.makeBiomeShape(region, zero, unit1, target, expression, hollow); player.findFreePosition(); BBC.VISITOR_FLAT.send(fp, affected); } catch (ExpressionException e) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/HelpBuilder.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/HelpBuilder.java index 11f87e904..0947bcb3b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/HelpBuilder.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/HelpBuilder.java @@ -51,14 +51,14 @@ public abstract class HelpBuilder implements Runnable { } boolean isRootLevel = true; - List visited = new ArrayList(); + List visited = new ArrayList<>(); // Create the message if (callable instanceof Dispatcher) { Dispatcher dispatcher = (Dispatcher) callable; // Get a list of aliases - List aliases = new ArrayList(dispatcher.getCommands()); + List aliases = new ArrayList<>(dispatcher.getCommands()); List prefixes = Collections.nCopies(aliases.size(), ""); // Group by callable @@ -174,7 +174,7 @@ public abstract class HelpBuilder implements Runnable { return; } dispatcher = (Dispatcher) callable; - aliases = new ArrayList(dispatcher.getCommands()); + aliases = new ArrayList<>(dispatcher.getCommands()); prefixes = Collections.nCopies(aliases.size(), ""); } else { aliases = new ArrayList<>(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/HistoryCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/HistoryCommands.java index 76e734dd0..af5716eb4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/HistoryCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/HistoryCommands.java @@ -39,6 +39,7 @@ import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.worldedit.*; import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.command.binding.Range; @@ -112,7 +113,7 @@ public class HistoryCommands extends MethodCommands { RollbackOptimizedHistory rollback = new RollbackOptimizedHistory(world, uuid, Integer.parseInt(name.substring(0, name.length() - 3))); DiskStorageHistory.DiskStorageSummary summary = rollback.summarize(RegionWrapper.GLOBAL(), false); if (summary != null) { - rollback.setDimensions(new Vector(summary.minX, 0, summary.minZ), new Vector(summary.maxX, 255, summary.maxZ)); + rollback.setDimensions(BlockVector3.at(summary.minX, 0, summary.minZ), BlockVector3.at(summary.maxX, 255, summary.maxZ)); rollback.setTime(historyFile.lastModified()); RollbackDatabase db = DBHandler.IMP.getDatabase(world); db.logEdit(rollback); @@ -165,10 +166,12 @@ public class HistoryCommands extends MethodCommands { radius = Math.max(Math.min(500, radius), 0); final World world = player.getWorld(); Location origin = player.getLocation(); - Vector bot = origin.toVector().subtract(radius, radius, radius); - bot.mutY(Math.max(0, bot.getY())); - Vector top = origin.toVector().add(radius, radius, radius); - top.mutY(Math.min(255, top.getY())); + BlockVector3 bot = origin.toBlockPoint().subtract(radius, radius, radius); + bot = bot.withY(Math.max(0, bot.getY())); +// bot.mutY(Math.max(0, bot.getY())); + BlockVector3 top = origin.toBlockPoint().add(radius, radius, radius); + bot = bot.withY(Math.min(255, top.getY())); +// top.mutY(Math.min(255, top.getY())); RollbackDatabase database = DBHandler.IMP.getDatabase(world); final AtomicInteger count = new AtomicInteger(); final FawePlayer fp = FawePlayer.wrap(player); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/MaskCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/MaskCommands.java index cdd5bdeb4..6f8266455 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/MaskCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/MaskCommands.java @@ -4,15 +4,16 @@ import com.boydti.fawe.object.mask.*; import com.sk89q.minecraft.util.commands.Command; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.*; import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.ExpressionException; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment; import com.sk89q.worldedit.session.request.RequestSelection; import com.sk89q.worldedit.util.command.binding.Switch; @@ -129,7 +130,7 @@ public class MaskCommands extends MethodCommands { max = 4 ) public Mask offset(double x, double y, double z, Mask mask) { - return new OffsetMask(mask, new Vector(x, y, z)); + return new OffsetMask(mask, BlockVector3.at(x, y, z)); } @Command( @@ -389,7 +390,7 @@ public class MaskCommands extends MethodCommands { max = 1 ) public Mask below(Mask mask) throws ExpressionException { - OffsetMask offsetMask = new OffsetMask(mask, new Vector(0, 1, 0)); + OffsetMask offsetMask = new OffsetMask(mask, BlockVector3.at(0, 1, 0)); return new MaskIntersection(offsetMask, Masks.negate(mask)); } @@ -401,7 +402,7 @@ public class MaskCommands extends MethodCommands { max = 1 ) public Mask above(Mask mask) throws ExpressionException { - OffsetMask offsetMask = new OffsetMask(mask, new Vector(0, -1, 0)); + OffsetMask offsetMask = new OffsetMask(mask, BlockVector3.at(0, -1, 0)); return new MaskIntersection(offsetMask, Masks.negate(mask)); } @@ -438,7 +439,7 @@ public class MaskCommands extends MethodCommands { ) public Mask expression(Extent extent, String input) throws ExpressionException { Expression exp = Expression.compile(input, "x", "y", "z"); - WorldEditExpressionEnvironment env = new WorldEditExpressionEnvironment(extent, Vector.ONE, Vector.ZERO); + WorldEditExpressionEnvironment env = new WorldEditExpressionEnvironment(extent, Vector3.ONE, Vector3.ZERO); exp.setEnvironment(env); return new ExpressionMask(exp); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/NavigationCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/NavigationCommands.java index a52446d45..af2d20284 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/NavigationCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/NavigationCommands.java @@ -45,7 +45,6 @@ import static com.sk89q.minecraft.util.commands.Logging.LogMode.POSITION; @Command(aliases = {}, desc = "Commands for moving the player around: [More Info](https://goo.gl/uQTUiT)") public class NavigationCommands { - @SuppressWarnings("unused") private final WorldEdit worldEdit; /** diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/OptionsCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/OptionsCommands.java index 74ff80ade..238220940 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/OptionsCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/OptionsCommands.java @@ -13,7 +13,7 @@ import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.input.ParserContext; @@ -284,7 +284,7 @@ public class OptionsCommands { int found = 0; - for (ItemType searchType : ItemTypes.values) { + for (ItemType searchType : ItemTypes.values()) { if (found >= 15) { actor.print(BBC.getPrefix() + "Too many results!"); break; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/PatternCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/PatternCommands.java index b46ffe82e..62abf2d76 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/PatternCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/PatternCommands.java @@ -16,12 +16,14 @@ import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.pattern.ClipboardPattern; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.RandomPattern; import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.ExpressionException; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment; import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.util.command.binding.Range; @@ -45,7 +47,7 @@ public class PatternCommands extends MethodCommands { public PatternCommands(WorldEdit worldEdit) { super(worldEdit); } - + @Command( aliases = {"#existing", "#*", "*", ".*"}, desc = "Use the block that is already there", @@ -190,7 +192,7 @@ public class PatternCommands extends MethodCommands { clipboards = Collections.singletonList(clipboard); break; default: - MultiClipboardHolder multi = ClipboardFormat.SCHEMATIC.loadAllFromInput(player, location, null, true); + MultiClipboardHolder multi = ClipboardFormats.loadAllFromInput(player, location, null, true); clipboards = multi != null ? multi.getHolders() : null; break; } @@ -266,7 +268,7 @@ public class PatternCommands extends MethodCommands { min = 1, max = 1 ) - public Pattern data(Actor actor, LocalSession session, Extent extent, BaseBiome biome) { + public Pattern biome(Actor actor, LocalSession session, Extent extent, BaseBiome biome) { return new BiomePattern(extent, biome); } @@ -426,7 +428,7 @@ public class PatternCommands extends MethodCommands { ) public Pattern expression(Actor actor, LocalSession session, Extent extent, String input) throws ExpressionException { Expression exp = Expression.compile(input, "x", "y", "z"); - WorldEditExpressionEnvironment env = new WorldEditExpressionEnvironment(extent, Vector.ONE, Vector.ZERO); + WorldEditExpressionEnvironment env = new WorldEditExpressionEnvironment(extent, Vector3.ONE, Vector3.ZERO); exp.setEnvironment(env); return new ExpressionPattern(exp); } 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 7dab9b06c..64d3f250c 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 @@ -34,9 +34,11 @@ import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.Logging; -import com.sk89q.worldedit.*; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; + +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.function.GroundFunction; @@ -51,13 +53,15 @@ import com.sk89q.worldedit.function.visitor.LayerVisitor; import com.sk89q.worldedit.internal.annotation.Direction; import com.sk89q.worldedit.internal.annotation.Selection; import com.sk89q.worldedit.internal.expression.ExpressionException; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.convolution.GaussianKernel; import com.sk89q.worldedit.math.convolution.HeightMap; import com.sk89q.worldedit.math.convolution.HeightMapFilter; import com.sk89q.worldedit.math.noise.RandomNoise; import com.sk89q.worldedit.regions.*; import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator.TreeType; import com.sk89q.worldedit.util.command.binding.Range; import com.sk89q.worldedit.util.command.binding.Switch; @@ -67,6 +71,7 @@ import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.biome.Biomes; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.registry.BiomeRegistry; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -113,7 +118,7 @@ public class RegionCommands extends MethodCommands { if (selection == null) { final int cx = loc.x >> 4; final int cz = loc.z >> 4; - selection = new CuboidRegion(new Vector(cx - 8, 0, cz - 8).multiply(16), new Vector(cx + 8, 0, cz + 8).multiply(16)); + 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(loc.world, selection, FaweQueue.RelightMode.ALL); BBC.LIGHTING_PROPOGATE_SELECTION.send(fp, count); @@ -147,7 +152,7 @@ public class RegionCommands extends MethodCommands { if (selection == null) { final int cx = loc.x >> 4; final int cz = loc.z >> 4; - selection = new CuboidRegion(new Vector(cx - 8, 0, cz - 8).multiply(16), new Vector(cx + 8, 0, cz + 8).multiply(16)); + 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(loc.world, selection, FaweQueue.RelightMode.NONE); BBC.UPDATED_LIGHTING_SELECTION.send(fp, count); @@ -164,7 +169,7 @@ public class RegionCommands extends MethodCommands { BBC.NO_BLOCK.send(player); return; } - CompoundTag nbt = editSession.getBlock(pos.toVector()).getNbtData(); + CompoundTag nbt = editSession.getFullBlock(pos.toBlockPoint()).getNbtData(); if (nbt != null) { player.print(nbt.getValue().toString()); } else { @@ -185,11 +190,11 @@ public class RegionCommands extends MethodCommands { final int cx = loc.x >> 4; final int cz = loc.z >> 4; final NMSMappedFaweQueue queue = (NMSMappedFaweQueue) fp.getFaweQueue(false); - for (Vector pt : region) { + for (BlockVector3 pt : region) { queue.setBlockLight((int) pt.getX(), (int) pt.getY(), (int) pt.getZ(), value); } int count = 0; - for (Vector2D chunk : region.getChunks()) { + for (BlockVector2 chunk : region.getChunks()) { queue.sendChunk(queue.getFaweChunk(chunk.getBlockX(), chunk.getBlockZ())); count++; } @@ -209,11 +214,11 @@ public class RegionCommands extends MethodCommands { final int cx = loc.x >> 4; final int cz = loc.z >> 4; final NMSMappedFaweQueue queue = (NMSMappedFaweQueue) fp.getFaweQueue(false); - for (Vector pt : region) { + for (BlockVector3 pt : region) { queue.setSkyLight((int) pt.getX(), (int) pt.getY(), (int) pt.getZ(), value); } int count = 0; - for (Vector2D chunk : region.getChunks()) { + for (BlockVector2 chunk : region.getChunks()) { queue.sendChunk(queue.getFaweChunk(chunk.getBlockX(), chunk.getBlockZ())); count++; } @@ -247,8 +252,8 @@ public class RegionCommands extends MethodCommands { } CuboidRegion cuboidregion = (CuboidRegion) region; - Vector pos1 = cuboidregion.getPos1(); - Vector pos2 = cuboidregion.getPos2(); + BlockVector3 pos1 = cuboidregion.getPos1(); + BlockVector3 pos2 = cuboidregion.getPos2(); int blocksChanged = editSession.drawLine(pattern, pos1, pos2, thickness, !shell); BBC.VISITOR_BLOCK.send(player, blocksChanged); @@ -282,8 +287,8 @@ public class RegionCommands extends MethodCommands { worldEdit.checkMaxRadius(thickness); player.checkConfirmationRegion(() -> { - ConvexPolyhedralRegion cpregion = (ConvexPolyhedralRegion) region; - List vectors = new ArrayList(cpregion.getVertices()); + ConvexPolyhedralRegion cpregion = (ConvexPolyhedralRegion) region; + List vectors = new ArrayList<>(cpregion.getVertices()); int blocksChanged = editSession.drawSpline(pattern, vectors, 0, 0, 0, 10, thickness, !shell); @@ -327,8 +332,7 @@ public class RegionCommands extends MethodCommands { @Logging(REGION) public void set(FawePlayer player, LocalSession session, EditSession editSession, @Selection Region selection, Pattern to, CommandContext context) throws WorldEditException { player.checkConfirmationRegion(() -> { - int affected; - affected = editSession.setBlocks(selection, to); + int affected = editSession.setBlocks(selection, to); if (affected != 0) { BBC.OPERATION.send(player, affected); if (!player.hasPermission("fawe.tips")) @@ -364,20 +368,19 @@ public class RegionCommands extends MethodCommands { @Logging(REGION) public void lay(FawePlayer player, EditSession editSession, @Selection Region region, Pattern pattern, CommandContext context) throws WorldEditException { player.checkConfirmationRegion(() -> { - Vector min = region.getMinimumPoint(); - Vector max = region.getMaximumPoint(); + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); int maxY = max.getBlockY(); int width = region.getWidth(); int height = region.getLength(); int bx = min.getBlockX(); int bz = min.getBlockZ(); - Iterable flat = Regions.asFlatRegion(region).asFlatRegion(); - Iterator iter = new Fast2DIterator(flat, editSession).iterator(); + Iterable flat = Regions.asFlatRegion(region).asFlatRegion(); + Iterator iter = new Fast2DIterator(flat, editSession).iterator(); int y = 0; int affected = 0; - MutableBlockVector mutable = new MutableBlockVector(); while (iter.hasNext()) { - Vector2D pos = iter.next(); + BlockVector2 pos = iter.next(); int x = pos.getBlockX(); int z = pos.getBlockZ(); y = editSession.getNearestSurfaceTerrainBlock(x, z, y, 0, maxY); @@ -465,8 +468,8 @@ public class RegionCommands extends MethodCommands { @CommandPermissions("worldedit.region.smoothsnow") @Logging(REGION) public void smooth(FawePlayer player, EditSession editSession, @Selection Region region, @Optional("1") int iterations, @Switch('n') boolean affectNatural, @Switch('s') boolean snow, CommandContext context) throws WorldEditException { - Vector min = region.getMinimumPoint(); - Vector max = region.getMaximumPoint(); + 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 = FawePlayer.wrap(player).getLimit(); if (volume >= limit.MAX_CHECKS) { @@ -537,7 +540,7 @@ public class RegionCommands extends MethodCommands { public void move(FawePlayer player, LocalSession session, EditSession editSession, @Selection Region region, @Optional("1") @Range(min = 1) int count, - @Optional(Direction.AIM) @Direction Vector direction, + @Optional(Direction.AIM) @Direction(includeDiagonals = true) BlockVector3 direction, @Optional("air") Pattern replace, @Switch('b') boolean copyBiomes, @Switch('e') boolean skipEntities, @@ -604,7 +607,7 @@ public class RegionCommands extends MethodCommands { public void stack(FawePlayer player, LocalSession session, EditSession editSession, @Selection Region region, @Optional("1") @Range(min = 1) int count, - @Optional(Direction.AIM) @Direction Vector direction, + @Optional(Direction.AIM) @Direction(includeDiagonals = true) BlockVector3 direction, @Switch('s') boolean moveSelection, @Switch('b') boolean copyBiomes, @Switch('e') boolean skipEntities, @@ -617,8 +620,8 @@ public class RegionCommands extends MethodCommands { if (moveSelection) { try { - final Vector size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); - Vector shiftVector = new Vector(direction.getX() * size.getX() * count, direction.getY() * size.getY() * count, direction.getZ() * size.getZ() * count); + final BlockVector3 size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); + BlockVector3 shiftVector = BlockVector3.at(direction.getX() * size.getX() * count, direction.getY() * size.getY() * count, direction.getZ() * size.getZ() * count); region.shift(shiftVector); session.getRegionSelector(player.getWorld()).learnChanges(); @@ -653,29 +656,30 @@ public class RegionCommands extends MethodCommands { @Switch('r') boolean useRawCoords, @Switch('o') boolean offset, CommandContext context) throws WorldEditException { - final Vector zero; - Vector unit; - + final Vector3 zero; + Vector3 unit; if (useRawCoords) { - zero = Vector.ZERO; - unit = Vector.ONE; + zero = Vector3.ZERO; + unit = Vector3.ONE; } else if (offset) { - zero = session.getPlacementPosition(player); - unit = Vector.ONE; + zero = session.getPlacementPosition(player).toVector3(); + unit = Vector3.ONE; } else { - final Vector min = region.getMinimumPoint(); - final Vector max = region.getMaximumPoint(); + final Vector3 min = region.getMinimumPoint().toVector3(); + final Vector3 max = region.getMaximumPoint().toVector3(); - zero = max.add(min).multiply(0.5); + zero = max.add(min).divide(2); unit = max.subtract(zero); - if (unit.getX() == 0) unit.mutX(1); - if (unit.getY() == 0) unit.mutY(1); - if (unit.getZ() == 0) unit.mutZ(1); + 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; fp.checkConfirmationRegion(() -> { try { - final int affected = editSession.deformRegion(region, zero, unit, expression); + final int affected = editSession.deformRegion(region, zero, unit1, expression); player.findFreePosition(); BBC.VISITOR_BLOCK.send(fp, affected); } catch (ExpressionException e) { 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 d7686aa8c..2ce053148 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 @@ -45,6 +45,7 @@ import com.sk89q.worldedit.event.extent.PlayerSaveClipboardEvent; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter; @@ -99,13 +100,13 @@ public class SchematicCommands extends MethodCommands { @Deprecated @CommandPermissions({"worldedit.clipboard.load", "worldedit.schematic.load", "worldedit.schematic.load.web", "worldedit.schematic.load.asset"}) public void loadall(final Player player, final LocalSession session, @Optional("schematic") final String formatName, final String filename, @Switch('r') boolean randomRotate) throws FilenameException { - final ClipboardFormat format = ClipboardFormat.findByAlias(formatName); + final ClipboardFormat format = ClipboardFormats.findByAlias(formatName); if (format == null) { BBC.CLIPBOARD_INVALID_FORMAT.send(player, formatName); return; } try { - MultiClipboardHolder all = format.loadAllFromInput(player, filename, null, true); + MultiClipboardHolder all = ClipboardFormats.loadAllFromInput(player, filename, null, true); if (all != null) { session.addClipboard(all); BBC.SCHEMATIC_LOADED.send(player, filename); @@ -175,7 +176,7 @@ public class SchematicCommands extends MethodCommands { @CommandPermissions({"worldedit.schematic.remap"}) public void remap(final Player player, final LocalSession session) throws WorldEditException { ClipboardRemapper remapper; - if (Fawe.imp().getPlatform().equalsIgnoreCase("nukkit")) { + if (false) { remapper = new ClipboardRemapper(ClipboardRemapper.RemapPlatform.PC, ClipboardRemapper.RemapPlatform.PE); } else { remapper = new ClipboardRemapper(ClipboardRemapper.RemapPlatform.PE, ClipboardRemapper.RemapPlatform.PC); @@ -192,7 +193,7 @@ public class SchematicCommands extends MethodCommands { @CommandPermissions({"worldedit.clipboard.load", "worldedit.schematic.load", "worldedit.schematic.load.asset", "worldedit.schematic.load.web", "worldedit.schematic.load.other"}) public void load(final Player player, final LocalSession session, @Optional() final String formatName, String filename) throws FilenameException { final LocalConfiguration config = this.worldEdit.getConfiguration(); - ClipboardFormat format = formatName == null ? null : ClipboardFormat.findByAlias(formatName); + ClipboardFormat format = formatName == null ? null : ClipboardFormats.findByAlias(formatName); InputStream in = null; try { URI uri; @@ -207,7 +208,7 @@ public class SchematicCommands extends MethodCommands { ReadableByteChannel rbc = Channels.newChannel(url.openStream()); in = Channels.newInputStream(rbc); uri = url.toURI(); - if (format == null) format = ClipboardFormat.SCHEMATIC; + if (format == null) format = BuiltInClipboardFormat.MCEDIT_SCHEMATIC; } else { if (!player.hasPermission("worldedit.schematic.load") && !player.hasPermission("worldedit.clipboard.load")) { BBC.NO_PERM.send(player, "worldedit.clipboard.load"); @@ -235,7 +236,7 @@ public class SchematicCommands extends MethodCommands { } if (format == null && filename.matches(".*\\.[\\w].*")) { String extension = filename.substring(filename.lastIndexOf('.') + 1, filename.length()); - format = ClipboardFormat.findByExtension(extension); + format = ClipboardFormats.findByExtension(extension); } f = MainUtil.resolve(dir, filename, format, false); } @@ -250,7 +251,7 @@ public class SchematicCommands extends MethodCommands { return; } if (format == null) { - format = ClipboardFormat.findByFile(f); + format = ClipboardFormats.findByFile(f); if (format == null) { BBC.CLIPBOARD_INVALID_FORMAT.send(player, f.getName()); return; @@ -276,12 +277,12 @@ public class SchematicCommands extends MethodCommands { } } - @Command(aliases = {"save"}, usage = "[format] ", desc = "Save a schematic into your clipboard") + @Command(aliases = {"save"}, usage = "[format] ", desc = "Save a schematic into your clipboard", help = "The default format for 1.13 is schem") @Deprecated @CommandPermissions({"worldedit.clipboard.save", "worldedit.schematic.save", "worldedit.schematic.save.other"}) public void save(final Player player, final LocalSession session, @Optional("schem") final String formatName, String filename, @Switch('g') boolean global) throws CommandException, WorldEditException { final LocalConfiguration config = this.worldEdit.getConfiguration(); - final ClipboardFormat format = ClipboardFormat.findByAlias(formatName); + final ClipboardFormat format = ClipboardFormats.findByAlias(formatName); if (format == null) { player.printError("Unknown schematic format: " + formatName); return; @@ -298,14 +299,14 @@ public class SchematicCommands extends MethodCommands { filename = filename.substring(3); } } - File f = this.worldEdit.getSafeSaveFile(player, dir, filename, format.getExtension(), format.getExtension()); - if (f.getName().replaceAll("." + format.getExtension(), "").isEmpty()) { + File f = this.worldEdit.getSafeSaveFile(player, dir, filename, format.getPrimaryFileExtension(), format.getPrimaryFileExtension()); + if (f.getName().replaceAll("." + format.getPrimaryFileExtension(), "").isEmpty()) { File directory = f.getParentFile(); if (directory.exists()) { int max = MainUtil.getMaxFileId(directory); - f = new File(directory, max + "." + format.getExtension()); + f = new File(directory, max + "." + format.getPrimaryFileExtension()); } else { - f = new File(directory, "1." + format.getExtension()); + f = new File(directory, "1." + format.getPrimaryFileExtension()); } } final File parent = f.getParentFile(); @@ -477,9 +478,9 @@ public class SchematicCommands extends MethodCommands { Message m = new Message(BBC.SCHEMATIC_FORMAT).newline(); String baseCmd = Commands.getAlias(SchematicCommands.class, "schematic") + " " + Commands.getAlias(SchematicCommands.class, "save"); boolean first = true; - for (final ClipboardFormat format : ClipboardFormat.values) { + for (final ClipboardFormat format : ClipboardFormats.getAll()) { StringBuilder builder = new StringBuilder(); - builder.append(format.name()).append(": "); + builder.append(format.getName()).append(": "); for (final String lookupName : format.getAliases()) { if (!first) { builder.append(", "); @@ -487,7 +488,7 @@ public class SchematicCommands extends MethodCommands { builder.append(lookupName); first = false; } - String cmd = baseCmd + " " + format.name() + " "; + String cmd = baseCmd + " " + format.getName() + " "; m.text(builder).suggestTip(cmd).newline(); first = true; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ScriptingCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ScriptingCommands.java index a4ad5779b..a8e9e911f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ScriptingCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ScriptingCommands.java @@ -79,8 +79,6 @@ public class ScriptingCommands { } public static T runScript(Actor actor, File f, String[] args, @Nullable Function processor) throws WorldEditException { - Request.reset(); - String filename = f.getPath(); int index = filename.lastIndexOf("."); String ext = filename.substring(index + 1, filename.length()); @@ -139,7 +137,7 @@ public class ScriptingCommands { engine.setTimeLimit(worldEdit.getConfiguration().scriptTimeout); - Map vars = new HashMap(); + Map vars = new HashMap<>(); vars.put("argv", args); vars.put("actor", actor); @@ -188,7 +186,7 @@ public class ScriptingCommands { player.printError("More info: https://github.com/boy0001/CraftScripts/"); return; } - this.worldEdit.runScript(LocationMaskedPlayerWrapper.unwrap(player), f, scriptArgs); + runScript(LocationMaskedPlayerWrapper.unwrap(player), f, scriptArgs); } @Command(aliases = {".s"}, usage = "[args...]", desc = "Execute last CraftScript", min = 0, max = -1) 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 e9b5efc5a..c00ac21f0 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 @@ -32,20 +32,18 @@ import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.Logging; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; + import com.sk89q.worldedit.blocks.BaseItemStack; -import com.sk89q.worldedit.blocks.BlockType; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extension.platform.permission.ActorSelectorLimits; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionOperationException; import com.sk89q.worldedit.regions.RegionSelector; @@ -65,18 +63,13 @@ import com.sk89q.worldedit.util.formatting.Style; import com.sk89q.worldedit.util.formatting.StyledFragment; import com.sk89q.worldedit.util.formatting.component.CommandListBox; import com.sk89q.worldedit.world.World; -import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.item.ItemTypes; import com.sk89q.worldedit.world.storage.ChunkStore; import java.io.File; -import java.net.MalformedURLException; import java.net.URI; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.Set; import static com.sk89q.minecraft.util.commands.Logging.LogMode.POSITION; @@ -103,19 +96,19 @@ public class SelectionCommands { ) @Logging(POSITION) @CommandPermissions("worldedit.selection.pos") - public void pos1(Player player, LocalSession session, CommandContext args) throws WorldEditException { - Vector pos; + public void pos1(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { + BlockVector3 pos; if (args.argsLength() == 1) { if (args.getString(0).matches("-?\\d+,-?\\d+,-?\\d+")) { String[] coords = args.getString(0).split(","); - pos = new Vector(Integer.parseInt(coords[0]), Integer.parseInt(coords[1]), Integer.parseInt(coords[2])); + pos = BlockVector3.at(Integer.parseInt(coords[0]), Integer.parseInt(coords[1]), Integer.parseInt(coords[2])); } else { BBC.SELECTOR_INVALID_COORDINATES.send(player, args.getString(0)); return; } } else { - pos = player.getBlockIn().toVector(); + pos = player.getBlockIn().toBlockPoint(); } pos = pos.clampY(0, player.getWorld().getMaximumPoint().getBlockY()); if (!session.getRegionSelector(player.getWorld()).selectPrimary(pos, ActorSelectorLimits.forActor(player))) { @@ -135,12 +128,12 @@ public class SelectionCommands { ) @Logging(POSITION) @CommandPermissions("worldedit.selection.pos") - public void pos2(Player player, LocalSession session, CommandContext args) throws WorldEditException { - Vector pos; + public void pos2(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { + BlockVector3 pos; if (args.argsLength() == 1) { if (args.getString(0).matches("-?\\d+,-?\\d+,-?\\d+")) { String[] coords = args.getString(0).split(","); - pos = new Vector(Integer.parseInt(coords[0]), + pos = BlockVector3.at(Integer.parseInt(coords[0]), Integer.parseInt(coords[1]), Integer.parseInt(coords[2])); } else { @@ -148,7 +141,7 @@ public class SelectionCommands { return; } } else { - pos = player.getBlockIn().toVector(); + pos = player.getBlockIn().toBlockPoint(); } pos = pos.clampY(0, player.getWorld().getMaximumPoint().getBlockY()); if (!session.getRegionSelector(player.getWorld()).selectSecondary(pos, ActorSelectorLimits.forActor(player))) { @@ -168,8 +161,8 @@ public class SelectionCommands { max = 0 ) @CommandPermissions("worldedit.selection.hpos") - public void hpos1(Player player, LocalSession session, CommandContext args) throws WorldEditException { - Vector pos = player.getBlockTrace(300).toVector(); + public void hpos1(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { + BlockVector3 pos = player.getBlockTrace(300).toBlockPoint(); if (pos != null) { if (!session.getRegionSelector(player.getWorld()).selectPrimary(pos, ActorSelectorLimits.forActor(player))) { @@ -192,8 +185,8 @@ public class SelectionCommands { max = 0 ) @CommandPermissions("worldedit.selection.hpos") - public void hpos2(Player player, LocalSession session, CommandContext args) throws WorldEditException { - Vector pos = player.getBlockTrace(300).toVector(); + public void hpos2(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { + BlockVector3 pos = player.getBlockTrace(300).toBlockPoint(); if (pos != null) { if (!session.getRegionSelector(player.getWorld()).selectSecondary(pos, ActorSelectorLimits.forActor(player))) { @@ -226,22 +219,22 @@ public class SelectionCommands { ) @Logging(POSITION) @CommandPermissions("worldedit.selection.chunk") - public void chunk(Player player, LocalSession session, CommandContext args) throws WorldEditException { - final Vector min; - final Vector max; + public void chunk(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { + final BlockVector3 min; + final BlockVector3 max; final World world = player.getWorld(); if (args.hasFlag('s')) { Region region = session.getSelection(world); - final Vector2D min2D = ChunkStore.toChunk(region.getMinimumPoint()); - final Vector2D max2D = ChunkStore.toChunk(region.getMaximumPoint()); + final BlockVector2 min2D = ChunkStore.toChunk(region.getMinimumPoint()); + final BlockVector2 max2D = ChunkStore.toChunk(region.getMaximumPoint()); - min = new Vector(min2D.getBlockX() * 16, 0, min2D.getBlockZ() * 16); - max = new Vector(max2D.getBlockX() * 16 + 15, world.getMaxY(), max2D.getBlockZ() * 16 + 15); + min = BlockVector3.at(min2D.getBlockX() * 16, 0, min2D.getBlockZ() * 16); + max = BlockVector3.at(max2D.getBlockX() * 16 + 15, world.getMaxY(), max2D.getBlockZ() * 16 + 15); BBC.SELECTION_CHUNKS.send(player, min2D.getBlockX() + ", " + min2D.getBlockZ(), max2D.getBlockX() + ", " + max2D.getBlockZ()); } else { - final Vector2D min2D; + final BlockVector2 min2D; if (args.argsLength() == 1) { // coords specified String[] coords = args.getString(0).split(","); @@ -250,14 +243,14 @@ public class SelectionCommands { } int x = Integer.parseInt(coords[0]); int z = Integer.parseInt(coords[1]); - Vector2D pos = new Vector2D(x, z); - min2D = (args.hasFlag('c')) ? pos : ChunkStore.toChunk(pos.toVector()); + BlockVector2 pos = BlockVector2.at(x, z); + min2D = (args.hasFlag('c')) ? pos : ChunkStore.toChunk(pos.toBlockVector3()); } else { // use player loc - min2D = ChunkStore.toChunk(player.getBlockIn().toVector()); + min2D = ChunkStore.toChunk(player.getBlockIn().toBlockPoint()); } - min = new Vector(min2D.getBlockX() * 16, 0, min2D.getBlockZ() * 16); + min = BlockVector3.at(min2D.getBlockX() * 16, 0, min2D.getBlockZ() * 16); max = min.add(15, world.getMaxY(), 15); BBC.SELECTION_CHUNK.send(player, min2D.getBlockX() + ", " + min2D.getBlockZ()); @@ -285,8 +278,8 @@ public class SelectionCommands { max = 0 ) @CommandPermissions("worldedit.wand") - public void wand(Player player, LocalSession session, CommandContext args) throws WorldEditException { - player.giveItem(new BaseItemStack(we.getConfiguration().wandItem, 1)); + public void wand(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { + player.giveItem(new BaseItemStack(ItemTypes.parse(we.getConfiguration().wandItem), 1)); BBC.SELECTION_WAND.send(player); if (!FawePlayer.wrap(player).hasPermission("fawe.tips")) BBC.TIP_SEL_LIST.or(BBC.TIP_SELECT_CONNECTED, BBC.TIP_SET_POS1, BBC.TIP_FARWAND, BBC.TIP_DISCORD).send(player); @@ -319,7 +312,7 @@ public class SelectionCommands { ) @Logging(REGION) @CommandPermissions("worldedit.selection.expand") - public void expand(Player player, LocalSession session, CommandContext args) throws WorldEditException { + public void expand(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { // Special syntax (//expand vert) to expand the selection between // sky and bedrock. if (args.getString(0).equalsIgnoreCase("vert") || args.getString(0).equalsIgnoreCase("vertical")) { @@ -327,8 +320,8 @@ public class SelectionCommands { try { int oldSize = region.getArea(); region.expand( - new Vector(0, (player.getWorld().getMaxY() + 1), 0), - new Vector(0, -(player.getWorld().getMaxY() + 1), 0)); + BlockVector3.at(0, (player.getWorld().getMaxY() + 1), 0), + BlockVector3.at(0, -(player.getWorld().getMaxY() + 1), 0)); session.getRegionSelector(player.getWorld()).learnChanges(); int newSize = region.getArea(); session.getRegionSelector(player.getWorld()).explainRegionAdjust(player, session); @@ -339,8 +332,7 @@ public class SelectionCommands { return; } - - List dirs = new ArrayList(); + List dirs = new ArrayList<>(); int change = args.getInteger(0); int reverseChange = 0; @@ -385,11 +377,11 @@ public class SelectionCommands { int oldSize = region.getArea(); if (reverseChange == 0) { - for (Vector dir : dirs) { + for (BlockVector3 dir : dirs) { region.expand(dir.multiply(change)); } } else { - for (Vector dir : dirs) { + for (BlockVector3 dir : dirs) { region.expand(dir.multiply(change), dir.multiply(-reverseChange)); } } @@ -410,8 +402,9 @@ public class SelectionCommands { ) @Logging(REGION) @CommandPermissions("worldedit.selection.contract") - public void contract(Player player, LocalSession session, CommandContext args) throws WorldEditException { - List dirs = new ArrayList(); + public void contract(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { + + List dirs = new ArrayList<>(); int change = args.getInteger(0); int reverseChange = 0; @@ -455,11 +448,11 @@ public class SelectionCommands { Region region = session.getSelection(player.getWorld()); int oldSize = region.getArea(); if (reverseChange == 0) { - for (Vector dir : dirs) { + for (BlockVector3 dir : dirs) { region.contract(dir.multiply(change)); } } else { - for (Vector dir : dirs) { + for (BlockVector3 dir : dirs) { region.contract(dir.multiply(change), dir.multiply(-reverseChange)); } } @@ -483,8 +476,9 @@ public class SelectionCommands { ) @Logging(REGION) @CommandPermissions("worldedit.selection.shift") - public void shift(Player player, LocalSession session, CommandContext args) throws WorldEditException { - List dirs = new ArrayList(); + public void shift(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { + + List dirs = new ArrayList<>(); int change = args.getInteger(0); if (args.argsLength() == 2) { if (args.getString(1).contains(",")) { @@ -501,7 +495,7 @@ public class SelectionCommands { try { Region region = session.getSelection(player.getWorld()); - for (Vector dir : dirs) { + for (BlockVector3 dir : dirs) { region.shift(dir.multiply(change)); } @@ -529,7 +523,7 @@ public class SelectionCommands { ) @Logging(REGION) @CommandPermissions("worldedit.selection.outset") - public void outset(Player player, LocalSession session, CommandContext args) throws WorldEditException { + public void outset(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { Region region = session.getSelection(player.getWorld()); region.expand(getChangesForEachDir(args)); session.getRegionSelector(player.getWorld()).learnChanges(); @@ -552,7 +546,7 @@ public class SelectionCommands { ) @Logging(REGION) @CommandPermissions("worldedit.selection.inset") - public void inset(Player player, LocalSession session, CommandContext args) throws WorldEditException { + public void inset(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { Region region = session.getSelection(player.getWorld()); region.contract(getChangesForEachDir(args)); session.getRegionSelector(player.getWorld()).learnChanges(); @@ -560,23 +554,23 @@ public class SelectionCommands { BBC.SELECTION_INSET.send(player); } - private Vector[] getChangesForEachDir(CommandContext args) { - List changes = new ArrayList(6); + private BlockVector3[] getChangesForEachDir(CommandContext args) { + List changes = new ArrayList<>(6); int change = args.getInteger(0); if (!args.hasFlag('h')) { - changes.add((new Vector(0, 1, 0)).multiply(change)); - changes.add((new Vector(0, -1, 0)).multiply(change)); + changes.add((BlockVector3.at(0, 1, 0)).multiply(change)); + changes.add((BlockVector3.at(0, -1, 0)).multiply(change)); } if (!args.hasFlag('v')) { - changes.add((new Vector(1, 0, 0)).multiply(change)); - changes.add((new Vector(-1, 0, 0)).multiply(change)); - changes.add((new Vector(0, 0, 1)).multiply(change)); - changes.add((new Vector(0, 0, -1)).multiply(change)); + changes.add((BlockVector3.at(1, 0, 0)).multiply(change)); + changes.add((BlockVector3.at(-1, 0, 0)).multiply(change)); + changes.add((BlockVector3.at(0, 0, 1)).multiply(change)); + changes.add((BlockVector3.at(0, 0, -1)).multiply(change)); } - return changes.toArray(new Vector[0]); + return changes.toArray(new BlockVector3[0]); } @Command( @@ -588,7 +582,7 @@ public class SelectionCommands { max = 0 ) @CommandPermissions("worldedit.selection.size") - public void size(Player player, LocalSession session, CommandContext args) throws WorldEditException { + public void size(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { if (args.hasFlag('c')) { ClipboardHolder root = session.getClipboard(); // Clipboard clipboard = holder.getClipboard(); @@ -608,8 +602,8 @@ public class SelectionCommands { } Region region = clipboard.getRegion(); - Vector size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(Vector.ONE); - Vector origin = clipboard.getOrigin(); + BlockVector3 size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(BlockVector3.ONE); + BlockVector3 origin = clipboard.getOrigin(); String sizeStr = size.getBlockX() + "*" + size.getBlockY() + "*" + size.getBlockZ(); String originStr = origin.getBlockX() + "," + origin.getBlockY() + "," + origin.getBlockZ(); @@ -628,11 +622,24 @@ public class SelectionCommands { // player.print(BBC.getPrefix() + "Offset: " + origin); // player.print(BBC.getPrefix() + "Cuboid distance: " + size.distance(Vector.ONE)); // player.print(BBC.getPrefix() + "# of blocks: " + (int) (size.getX() * size.getY() * size.getZ())); +//======= +// public void size(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { +// if (args.hasFlag('c')) { +// ClipboardHolder holder = session.getClipboard(); +// Clipboard clipboard = holder.getClipboard(); +// Region region = clipboard.getRegion(); +// BlockVector3 size = region.getMaximumPoint().subtract(region.getMinimumPoint()); +// BlockVector3 origin = clipboard.getOrigin(); +// +// player.print("Cuboid dimensions (max - min): " + size); +// player.print("Offset: " + origin); +// player.print("Cuboid distance: " + size.distance(BlockVector3.ONE)); +// player.print("# of blocks: " + (int) (size.getX() * size.getY() * size.getZ())); return; } Region region = session.getSelection(player.getWorld()); - Vector size = region.getMaximumPoint() + BlockVector3 size = region.getMaximumPoint() .subtract(region.getMinimumPoint()) .add(1, 1, 1); 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 3373ed9b8..3056036fc 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 @@ -29,7 +29,7 @@ import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.command.tool.BlockDataCyler; 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 bf96065a9..ad3314995 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 @@ -28,33 +28,42 @@ import com.boydti.fawe.config.Settings; import com.boydti.fawe.object.DelegateConsumer; import com.boydti.fawe.object.FaweLimit; import com.boydti.fawe.object.FawePlayer; -import com.boydti.fawe.object.RunnableVal; import com.boydti.fawe.object.RunnableVal3; import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.MathMan; import com.boydti.fawe.util.StringMan; import com.boydti.fawe.util.chat.Message; import com.boydti.fawe.util.chat.UsageMessage; -import com.boydti.fawe.util.gui.FormBuilder; import com.boydti.fawe.util.image.ImageUtil; import com.sk89q.minecraft.util.commands.*; -import com.sk89q.worldedit.*; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; + +import static com.sk89q.minecraft.util.commands.Logging.LogMode.PLACEMENT; + +import com.sk89q.minecraft.util.commands.Command; +import com.sk89q.minecraft.util.commands.CommandContext; +import com.sk89q.minecraft.util.commands.CommandException; +import com.sk89q.minecraft.util.commands.CommandPermissions; +import com.sk89q.minecraft.util.commands.Logging; +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.LocalConfiguration; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.command.util.CreatureButcher; import com.sk89q.worldedit.command.util.EntityRemover; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.platform.CommandEvent; -import com.sk89q.worldedit.extension.factory.DefaultMaskParser; import com.sk89q.worldedit.extension.factory.DefaultTransformParser; -import com.sk89q.worldedit.extension.factory.HashTagPatternParser; +import com.sk89q.worldedit.extension.factory.parser.mask.DefaultMaskParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.ClipboardPatternParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.DefaultPatternParser; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.function.mask.ExistingBlockMask; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.Operations; @@ -64,6 +73,7 @@ import com.sk89q.worldedit.internal.annotation.Direction; import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.ExpressionException; import com.sk89q.worldedit.internal.expression.runtime.EvaluationException; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CylinderRegion; import com.sk89q.worldedit.regions.Region; @@ -73,6 +83,7 @@ import com.sk89q.worldedit.util.command.binding.Text; import com.sk89q.worldedit.util.command.parametric.Optional; import com.sk89q.worldedit.util.command.parametric.ParameterData; import com.sk89q.worldedit.world.World; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockTypes; import javax.imageio.ImageIO; @@ -114,7 +125,7 @@ public class UtilityCommands extends MethodCommands { queued = false ) public void patterns(Player player, LocalSession session, CommandContext args) throws WorldEditException { - displayModifierHelp(player, HashTagPatternParser.class, args); + displayModifierHelp(player, DefaultPatternParser.class, args); } @Command( @@ -185,33 +196,30 @@ public class UtilityCommands extends MethodCommands { File maxImages = new File(webSrc, "images" + File.separator + "max"); final int sub = srcFolder.getAbsolutePath().length(); List images = new ArrayList<>(); - MainUtil.iterateFiles(srcFolder, new Consumer() { - @Override - public void accept(File file) { - switch (file.getName().substring(file.getName().lastIndexOf('.')).toLowerCase()) { - case ".png": - case ".jpeg": - break; - default: - return; - } - try { - String name = file.getAbsolutePath().substring(sub); - 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); - player.sendMessage("Writing " + name); - File minFile = new File(minImages, name); - File maxFile = new File(maxImages, name); - minFile.getParentFile().mkdirs(); - maxFile.getParentFile().mkdirs(); - ImageIO.write(minImg, "png", minFile); - ImageIO.write(maxImg, "png", maxFile); - images.add(name); - } catch (IOException e) { - throw new RuntimeException(e); - } + MainUtil.iterateFiles(srcFolder, file -> { + switch (file.getName().substring(file.getName().lastIndexOf('.')).toLowerCase()) { + case ".png": + case ".jpeg": + break; + default: + return; + } + try { + String name = file.getAbsolutePath().substring(sub); + 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); + player.sendMessage("Writing " + name); + File minFile = new File(minImages, name); + File maxFile = new File(maxImages, name); + minFile.getParentFile().mkdirs(); + maxFile.getParentFile().mkdirs(); + ImageIO.write(minImg, "png", minFile); + ImageIO.write(maxImg, "png", maxFile); + images.add(name); + } catch (IOException e) { + throw new RuntimeException(e); } }); StringBuilder config = new StringBuilder(); @@ -252,9 +260,9 @@ public class UtilityCommands extends MethodCommands { ) @CommandPermissions("worldedit.fill") @Logging(PLACEMENT) - public void fill(Player player, LocalSession session, EditSession editSession, Pattern pattern, double radius, @Optional("1") double depth, @Optional("down") @Direction Vector direction) throws WorldEditException { + public void fill(Player player, LocalSession session, EditSession editSession, Pattern pattern, double radius, @Optional("1") double depth, @Optional("down") @Direction BlockVector3 direction) throws WorldEditException { worldEdit.checkMaxRadius(radius); - Vector pos = session.getPlacementPosition(player); + BlockVector3 pos = session.getPlacementPosition(player); int affected; affected = editSession.fillDirection(pos, pattern, radius, (int) depth, direction); player.print(BBC.getPrefix() + affected + " block(s) have been created."); @@ -271,10 +279,32 @@ public class UtilityCommands extends MethodCommands { @Logging(PLACEMENT) public void fillr(Player player, LocalSession session, EditSession editSession, Pattern pattern, double radius, @Optional("-1") double depth) throws WorldEditException { worldEdit.checkMaxRadius(radius); - Vector pos = session.getPlacementPosition(player); + BlockVector3 pos = session.getPlacementPosition(player); if (depth == -1) depth = Integer.MAX_VALUE; int affected = editSession.fillXZ(pos, pattern, radius, (int) depth, true); player.print(BBC.getPrefix() + affected + " block(s) have been created."); +//======= +// public void fillr(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { +// +// ParserContext context = new ParserContext(); +// context.setActor(player); +// context.setWorld(player.getWorld()); +// context.setSession(session); +// Pattern pattern = we.getPatternFactory().parseFromInput(args.getString(0), context); +// +// double radius = Math.max(1, args.getDouble(1)); +// we.checkMaxRadius(radius); +// int depth = args.argsLength() > 2 ? Math.max(1, args.getInteger(2)) : Integer.MAX_VALUE; +// +// BlockVector3 pos = session.getPlacementPosition(player); +// int affected = 0; +// if (pattern instanceof BlockPattern) { +// affected = editSession.fillXZ(pos, ((BlockPattern) pattern).getBlock(), radius, depth, true); +// } else { +// affected = editSession.fillXZ(pos, pattern, radius, depth, true); +// } +// player.print(affected + " block(s) have been created."); +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner } @Command( @@ -385,9 +415,10 @@ public class UtilityCommands extends MethodCommands { if (from == null) { from = new ExistingBlockMask(editSession); } - Vector base = session.getPlacementPosition(player); - Vector min = base.subtract(size, size, size); - Vector max = base.add(size, size, size); + + BlockVector3 base = session.getPlacementPosition(player); + BlockVector3 min = base.subtract((int)size, (int)size, (int)size); + BlockVector3 max = base.add((int)size, (int)size, (int)size); Region region = new CuboidRegion(player.getWorld(), min, max); int affected = editSession.replaceBlocks(region, from, to); @@ -517,13 +548,13 @@ public class UtilityCommands extends MethodCommands { CreatureButcher flags = new CreatureButcher(actor); flags.fromCommand(args); - List visitors = new ArrayList(); + List visitors = new ArrayList<>(); LocalSession session = null; EditSession editSession = null; if (player != null) { session = worldEdit.getSessionManager().get(player); - Vector center = session.getPlacementPosition(player); + BlockVector3 center = session.getPlacementPosition(player); editSession = session.createEditSession(player); List entities; if (radius >= 0) { @@ -577,13 +608,13 @@ public class UtilityCommands extends MethodCommands { EntityRemover remover = new EntityRemover(); remover.fromString(typeStr); - List visitors = new ArrayList(); + List visitors = new ArrayList<>(); LocalSession session = null; EditSession editSession = null; if (player != null) { session = worldEdit.getSessionManager().get(player); - Vector center = session.getPlacementPosition(player); + BlockVector3 center = session.getPlacementPosition(player); editSession = session.createEditSession(player); List entities; if (radius >= 0) { @@ -627,20 +658,12 @@ public class UtilityCommands extends MethodCommands { final Expression expression = Expression.compile(input); ExecutorService executor = Executors.newSingleThreadExecutor(); - Future futureResult = executor.submit(new Callable() { - @Override - public Double call() throws Exception { - - return expression.evaluate(); - } - }); + Future futureResult = executor.submit((Callable) expression::evaluate); Double result = Double.NaN; try { result = futureResult.get(limit.MAX_EXPRESSION_MS, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { futureResult.cancel(true); @@ -741,26 +764,25 @@ public class UtilityCommands extends MethodCommands { final int sortType = args.hasFlag('d') ? -1 : args.hasFlag('n') ? 1 : 0; // cleanup file list - Collections.sort(fileList, new Comparator() { - @Override - public int compare(File f1, File f2) { - boolean dir1 = f1.isDirectory(); - boolean dir2 = f2.isDirectory(); - if (dir1 != dir2) return dir1 ? -1 : 1; - int res; - if (sortType == 0) { // use name by default - int p = f1.getParent().compareTo(f2.getParent()); - if (p == 0) { // same parent, compare names - res = f1.getName().compareTo(f2.getName()); - } else { // different parent, sort by that - res = p; - } - } else { - res = Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); // use date if there is a flag - if (sortType == 1) res = -res; // flip date for newest first instead of oldest first + fileList.sort((f1, f2) -> { + boolean dir1 = f1.isDirectory(); + boolean dir2 = f2.isDirectory(); + if (dir1 != dir2) + return dir1 ? -1 : 1; + int res; + if (sortType == 0) { // use name by default + int p = f1.getParent().compareTo(f2.getParent()); + if (p == 0) { // same parent, compare names + res = f1.getName().compareTo(f2.getName()); + } else { // different parent, sort by that + res = p; } - return res; + } 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 } + return res; }); int offset = (page - 1) * perPage; @@ -852,7 +874,7 @@ public class UtilityCommands extends MethodCommands { UUID uuid = UUID.fromString(f.getName()); return false; } - } catch (IllegalArgumentException exception) {} + } catch (IllegalArgumentException ignored) {} return true; }; @@ -867,7 +889,7 @@ public class UtilityCommands extends MethodCommands { } if (formatName != null) { - final ClipboardFormat cf = ClipboardFormat.findByAlias(formatName); + final ClipboardFormat cf = ClipboardFormats.findByAlias(formatName); forEachFile = new DelegateConsumer(forEachFile) { @Override public void accept(File file) { @@ -977,7 +999,7 @@ public class UtilityCommands extends MethodCommands { dir = root; } - ClipboardFormat format = ClipboardFormat.findByFile(file); + ClipboardFormat format = ClipboardFormats.findByFile(file); URI relative = dir.toURI().relativize(file.toURI()); StringBuilder name = new StringBuilder(); if (relative.isAbsolute()) { @@ -992,269 +1014,6 @@ public class UtilityCommands extends MethodCommands { help(args, we, actor, "/", null); } - @Command( - aliases = {"/gui"}, - desc = "Open the GUI" - ) - @Logging(PLACEMENT) - public void gui(Actor actor, FawePlayer fp, LocalSession session, CommandContext args) throws WorldEditException, CommandException { - FormBuilder gui = Fawe.imp().getFormBuilder(); - if (gui == null) throw new CommandException("Only supported on Pocket Edition"); - - Dispatcher callable = worldEdit.getPlatformManager().getCommandManager().getDispatcher(); - CommandLocals locals = args.getLocals(); - - String prefix = Commands.getAlias(UtilityCommands.class, "/gui"); - - // TODO sort commands by most used - - new HelpBuilder(callable, args, prefix, Integer.MAX_VALUE) { - @Override - public void displayFailure(String message) { - gui.setTitle("Error"); - gui.addLabel(message); - } - - @Override - public void displayUsage(CommandCallable callable, String commandString) { - gui.setTitle(commandString); - - if (callable instanceof Dispatcher) { - Dispatcher dispathcer = (Dispatcher) callable; - dispathcer.getCommands(); - gui.addLabel("Dispatcher not implemented for " + commandString); - } else { - Description cmdDesc = callable.getDescription(); - - - - List params = cmdDesc.getParameters(); - String[] suggested = new String[params.size()]; - if (cmdDesc.getUsage() != null) { - String[] usageArgs = cmdDesc.getUsage().split(" ", params.size()); - for (int i = 0; i < usageArgs.length; i++) { - String arg = usageArgs[i]; - String[] splitSug = arg.split("="); - if (splitSug.length == 2) { - suggested[i] = splitSug[1]; - } - } - } - for (int i = 0 ; i < params.size(); i++) { - String[] def = params.get(i).getDefaultValue(); - if (def != null && def.length != 0) { - suggested[i] = def[0]; - } - } - - String help = cmdDesc.getHelp(); - if (help == null || help.isEmpty()) help = cmdDesc.getDescription(); - - gui.addLabel(BBC.color("&2" + help + "\n")); - - List flags = new ArrayList<>(); - - for (int i = 0; i < params.size(); i++) { - Parameter param = params.get(i); - String name = param.getName(); - boolean optional = param.isValueFlag() || param.isOptional(); - String[] def = param.getDefaultValue(); - - if (param.getFlag() != null) { - flags.add("-" + param.getFlag() + " "); - } else { - flags.add(""); - } - - if (param instanceof ParameterData) { - ParameterData pd = (ParameterData) param; - Type type = pd.getType(); - String suggestion = suggested[i]; - - String color = optional ? "3" : "c"; - StringBuilder label = new StringBuilder(BBC.color("&" + color + name + ": ")); -// if (suggested[i] != null) label.append(" e.g. " + suggestion); - Range range = MainUtil.getOf(pd.getModifiers(), Range.class); - double min = 0; - double max = 100; - if (range != null) { - min = range.min(); - max = range.max(); - } else { - SuggestedRange suggestedRange = MainUtil.getOf(pd.getModifiers(), SuggestedRange.class); - if (suggestedRange != null) { - min = suggestedRange.min(); - max = suggestedRange.max(); - } else if (name.equalsIgnoreCase("radius") || name.equalsIgnoreCase("size")) { - max = WorldEdit.getInstance().getConfiguration().maxBrushRadius; - } - } - int step = 1; - Step stepSizeAnn = MainUtil.getOf(pd.getModifiers(), Step.class); - if (stepSizeAnn != null) { - double stepVal = stepSizeAnn.value(); - step = Math.max(1, (int) stepVal); - } - /* - BaseBiome - Vector - Vector2D - */ - - switch (type.getTypeName()) { - case "double": - case "java.lang.Double": { - double value = suggestion != null ? Double.parseDouble(suggestion) : min; - gui.addSlider("\n" + label.toString(), min, max, 1, value); - break; - } - case "int": - case "java.lang.Integer": { - int value = suggestion != null ? Integer.parseInt(suggestion) : (int) min; - gui.addSlider("\n" + label.toString(), min, max, 1, value); - break; - } - case "boolean": - case "java.lang.Boolean": { - boolean value = suggestion != null ? Boolean.parseBoolean(suggestion) : false; - gui.addToggle(label.toString(), value); - break; - } - case "com.sk89q.worldedit.patterns.Pattern": { - gui.addInput("\n" + label.toString(), "stone", "wood"); - break; - } - case "com.sk89q.worldedit.blocks.BaseBlock": { - gui.addInput("\n" + label.toString(), "stone", "wood"); - break; - } - case "com.sk89q.worldedit.function.mask.Mask": { - gui.addInput("\n" + label.toString(), "stone", "wood"); - break; - } - default: - case "java.lang.String": { - // TODO - // clipboard - // schematic - // image - if (suggestion == null) suggestion = ""; - gui.addInput("\n" + label.toString(), suggestion, suggestion); - break; - } - } - } else { - throw new UnsupportedOperationException("Unsupported callable: " + callable.getClass() + " | " + param.getClass()); - } - } - - gui.setResponder(new Consumer>() { - @Override - public void accept(Map response) { - int index = 0; - StringBuilder command = new StringBuilder(commandString); - for (Map.Entry arg : response.entrySet()) { - String argValue = arg.getValue().toString(); - String flag = flags.get(index); - if (!flag.isEmpty()) { - if (argValue.equalsIgnoreCase("false")) continue; - if (argValue.equalsIgnoreCase("true")) argValue = ""; - } - command.append(" " + flag + argValue); - index++; - } - CommandEvent event = new CommandEvent(actor, command.toString()); - CommandManager.getInstance().handleCommand(event); - } - }); - } - } - - @Override - public void displayCategories(Map> categories) { - gui.setTitle(BBC.HELP_HEADER_CATEGORIES.s()); - List categoryList = new ArrayList<>(); - for (Map.Entry> categoryEntry : categories.entrySet()) { - String category = categoryEntry.getKey(); - categoryList.add(category); - Map commandMap = categoryEntry.getValue(); - int size = commandMap.size(); - - String plural = size == 1 ? "command" : "commands"; - gui.addButton(BBC.HELP_ITEM_ALLOWED.f(category, "(" + size + " " + plural + ")"), null); - } - - gui.setResponder(new Consumer>() { - @Override - public void accept(Map response) { - if (response.isEmpty()) { - // ?? - throw new IllegalArgumentException("No response for categories"); - } else { - Map.Entry clicked = response.entrySet().iterator().next(); - String category = categoryList.get(clicked.getKey()); - String arguments = prefix + " " + category; - CommandEvent event = new CommandEvent(actor, arguments); - CommandManager.getInstance().handleCommand(event); - } - } - }); - } - - @Override - public void displayCommands(Map commandMap, String visited, int page, int pageTotal, int effectiveLength) { - gui.setTitle(BBC.HELP_HEADER_SUBCOMMANDS.s()); - - String baseCommand = prefix; - if (effectiveLength > 0) baseCommand += " " + args.getString(0, effectiveLength - 1); - - CommandLocals locals = args.getLocals(); - if (!visited.isEmpty()) { - visited = visited + " "; - } - - List commands = new ArrayList<>(); - - for (Map.Entry cmdEntry : commandMap.entrySet()) { - CommandMapping mapping = cmdEntry.getKey(); - String subPrefix = cmdEntry.getValue(); - - StringBuilder helpCmd = new StringBuilder(); - helpCmd.append(prefix); - helpCmd.append(" "); - helpCmd.append(subPrefix); - CommandCallable c = mapping.getCallable(); - helpCmd.append(visited); - helpCmd.append(mapping.getPrimaryAlias()); - String s2 = mapping.getDescription().getDescription(); - if (c.testPermission(locals)) { -// gui.addLabel(s2); - gui.addButton(helpCmd.toString(), null); - commands.add(helpCmd.toString()); - } - } - - gui.setResponder(new Consumer>() { - @Override - public void accept(Map response) { - if (response.isEmpty()) { - // ?? - throw new IllegalArgumentException("No response for command list: " + prefix); - } else { - Map.Entry clicked = response.entrySet().iterator().next(); - int index = clicked.getKey(); - String cmd = commands.get(index); - CommandEvent event = new CommandEvent(actor, cmd); - CommandManager.getInstance().handleCommand(event); - } - } - }); - } - }.run(); - - gui.display(fp); - } - public static void help(CommandContext args, WorldEdit we, Actor actor, String prefix, CommandCallable callable) { final int perPage = actor instanceof Player ? 12 : 20; // More pages for console 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 d1d532a4f..301640c03 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 @@ -25,6 +25,7 @@ import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.Settings; import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.util.*; +import com.google.common.io.Files; import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandPermissions; @@ -37,6 +38,18 @@ import com.sk89q.worldedit.extension.platform.*; import java.io.IOException; import java.net.URL; +import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.extension.platform.Capability; +import com.sk89q.worldedit.extension.platform.Platform; +import com.sk89q.worldedit.extension.platform.PlatformManager; +import com.sk89q.worldedit.util.paste.ActorCallbackPaste; +import com.sk89q.worldedit.util.report.ConfigReport; +import com.sk89q.worldedit.util.report.ReportList; +import com.sk89q.worldedit.util.report.SystemInfoReport; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; @@ -210,6 +223,28 @@ public class WorldEditCommands { } } +// @Command(aliases = {"report"}, desc = "Writes a report on WorldEdit", flags = "p", max = 0) +// @CommandPermissions({"worldedit.report"}) +// public void report(Actor actor, CommandContext args) throws WorldEditException { +// ReportList report = new ReportList("Report"); +// report.add(new SystemInfoReport()); +// report.add(new ConfigReport()); +// String result = report.toString(); +// +// try { +// File dest = new File(we.getWorkingDirectoryFile(we.getConfiguration().saveDir), "report.txt"); +// Files.write(result, dest, Charset.forName("UTF-8")); +// actor.print("WorldEdit report written to " + dest.getAbsolutePath()); +// } catch (IOException e) { +// actor.printError("Failed to write report: " + e.getMessage()); +// } +// +// if (args.hasFlag('p')) { +// actor.checkPermission("worldedit.report.pastebin"); +// ActorCallbackPaste.pastebin(we.getSupervisor(), actor, result, "WorldEdit report: %s.report"); +// } +// } + @Command( aliases = {"cui"}, usage = "", diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/ItemUseParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/ItemUseParser.java index 2ce222c5b..f6da447a1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/ItemUseParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/ItemUseParser.java @@ -22,12 +22,12 @@ package com.sk89q.worldedit.command.argument; import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandLocals; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.function.Contextual; import com.sk89q.worldedit.function.EditContext; import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.command.argument.CommandArgs; import com.sk89q.worldedit.util.command.composition.SimpleCommand; @@ -35,7 +35,7 @@ import com.sk89q.worldedit.world.World; public class ItemUseParser extends SimpleCommand> { - private final ItemParser itemParser = addParameter(new ItemParser("item", "minecraft:dye:15")); + private final ItemParser itemParser = addParameter(new ItemParser("item", "minecraft:bone_meal")); @Override public Contextual call(CommandArgs args, CommandLocals locals) throws CommandException { @@ -82,7 +82,7 @@ public class ItemUseParser extends SimpleCommand> { } @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { return world.useItem(position, item, Direction.UP); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/NumberParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/NumberParser.java index 9c7f2fed2..349089e50 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/NumberParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/NumberParser.java @@ -62,7 +62,7 @@ public class NumberParser implements CommandExecutor { @Override public List getSuggestions(CommandArgs args, CommandLocals locals) throws MissingArgumentException { String value = args.next(); - return value.isEmpty() && defaultSuggestion != null ? Lists.newArrayList(defaultSuggestion) : Collections.emptyList(); + return value.isEmpty() && defaultSuggestion != null ? Lists.newArrayList(defaultSuggestion) : Collections.emptyList(); } @Override diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/StringParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/StringParser.java index 518024cd3..298f999e4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/StringParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/StringParser.java @@ -57,7 +57,7 @@ public class StringParser implements CommandExecutor { @Override public List getSuggestions(CommandArgs args, CommandLocals locals) throws MissingArgumentException { String value = args.next(); - return value.isEmpty() && defaultSuggestion != null ? Lists.newArrayList(defaultSuggestion) : Collections.emptyList(); + return value.isEmpty() && defaultSuggestion != null ? Lists.newArrayList(defaultSuggestion) : Collections.emptyList(); } @Override diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/DeformCommand.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/DeformCommand.java index 3bcb8a063..cae499dce 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/DeformCommand.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/DeformCommand.java @@ -60,7 +60,7 @@ public class DeformCommand extends SimpleCommand Player player = (Player) locals.get(Actor.class); LocalSession session = WorldEdit.getInstance().getSessionManager().get(locals.get(Actor.class)); try { - deform.setOffset(session.getPlacementPosition(player)); + deform.setOffset(session.getPlacementPosition(player).toVector3()); } catch (IncompleteRegionException e) { throw new WrappedCommandException(e); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java index 5d9c4b95e..645d1f232 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/composition/SelectionCommand.java @@ -36,7 +36,7 @@ import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; 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 a93a6f62c..58abbcd0d 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 @@ -30,7 +30,7 @@ public class AreaPickaxe implements BlockTool { int ox = clicked.getBlockX(); int oy = clicked.getBlockY(); int oz = clicked.getBlockZ(); - BlockType initialType = clicked.getExtent().getBlock(clicked.toVector()).getBlockType(); + BlockType initialType = clicked.getExtent().getBlock(clicked.toBlockPoint()).getBlockType(); if (initialType.getMaterial().isAir()) { return true; @@ -48,6 +48,22 @@ public class AreaPickaxe implements BlockTool { for (int y = oy + range; y >= oy - range; --y) { if (initialType.equals(editSession.getLazyBlock(x, y, z))) { continue; +// try (EditSession editSession = session.createEditSession(player)) { +// editSession.getSurvivalExtent().setToolUse(config.superPickaxeManyDrop); +// +// try { +// for (int x = ox - range; x <= ox + range; ++x) { +// for (int y = oy - range; y <= oy + range; ++y) { +// for (int z = oz - range; z <= oz + range; ++z) { +// BlockVector3 pos = new BlockVector3(x, y, z); +// if (editSession.getBlock(pos).getBlockType() != initialType) { +// continue; +// } +// +// ((World) clicked.getExtent()).queueBlockBreakEffect(server, pos, initialType, clicked.toBlockPoint().distanceSq(pos)); +// +// editSession.setBlock(pos, BlockTypes.AIR.getDefaultState()); +// } } editSession.setBlock(x, y, z, BlockTypes.AIR.getDefaultState()); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockDataCyler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockDataCyler.java index f7437ea76..004dc5bb2 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockDataCyler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockDataCyler.java @@ -19,6 +19,12 @@ package com.sk89q.worldedit.command.tool; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import com.google.common.collect.Lists; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalSession; @@ -26,9 +32,11 @@ import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Platform; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockState; /** * A mode that cycles the data values of supported blocks. @@ -39,13 +47,17 @@ public class BlockDataCyler implements DoubleActionBlockTool { public boolean canUse(Actor player) { return player.hasPermission("worldedit.tool.data-cycler"); } + + private Map> selectedProperties = new HashMap<>(); private boolean handleCycle(Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked, boolean forward) { World world = (World) clicked.getExtent(); - BlockStateHolder block = world.getBlock(clicked.toVector()); +// BlockStateHolder block = world.getBlock(clicked); + BlockVector3 blockPoint = clicked.toBlockPoint(); + BlockState block = world.getBlock(blockPoint); if (!config.allowedDataCycleBlocks.isEmpty() && !player.hasPermission("worldedit.override.data-cycler") @@ -54,26 +66,45 @@ public class BlockDataCyler implements DoubleActionBlockTool { return true; } - if (block.getBlockType().getProperties().isEmpty()) { - player.printError("That block's data cannot be cycled!"); + if (block.getStates().keySet().isEmpty()) { + player.printError("That block's data cannot be cycled!"); } else { - BlockStateHolder newBlock = block; - - // TODO Forward = cycle value, Backward = Next property - // int increment = forward ? 1 : -1; - // BaseBlock newBlock = new BaseBlock(type, BlockData.cycle(type, data, increment)); - EditSession editSession = session.createEditSession(player); - - try { - editSession.setBlock(clicked.toVector(), newBlock); - } catch (MaxChangedBlocksException e) { - player.printError("Max blocks change limit reached."); - } finally { - session.remember(editSession); - } + Property currentProperty = selectedProperties.get(player.getUniqueId()); + + if (currentProperty == null || (forward && block.getState(currentProperty) == null)) { + currentProperty = block.getStates().keySet().stream().findFirst().get(); + selectedProperties.put(player.getUniqueId(), currentProperty); + } + + if (forward) { + block.getState(currentProperty); + int index = currentProperty.getValues().indexOf(block.getState(currentProperty)); + index = (index + 1) % currentProperty.getValues().size(); + @SuppressWarnings("unchecked") + Property objProp = (Property) currentProperty; + BlockState newBlock = block.with(objProp, currentProperty.getValues().get(index)); + + try { + EditSession editSession = session.createEditSession(player); + try { + editSession.setBlock(blockPoint, newBlock); + player.print("Value of " + currentProperty.getName() + " is now " + currentProperty.getValues().get(index).toString()); + } catch (MaxChangedBlocksException e) { + player.printError("Max blocks change limit reached."); + } finally { + session.remember(editSession); + } + }catch (Exception e) {} + } else { + List> properties = Lists.newArrayList(block.getStates().keySet()); + int index = properties.indexOf(currentProperty); + index = (index + 1) % properties.size(); + currentProperty = properties.get(index); + selectedProperties.put(player.getUniqueId(), currentProperty); + player.print("Now cycling " + currentProperty.getName()); + } } - - return true; + return true; } @Override diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockReplacer.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockReplacer.java index e7f71a915..0a7b63e6c 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockReplacer.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/BlockReplacer.java @@ -19,24 +19,16 @@ package com.sk89q.worldedit.command.tool; -import com.boydti.fawe.object.extent.PatternTransform; -import com.sk89q.worldedit.*; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extent.inventory.BlockBag; -import com.sk89q.worldedit.function.pattern.BlockPattern; -import com.sk89q.worldedit.function.pattern.Pattern; -import com.sk89q.worldedit.world.block.BlockStateHolder; /** * A mode that replaces one block. @@ -61,7 +53,7 @@ public class BlockReplacer implements DoubleActionBlockTool { EditSession editSession = session.createEditSession(player); try { - editSession.setBlock(clicked.toVector(), pattern); + editSession.setBlock(clicked.toBlockPoint(), pattern); } finally { if (bag != null) { bag.flushChanges(); @@ -76,7 +68,7 @@ public class BlockReplacer implements DoubleActionBlockTool { @Override public boolean actSecondary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) { EditSession editSession = session.createEditSession(player); - BlockStateHolder targetBlock = (editSession).getBlock(clicked.toVector()); + BlockStateHolder targetBlock = (editSession).getBlock(clicked.toBlockPoint()); BlockType type = targetBlock.getBlockType(); if (type != null) { 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 ab88340e2..221d71eb5 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 @@ -1,7 +1,6 @@ package com.sk89q.worldedit.command.tool; import com.boydti.fawe.Fawe; -import com.boydti.fawe.FaweCache; import com.boydti.fawe.config.BBC; import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.RunnableVal; @@ -22,9 +21,10 @@ import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.internal.expression.Expression; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.entity.Player; @@ -38,7 +38,6 @@ import com.sk89q.worldedit.function.mask.SolidBlockMask; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import java.io.IOException; @@ -51,7 +50,6 @@ import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; -import static com.boydti.fawe.object.brush.TargetMode.TARGET_FACE_RANGE; import static com.google.common.base.Preconditions.checkNotNull; public class BrushTool implements DoubleActionTraceTool, ScrollTool, MovableTool, ResettableTool, Serializable { @@ -379,19 +377,19 @@ public class BrushTool implements DoubleActionTraceTool, ScrollTool, MovableTool this.range = range; } - public Vector getPosition(EditSession editSession, Player player) { + public BlockVector3 getPosition(EditSession editSession, Player player) { Location loc = player.getLocation(); switch (targetMode) { case TARGET_BLOCK_RANGE: - return offset(new MutableBlockVector(trace(editSession, player, getRange(), true)), loc.toVector()); + return offset(trace(editSession, player, getRange(), true), loc).toBlockPoint(); case FOWARD_POINT_PITCH: { int d = 0; float pitch = loc.getPitch(); pitch = 23 - (pitch / 4); d += (int) (Math.sin(Math.toRadians(pitch)) * 50); - final Vector vector = loc.getDirection().setY(0).normalize().multiply(d); - vector.add(loc.getX(), loc.getY(), loc.getZ()).toBlockVector(); - return offset(new MutableBlockVector(vector), loc.toVector()); + final Vector3 vector = loc.getDirection().withY(0).normalize().multiply(d).add(loc.getX(), loc.getY(), loc.getZ()); +// vector = vector.add(loc.getX(), loc.getY(), loc.getZ()); + return offset(vector, loc).toBlockPoint(); } case TARGET_POINT_HEIGHT: { final int height = loc.getBlockY(); @@ -405,29 +403,29 @@ public class BrushTool implements DoubleActionTraceTool, ScrollTool, MovableTool } } final int distance = (height - y) + 8; - return offset(new MutableBlockVector(trace(editSession, player, distance, true)), loc.toVector()); + return offset(trace(editSession, player, distance, true), loc).toBlockPoint(); } case TARGET_FACE_RANGE: - return offset(new MutableBlockVector(trace(editSession, player, getRange(), true)), loc.toVector()); + return offset(trace(editSession, player, getRange(), true), loc).toBlockPoint(); default: return null; } } - private Vector offset(Vector target, Vector playerPos) { + private Vector3 offset(Vector3 target, Vector3 playerPos) { if (targetOffset == 0) return target; return target.subtract(target.subtract(playerPos).normalize().multiply(targetOffset)); } - private Vector trace(EditSession editSession, Player player, int range, boolean useLastBlock) { + private Vector3 trace(EditSession editSession, Player player, int range, boolean useLastBlock) { Mask mask = targetMask == null ? new SolidBlockMask(editSession) : targetMask; new MaskTraverser(mask).reset(editSession); MaskedTargetBlock tb = new MaskedTargetBlock(mask, player, range, 0.2); - return TaskManager.IMP.sync(new RunnableVal() { + return TaskManager.IMP.sync(new RunnableVal() { @Override - public void run(Vector value) { + public void run(Vector3 value) { Location result = tb.getMaskedTargetBlock(useLastBlock); - this.value = result.toVector(); + this.value = result; } }); } @@ -453,7 +451,7 @@ public class BrushTool implements DoubleActionTraceTool, ScrollTool, MovableTool return false; } - Vector target = getPosition(editSession, player); + BlockVector3 target = getPosition(editSession, player); if (target == null) { editSession.cancel(); @@ -474,6 +472,14 @@ public class BrushTool implements DoubleActionTraceTool, ScrollTool, MovableTool MaskIntersection newMask = new MaskIntersection(existingMask); newMask.add(mask); editSession.setMask(newMask); +//======= +// try { +// brush.build(editSession, target.toBlockPoint(), material, size); +// } catch (MaxChangedBlocksException e) { +// player.printError("Max blocks change limit reached."); +// } finally { +// session.remember(editSession); +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner } } Mask sourceMask = current.getSourceMask(); @@ -613,7 +619,7 @@ public class BrushTool implements DoubleActionTraceTool, ScrollTool, MovableTool .combineStages(false) .build(); VisualExtent newVisualExtent = new VisualExtent(editSession.getExtent(), editSession.getQueue()); - Vector position = getPosition(editSession, player); + BlockVector3 position = getPosition(editSession, player); if (position != null) { editSession.setExtent(newVisualExtent); switch (mode) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/DistanceWand.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/DistanceWand.java index 7488c14ad..b78f81f15 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/DistanceWand.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/DistanceWand.java @@ -25,6 +25,7 @@ import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.permission.ActorSelectorLimits; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.util.Location; @@ -49,8 +50,9 @@ public class DistanceWand extends BrushTool implements DoubleActionTraceTool { if (target == null) return true; RegionSelector selector = session.getRegionSelector(player.getWorld()); - if (selector.selectPrimary(target.toVector(), ActorSelectorLimits.forActor(player))) { - selector.explainPrimarySelection(player, session, target.toVector()); + BlockVector3 blockPoint = target.toBlockPoint(); + if (selector.selectPrimary(blockPoint, ActorSelectorLimits.forActor(player))) { + selector.explainPrimarySelection(player, session, blockPoint); } return true; @@ -66,8 +68,9 @@ public class DistanceWand extends BrushTool implements DoubleActionTraceTool { if (target == null) return true; RegionSelector selector = session.getRegionSelector(player.getWorld()); - if (selector.selectSecondary(target.toVector(), ActorSelectorLimits.forActor(player))) { - selector.explainSecondarySelection(player, session, target.toVector()); + BlockVector3 blockPoint = target.toBlockPoint(); + if (selector.selectSecondary(blockPoint, ActorSelectorLimits.forActor(player))) { + selector.explainSecondarySelection(player, session, blockPoint); } return true; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/FloatingTreeRemover.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/FloatingTreeRemover.java index 43a840cf6..aa3d91b7f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/FloatingTreeRemover.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/FloatingTreeRemover.java @@ -23,10 +23,10 @@ import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Platform; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; @@ -66,31 +66,29 @@ public class FloatingTreeRemover implements BlockTool { @Override public boolean actPrimary(Platform server, LocalConfiguration config, - Player player, LocalSession session, Location clicked) { + Player player, LocalSession session, Location clicked) { final World world = (World) clicked.getExtent(); - final BlockState state = world.getBlock(clicked.toVector()); + final BlockState state = world.getBlock(clicked.toBlockPoint()); if (!isTreeBlock(state.getBlockType())) { player.printError("That's not a tree."); return true; } - final EditSession editSession = session.createEditSession(player); - - try { - final Set blockSet = bfs(world, clicked.toVector()); - if (blockSet == null) { - player.printError("That's not a floating tree."); - return true; - } - - for (Vector blockVector : blockSet) { - final BlockState otherState = editSession.getBlock(blockVector); - if (isTreeBlock(otherState.getBlockType())) { - editSession.setBlock(blockVector, BlockTypes.AIR.getDefaultState()); + try /*(EditSession editSession = session.createEditSession(player))*/ { + final Set blockSet = bfs(world, clicked.toBlockPoint()); + if (blockSet == null) { + player.printError("That's not a floating tree."); + return true; + } + + for (BlockVector3 blockVector : blockSet) { + final BlockState otherState = editSession.getBlock(blockVector); + if (isTreeBlock(otherState.getBlockType())) { + editSession.setBlock(blockVector, BlockTypes.AIR.getDefaultState()); + } } - } } catch (MaxChangedBlocksException e) { player.printError("Max blocks change limit reached."); } finally { @@ -100,13 +98,13 @@ public class FloatingTreeRemover implements BlockTool { return true; } - private Vector[] recurseDirections = { - Direction.NORTH.toVector(), - Direction.EAST.toVector(), - Direction.SOUTH.toVector(), - Direction.WEST.toVector(), - Direction.UP.toVector(), - Direction.DOWN.toVector(), + private BlockVector3[] recurseDirections = { + Direction.NORTH.toBlockVector(), + Direction.EAST.toBlockVector(), + Direction.SOUTH.toBlockVector(), + Direction.WEST.toBlockVector(), + Direction.UP.toBlockVector(), + Direction.DOWN.toBlockVector(), }; /** @@ -116,17 +114,17 @@ public class FloatingTreeRemover implements BlockTool { * @param origin any point contained in the floating tree * @return a set containing all blocks in the tree/shroom or null if this is not a floating tree/shroom. */ - private Set bfs(World world, Vector origin) throws MaxChangedBlocksException { - final Set visited = new HashSet<>(); - final LinkedList queue = new LinkedList<>(); + private Set bfs(World world, BlockVector3 origin) throws MaxChangedBlocksException { + final Set visited = new HashSet<>(); + final LinkedList queue = new LinkedList<>(); queue.addLast(origin); visited.add(origin); while (!queue.isEmpty()) { - final Vector current = queue.removeFirst(); - for (Vector recurseDirection : recurseDirections) { - final Vector next = current.add(recurseDirection); + final BlockVector3 current = queue.removeFirst(); + for (BlockVector3 recurseDirection : recurseDirections) { + final BlockVector3 next = current.add(recurseDirection); if (origin.distanceSq(next) > rangeSq) { // Maximum range exceeded => stop walking continue; @@ -134,13 +132,8 @@ public class FloatingTreeRemover implements BlockTool { if (visited.add(next)) { BlockState state = world.getBlock(next); - BlockTypes type = state.getBlockType(); - switch (type) { - case AIR: - case CAVE_AIR: - case VOID_AIR: - case SNOW: - continue; + if (state.getBlockType().getMaterial().isAir() || state.getBlockType() == BlockTypes.SNOW) { + continue; } if (isTreeBlock(state.getBlockType())) { queue.addLast(next); @@ -158,4 +151,4 @@ public class FloatingTreeRemover implements BlockTool { return visited; } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/FloodFillTool.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/FloodFillTool.java index 37644f77f..ee08812ad 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/FloodFillTool.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/FloodFillTool.java @@ -19,11 +19,15 @@ package com.sk89q.worldedit.command.tool; -import com.sk89q.worldedit.*; +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.LocalConfiguration; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.block.BlockType; @@ -54,7 +58,8 @@ public class FloodFillTool implements BlockTool { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked) { World world = (World) clicked.getExtent(); - BlockType initialType = world.getBlockType(clicked.toVector()); + BlockVector3 origin = clicked.toBlockPoint(); + BlockType initialType = world.getBlock(origin).getBlockType(); if (initialType.getMaterial().isAir()) { return true; @@ -65,20 +70,21 @@ public class FloodFillTool implements BlockTool { } EditSession editSession = session.createEditSession(player); - try { - recurse(editSession, clicked.toVector().toBlockVector(), - clicked.toVector(), range, initialType, new HashSet()); - } catch (WorldEditException e) { - throw new RuntimeException(e); + recurse(editSession, origin, origin, range, initialType, new HashSet<>()); + } catch (MaxChangedBlocksException e) { + player.printError("Max blocks change limit reached."); + } finally { + session.remember(editSession); } + editSession.flushQueue(); session.remember(editSession); return true; } - private void recurse(EditSession editSession, BlockVector pos, Vector origin, int size, BlockType initialType, - Set visited) throws WorldEditException { + private void recurse(EditSession editSession, BlockVector3 pos, BlockVector3 origin, int size, BlockType initialType, + Set visited) throws MaxChangedBlocksException { if (origin.distance(pos) > size || visited.contains(pos)) { return; @@ -92,17 +98,17 @@ public class FloodFillTool implements BlockTool { return; } - recurse(editSession, pos.add(1, 0, 0).toBlockVector(), + recurse(editSession, pos.add(1, 0, 0), origin, size, initialType, visited); - recurse(editSession, pos.add(-1, 0, 0).toBlockVector(), + recurse(editSession, pos.add(-1, 0, 0), origin, size, initialType, visited); - recurse(editSession, pos.add(0, 0, 1).toBlockVector(), + recurse(editSession, pos.add(0, 0, 1), origin, size, initialType, visited); - recurse(editSession, pos.add(0, 0, -1).toBlockVector(), + recurse(editSession, pos.add(0, 0, -1), origin, size, initialType, visited); - recurse(editSession, pos.add(0, 1, 0).toBlockVector(), + recurse(editSession, pos.add(0, 1, 0), origin, size, initialType, visited); - recurse(editSession, pos.add(0, -1, 0).toBlockVector(), + recurse(editSession, pos.add(0, -1, 0), origin, size, initialType, visited); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/LongRangeBuildTool.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/LongRangeBuildTool.java index 789055d72..4137e1efd 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/LongRangeBuildTool.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/LongRangeBuildTool.java @@ -28,9 +28,9 @@ import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BaseBlock; /** * A tool that can place (or remove) blocks at a distance. @@ -56,14 +56,20 @@ public class LongRangeBuildTool extends BrushTool implements DoubleActionTraceTo Location pos = getTargetFace(player); if (pos == null) return false; EditSession eS = session.createEditSession(player); - - BlockStateHolder applied = secondary.apply(pos.toVector()); - if (applied.getBlockType().getMaterial().isAir()) { - eS.setBlock(pos.toVector(), secondary); - } else { - eS.setBlock(pos.add(pos.getDirection()), secondary); + try { +// eS.disableBuffering(); + BlockVector3 blockPoint = pos.toBlockPoint(); + BaseBlock applied = secondary.apply(blockPoint); + if (applied.getBlockType().getMaterial().isAir()) { + eS.setBlock(blockPoint, secondary); + } else { + eS.setBlock(pos.subtract(pos.getDirection()).toBlockPoint(), secondary); + } + return true; + } catch (MaxChangedBlocksException e) { + // one block? eat it } - return true; + return false; } @Override @@ -71,11 +77,19 @@ public class LongRangeBuildTool extends BrushTool implements DoubleActionTraceTo Location pos = getTargetFace(player); if (pos == null) return false; EditSession eS = session.createEditSession(player); - BlockStateHolder applied = primary.apply(pos.toVector()); - if (applied.getBlockType().getMaterial().isAir()) { - eS.setBlock(pos.toVector(), primary); - } else { - eS.setBlock(pos.add(pos.getDirection()), primary); + + try { +// eS.disableBuffering(); + BlockVector3 blockPoint = pos.toBlockPoint(); + BaseBlock applied = primary.apply(blockPoint); + if (applied.getBlockType().getMaterial().isAir()) { + eS.setBlock(blockPoint, primary); + } else { + eS.setBlock(pos.subtract(pos.getDirection()).toBlockPoint(), primary); + } + return true; + } catch (MaxChangedBlocksException e) { + // one block? eat it } return true; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/QueryTool.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/QueryTool.java index 1ad0441a4..29d655d08 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/QueryTool.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/QueryTool.java @@ -26,8 +26,9 @@ import com.sk89q.worldedit.blocks.MobSpawnerBlock; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Platform; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.World; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BaseBlock; /** * Looks up information about a block. @@ -44,13 +45,14 @@ public class QueryTool implements BlockTool { World world = (World) clicked.getExtent(); EditSession editSession = session.createEditSession(player); - BlockStateHolder block = editSession.getFullBlock(clicked.toVector()); + BlockVector3 blockPoint = clicked.toBlockPoint(); + BaseBlock block = editSession.getFullBlock(blockPoint); - player.print("\u00A79@" + clicked.toVector() + ": " + "\u00A7e" + player.print("\u00A79@" + clicked + ": " + "\u00A7e" + block.getBlockType().getName() + "\u00A77" + " (" + block.toString() + ") " + "\u00A7f" - + " (" + world.getBlockLightLevel(clicked.toVector()) + "/" + world.getBlockLightLevel(clicked.toVector().add(0, 1, 0)) + ")"); + + " (" + world.getBlockLightLevel(blockPoint) + "/" + world.getBlockLightLevel(blockPoint.add(0, 1, 0)) + ")"); if (block instanceof MobSpawnerBlock) { player.printRaw("\u00A7e" + "Mob Type: " diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/RecursivePickaxe.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/RecursivePickaxe.java index edfefdd06..f794882d7 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/RecursivePickaxe.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/RecursivePickaxe.java @@ -4,7 +4,6 @@ import com.boydti.fawe.object.mask.IdMask; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Platform; @@ -12,8 +11,10 @@ import com.sk89q.worldedit.function.block.BlockReplace; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.visitor.RecursiveVisitor; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; /** @@ -35,9 +36,11 @@ public class RecursivePickaxe implements BlockTool { @Override public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) { World world = (World) clicked.getExtent(); - final Vector pos = clicked.toVector(); + final BlockVector3 pos = clicked.toBlockPoint(); EditSession editSession = session.createEditSession(player); + BlockVector3 origin = clicked.toBlockPoint(); + BlockType initialType = world.getBlock(origin).getBlockType(); BlockStateHolder block = editSession.getBlock(pos); if (block.getBlockType().getMaterial().isAir()) { @@ -50,6 +53,7 @@ public class RecursivePickaxe implements BlockTool { editSession.getSurvivalExtent().setToolUse(config.superPickaxeManyDrop); +//<<<<<<< HEAD final int radius = (int) range; final BlockReplace replace = new BlockReplace(editSession, (editSession.nullBlock)); editSession.setMask((Mask) null); @@ -59,9 +63,51 @@ public class RecursivePickaxe implements BlockTool { editSession.flushQueue(); session.remember(editSession); +//======= +// try { +// recurse(server, editSession, world, clicked.toBlockPoint(), +// clicked.toBlockPoint(), range, initialType, new HashSet<>()); +// } catch (MaxChangedBlocksException e) { +// player.printError("Max blocks change limit reached."); +// } finally { +// session.remember(editSession); +// } +// } +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner return true; } +// private static void recurse(Platform server, EditSession editSession, World world, BlockVector3 pos, +// BlockVector3 origin, double size, BlockType initialType, Set visited) throws MaxChangedBlocksException { +// +// final double distanceSq = origin.distanceSq(pos); +// if (distanceSq > size*size || visited.contains(pos)) { +// return; +// } +// +// visited.add(pos); +// +// if (editSession.getBlock(pos).getBlockType() != initialType) { +// return; +// } +// +// world.queueBlockBreakEffect(server, pos, initialType, distanceSq); +// +// editSession.setBlock(pos, BlockTypes.AIR.getDefaultState()); +// +// recurse(server, editSession, world, pos.add(1, 0, 0), +// origin, size, initialType, visited); +// recurse(server, editSession, world, pos.add(-1, 0, 0), +// origin, size, initialType, visited); +// recurse(server, editSession, world, pos.add(0, 0, 1), +// origin, size, initialType, visited); +// recurse(server, editSession, world, pos.add(0, 0, -1), +// origin, size, initialType, visited); +// recurse(server, editSession, world, pos.add(0, 1, 0), +// origin, size, initialType, visited); +// recurse(server, editSession, world, pos.add(0, -1, 0), +// origin, size, initialType, visited); +// } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/SinglePickaxe.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/SinglePickaxe.java index 21176deb7..9ac871ad3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/SinglePickaxe.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/SinglePickaxe.java @@ -22,9 +22,11 @@ package com.sk89q.worldedit.command.tool; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Platform; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; @@ -41,19 +43,25 @@ public class SinglePickaxe implements BlockTool { @Override public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) { - World world = (World) clicked.getExtent(); - final BlockType blockType = world.getLazyBlock(clicked.toVector()).getBlockType(); - if (blockType == BlockTypes.BEDROCK && !player.canDestroyBedrock()) { + World world = (World) clicked.getExtent(); + BlockVector3 blockPoint = clicked.toBlockPoint(); + final BlockType blockType = world.getBlock(blockPoint).getBlockType(); + if (blockType == BlockTypes.BEDROCK + && !player.canDestroyBedrock()) { return true; } - - EditSession editSession = session.createEditSession(player); - editSession.getSurvivalExtent().setToolUse(config.superPickaxeDrop); + final EditSession editSession = session.createEditSession(player); + try { + editSession.getSurvivalExtent().setToolUse(config.superPickaxeDrop); + editSession.setBlock(blockPoint, BlockTypes.AIR.getDefaultState()); + } catch (MaxChangedBlocksException e) { + player.printError("Max blocks change limit reached."); + } try { if (editSession.setBlock(clicked.getBlockX(), clicked.getBlockY(), clicked.getBlockZ(), EditSession.nullBlock)) { // TODO FIXME play effect -// world.playEffect(clicked.toVector(), 2001, blockType); +// world.playEffect(clicked, 2001, blockType); } } finally { editSession.flushQueue(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/TreePlanter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/TreePlanter.java index 436d42104..41353b0ad 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/TreePlanter.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/TreePlanter.java @@ -52,13 +52,12 @@ public class TreePlanter implements BlockTool { try { boolean successful = false; - - for (int i = 0; i < 10; i++) { - if (treeType.generate(editSession, clicked.toVector().add(0, 1, 0))) { - successful = true; - break; + for (int i = 0; i < 10; i++) { + if (treeType.generate(editSession, clicked.add(0, 1, 0).toBlockPoint())) { + successful = true; + break; + } } - } if (!successful) { player.printError("A tree can't go there."); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/Brush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/Brush.java index 97a07e700..c066c7d10 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/Brush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/Brush.java @@ -21,9 +21,8 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; /** * A brush is a long-range build tool. @@ -39,6 +38,6 @@ public interface Brush { * @param size the size of the brush * @throws MaxChangedBlocksException */ - void build(EditSession editSession, Vector position, Pattern pattern, double size) throws WorldEditException; + void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/ButcherBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/ButcherBrush.java index 175cc32ae..f715c424f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/ButcherBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/ButcherBrush.java @@ -21,12 +21,12 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.util.CreatureButcher; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.visitor.EntityVisitor; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CylinderRegion; import java.util.List; @@ -40,7 +40,7 @@ public class ButcherBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { CylinderRegion region = CylinderRegion.createRadius(editSession, position, size); List entities = editSession.getEntities(region); Operations.completeLegacy(new EntityVisitor(entities.iterator(), flags.createFunction())); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/ClipboardBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/ClipboardBrush.java index 184480787..d6abe3cc9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/ClipboardBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/ClipboardBrush.java @@ -21,11 +21,11 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.session.ClipboardHolder; @@ -42,10 +42,10 @@ public class ClipboardBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { Clipboard clipboard = holder.getClipboard(); Region region = clipboard.getRegion(); - Vector centerOffset = region.getCenter().subtract(clipboard.getOrigin()); + BlockVector3 centerOffset = region.getCenter().toBlockPoint().subtract(clipboard.getOrigin()); Operation operation = holder .createPaste(editSession) diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java index 10db344ca..cfebeaf17 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/CylinderBrush.java @@ -21,10 +21,10 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; -import com.sk89q.worldedit.world.block.BlockTypes; public class CylinderBrush implements Brush { @@ -35,7 +35,7 @@ public class CylinderBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { if (pattern == null) { pattern = new BlockPattern(BlockTypes.COBBLESTONE.getDefaultState()); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/GravityBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/GravityBrush.java index 0e21d43e0..2c67b3fdc 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/GravityBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/GravityBrush.java @@ -21,12 +21,11 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; + import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Masks; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; public class GravityBrush implements Brush { @@ -38,7 +37,7 @@ public class GravityBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double sizeDouble) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double sizeDouble) throws MaxChangedBlocksException { Mask mask = editSession.getMask(); if (mask == Masks.alwaysTrue() || mask == Masks.alwaysTrue2D()) { mask = null; @@ -47,7 +46,6 @@ public class GravityBrush implements Brush { int endY = position.getBlockY() + size; int startPerformY = Math.max(0, position.getBlockY() - size); int startCheckY = fullHeight ? 0 : startPerformY; - Vector mutablePos = new Vector(0, 0, 0); for (int x = position.getBlockX() + size; x > position.getBlockX() - size; --x) { for (int z = position.getBlockZ() + size; z > position.getBlockZ() - size; --z) { int freeSpot = startCheckY; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowCylinderBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowCylinderBrush.java index 13859d587..54247c107 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowCylinderBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowCylinderBrush.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.block.BlockTypes; @@ -35,9 +35,9 @@ public class HollowCylinderBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { if (pattern == null) { - pattern = BlockTypes.COBBLESTONE.getDefaultState(); + pattern = new BlockPattern(BlockTypes.COBBLESTONE.getDefaultState()); } editSession.makeCylinder(position, pattern, size, size, height, false); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowSphereBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowSphereBrush.java index d7115efe3..9763a621a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowSphereBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/HollowSphereBrush.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.block.BlockTypes; @@ -29,9 +29,9 @@ import com.sk89q.worldedit.world.block.BlockTypes; public class HollowSphereBrush implements Brush { @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { if (pattern == null) { - pattern = BlockTypes.COBBLESTONE.getDefaultState(); + pattern = new BlockPattern(BlockTypes.COBBLESTONE.getDefaultState()); } editSession.makeSphere(position, pattern, size, size, size, false); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/OperationFactoryBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/OperationFactoryBrush.java index f9a679d62..6a323f14b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/OperationFactoryBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/OperationFactoryBrush.java @@ -21,12 +21,12 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.Contextual; import com.sk89q.worldedit.function.EditContext; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.factory.RegionFactory; public class OperationFactoryBrush implements Brush { @@ -40,7 +40,7 @@ public class OperationFactoryBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { EditContext context = new EditContext(); context.setDestination(editSession); context.setRegion(regionFactory.createCenteredAt(position, size)); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SmoothBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SmoothBrush.java index df76950d4..a2c2750b6 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SmoothBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SmoothBrush.java @@ -21,7 +21,8 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.math.convolution.GaussianKernel; import com.sk89q.worldedit.math.convolution.HeightMap; @@ -39,10 +40,11 @@ public class SmoothBrush implements Brush { } @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { - Location min = new Location(editSession.getWorld(), position.subtract(size, size, size)); - Vector max = position.add(size, size + 10, size); - Region region = new CuboidRegion(editSession.getWorld(), min.toVector(), max); + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { + Vector3 posDouble = position.toVector3(); + Location min = new Location(editSession.getWorld(), posDouble.subtract(size, size, size)); + BlockVector3 max = posDouble.add(size, size + 10, size).toBlockPoint(); + Region region = new CuboidRegion(editSession.getWorld(), min.toBlockPoint(), max); HeightMap heightMap = new HeightMap(editSession, region); HeightMapFilter filter = new HeightMapFilter(new GaussianKernel(5, 1.0)); heightMap.applyFilter(filter, iterations); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SphereBrush.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SphereBrush.java index 781ee6d1f..7c38382de 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SphereBrush.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/tool/brush/SphereBrush.java @@ -21,8 +21,7 @@ package com.sk89q.worldedit.command.tool.brush; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.world.block.BlockTypes; @@ -30,9 +29,9 @@ import com.sk89q.worldedit.world.block.BlockTypes; public class SphereBrush implements Brush { @Override - public void build(EditSession editSession, Vector position, Pattern pattern, double size) throws MaxChangedBlocksException { + public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException { if (pattern == null) { - pattern = new BlockPattern(new BaseBlock(BlockTypes.COBBLESTONE)); + pattern = new BlockPattern(BlockTypes.COBBLESTONE.getDefaultState()); } editSession.makeSphere(position, pattern, size, size, size, true); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/AsyncCommandHelper.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/AsyncCommandHelper.java new file mode 100644 index 000000000..f3b707435 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/AsyncCommandHelper.java @@ -0,0 +1,141 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.command.util; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.util.command.parametric.ExceptionConverter; +import com.sk89q.worldedit.util.task.FutureForwardingTask; +import com.sk89q.worldedit.util.task.Supervisor; +import com.sk89q.worldedit.world.World; + +import javax.annotation.Nullable; + +public class AsyncCommandHelper { + + private final ListenableFuture future; + private final Supervisor supervisor; + private final Actor sender; + private final ExceptionConverter exceptionConverter; + @Nullable + private Object[] formatArgs; + + private AsyncCommandHelper(ListenableFuture future, Supervisor supervisor, Actor sender, ExceptionConverter exceptionConverter) { + checkNotNull(future); + checkNotNull(supervisor); + checkNotNull(sender); + checkNotNull(exceptionConverter); + + this.future = future; + this.supervisor = supervisor; + this.sender = sender; + this.exceptionConverter = exceptionConverter; + } + + public AsyncCommandHelper formatUsing(Object... args) { + this.formatArgs = args; + return this; + } + + private String format(String message) { + if (formatArgs != null) { + return String.format(message, formatArgs); + } else { + return message; + } + } + + public AsyncCommandHelper registerWithSupervisor(String description) { + supervisor.monitor( + FutureForwardingTask.create( + future, format(description), sender)); + return this; + } + + public AsyncCommandHelper sendMessageAfterDelay(String message) { + FutureProgressListener.addProgressListener(future, sender, format(message)); + return this; + } + + public AsyncCommandHelper thenRespondWith(String success, String failure) { + // Send a response message + Futures.addCallback( + future, + new MessageFutureCallback.Builder(sender) + .exceptionConverter(exceptionConverter) + .onSuccess(format(success)) + .onFailure(format(failure)) + .build()); + return this; + } + + public AsyncCommandHelper thenTellErrorsOnly(String failure) { + // Send a response message + Futures.addCallback( + future, + new MessageFutureCallback.Builder(sender) + .exceptionConverter(exceptionConverter) + .onFailure(format(failure)) + .build()); + return this; + } + + public AsyncCommandHelper forRegionDataLoad(World world, boolean silent) { + checkNotNull(world); + + formatUsing(world.getName()); + registerWithSupervisor("Loading region data for '%s'"); + if (silent) { + thenTellErrorsOnly("Failed to load regions '%s'"); + } else { + sendMessageAfterDelay("(Please wait... loading the region data for '%s')"); + thenRespondWith( + "Loaded region data for '%s'", + "Failed to load regions '%s'"); + } + + return this; + } + + public AsyncCommandHelper forRegionDataSave(World world, boolean silent) { + checkNotNull(world); + + formatUsing(world.getName()); + registerWithSupervisor("Saving region data for '%s'"); + if (silent) { + thenTellErrorsOnly("Failed to save regions '%s'"); + } else { + sendMessageAfterDelay("(Please wait... saving the region data for '%s')"); + thenRespondWith( + "Saved region data for '%s'", + "Failed to load regions '%s'"); + } + + return this; + } + + public static AsyncCommandHelper wrap(ListenableFuture future, Supervisor supervisor, Actor sender, ExceptionConverter exceptionConverter) { + return new AsyncCommandHelper(future, supervisor, sender, exceptionConverter); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/FutureProgressListener.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/FutureProgressListener.java new file mode 100644 index 000000000..54d366ba4 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/FutureProgressListener.java @@ -0,0 +1,54 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.command.util; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.MoreExecutors; +import com.sk89q.worldedit.extension.platform.Actor; + +import java.util.Timer; + +public class FutureProgressListener implements Runnable { + + private static final Timer timer = new Timer(); + private static final int MESSAGE_DELAY = 1000; + + private final MessageTimerTask task; + + public FutureProgressListener(Actor sender, String message) { + checkNotNull(sender); + checkNotNull(message); + + task = new MessageTimerTask(sender, message); + timer.schedule(task, MESSAGE_DELAY); + } + + @Override + public void run() { + task.cancel(); + } + + public static void addProgressListener(ListenableFuture future, Actor sender, String message) { + future.addListener(new FutureProgressListener(sender, message), MoreExecutors.directExecutor()); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/MessageFutureCallback.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/MessageFutureCallback.java new file mode 100644 index 000000000..3abb73545 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/MessageFutureCallback.java @@ -0,0 +1,114 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.command.util; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.util.concurrent.FutureCallback; +import com.sk89q.minecraft.util.commands.CommandException; +import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.util.command.parametric.ExceptionConverter; + +import javax.annotation.Nullable; + +public class MessageFutureCallback implements FutureCallback { + + private final ExceptionConverter exceptionConverter; + private final Actor sender; + @Nullable + private final String success; + @Nullable + private final String failure; + + private MessageFutureCallback(ExceptionConverter exceptionConverter, Actor sender, @Nullable String success, @Nullable String failure) { + this.exceptionConverter = exceptionConverter; + this.sender = sender; + this.success = success; + this.failure = failure; + } + + @Override + public void onSuccess(@Nullable V v) { + if (success != null) { + sender.print(success); + } + } + + @Override + public void onFailure(@Nullable Throwable throwable) { + try { + exceptionConverter.convert(throwable); + } catch (CommandException e) { + String failure = this.failure != null ? this.failure : "An error occurred"; + String message = e.getMessage() != null ? e.getMessage() : "An unknown error occurred. Please see the console!"; + sender.printError(failure + ": " + message); + } + } + + public static class Builder { + private final Actor sender; + @Nullable + private String success; + @Nullable + private String failure; + private ExceptionConverter exceptionConverter; + + public Builder(Actor sender) { + checkNotNull(sender); + + this.sender = sender; + } + + public Builder exceptionConverter(ExceptionConverter exceptionConverter) { + this.exceptionConverter = exceptionConverter; + return this; + } + + public Builder onSuccess(@Nullable String message) { + this.success = message; + return this; + } + + public Builder onFailure(@Nullable String message) { + this.failure = message; + return this; + } + + public MessageFutureCallback build() { + checkNotNull(exceptionConverter); + return new MessageFutureCallback<>(exceptionConverter, sender, success, failure); + } + } + + public static MessageFutureCallback createRegionLoadCallback(ExceptionConverter exceptionConverter, Actor sender) { + return new Builder(sender) + .exceptionConverter(exceptionConverter) + .onSuccess("Successfully load the region data.") + .build(); + } + + public static MessageFutureCallback createRegionSaveCallback(ExceptionConverter exceptionConverter, Actor sender) { + return new Builder(sender) + .exceptionConverter(exceptionConverter) + .onSuccess("Successfully saved the region data.") + .build(); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/MessageTimerTask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/MessageTimerTask.java new file mode 100644 index 000000000..4a2549318 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/MessageTimerTask.java @@ -0,0 +1,46 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.command.util; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.extension.platform.Actor; + +import java.util.TimerTask; + +public class MessageTimerTask extends TimerTask { + + private final Actor sender; + private final String message; + + MessageTimerTask(Actor sender, String message) { + checkNotNull(sender); + checkNotNull(message); + + this.sender = sender; + this.message = message; + } + + @Override + public void run() { + sender.printDebug(message); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/entity/Entity.java b/worldedit-core/src/main/java/com/sk89q/worldedit/entity/Entity.java index ef806ce7c..31bff6968 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/entity/Entity.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/entity/Entity.java @@ -54,6 +54,14 @@ public interface Entity extends Faceted { */ Location getLocation(); + /** + * Sets the location of this entity. + * + * @param location the new location of the entity + * @return if the teleport worked + */ + boolean setLocation(Location location); + /** * Get the extent that this entity is on. * 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 4b0543043..d5be2e40d 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 @@ -19,19 +19,22 @@ package com.sk89q.worldedit.entity; -import com.sk89q.worldedit.PlayerDirection; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extent.inventory.BlockBag; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; +import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.World; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.gamemode.GameMode; +import javax.annotation.Nullable; + /** * Represents a player */ @@ -57,7 +60,7 @@ public interface Player extends Entity, Actor { * * @return the direction */ - PlayerDirection getCardinalDirection(int yawOffset); + Direction getCardinalDirection(int yawOffset); /** * Get the item that the player is holding. @@ -71,7 +74,7 @@ public interface Player extends Entity, Actor { * * @return the item id of the item the player is holding */ - BlockState getBlockInHand(HandSide handSide) throws WorldEditException; + BaseBlock getBlockInHand(HandSide handSide) throws WorldEditException; /** * Gives the player an item. @@ -237,7 +240,7 @@ public interface Player extends Entity, Actor { * * @return the direction */ - PlayerDirection getCardinalDirection(); + Direction getCardinalDirection(); /** * Pass through the wall that you are looking at. @@ -254,13 +257,24 @@ public interface Player extends Entity, Actor { * @param pitch the pitch (up/down) of the player's view in degrees * @param yaw the yaw (left/right) of the player's view in degrees */ - void setPosition(Vector pos, float pitch, float yaw); + void setPosition(Vector3 pos, float pitch, float yaw); /** * Move the player. * * @param pos where to move them */ - void setPosition(Vector pos); + void setPosition(Vector3 pos); + /** + * Sends a fake block to the client. + * + *

+ * This block isn't real. + *

+ * + * @param pos The position of the block + * @param block The block to send, null to reset + */ + > void sendFakeBlock(BlockVector3 pos, @Nullable B block); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/entity/metadata/Metadatable.java b/worldedit-core/src/main/java/com/sk89q/worldedit/entity/metadata/Metadatable.java deleted file mode 100644 index e0448420f..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/entity/metadata/Metadatable.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.sk89q.worldedit.entity.metadata; - -import java.util.Map; - -public interface Metadatable { - Map getMetaMap(); - - /** - * Set some session only metadata for the player - * - * @param key - * @param value - * @return previous value - */ - default void setMeta(String key, Object value) { - getMetaMap().put(key, value); - } - - default T getAndSetMeta(String key, T value) { - return (T) getMetaMap().put(key, value); - } - - default boolean hasMeta() { - return !getMetaMap().isEmpty(); - } - - /** - * Get the metadata for a key. - * - * @param - * @param key - * @return - */ - default V getMeta(String key) { - if (getMetaMap() != null) { - return (V) getMetaMap().get(key); - } - return null; - } - - /** - * Get the metadata for a specific key (or return the default provided) - * - * @param key - * @param def - * @param - * @return - */ - default V getMeta(String key, V def) { - if (getMetaMap() != null) { - V value = (V) getMetaMap().get(key); - return value == null ? def : value; - } - return def; - } - - /** - * Delete the metadata for a key. - * - metadata is session only - * - deleting other plugin's metadata may cause issues - * - * @param key - */ - default V deleteMeta(String key) { - return getMetaMap() == null ? null : (V) getMetaMap().remove(key); - } -} 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 07fdec002..e6364bbec 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 @@ -20,13 +20,13 @@ package com.sk89q.worldedit.event.extent; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.event.Cancellable; import com.sk89q.worldedit.event.Event; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.World; import javax.annotation.Nullable; @@ -55,7 +55,7 @@ import static com.sk89q.worldedit.EditSession.Stage; * is set to {@link Stage#BEFORE_HISTORY}, then you can drop (or log) changes * before the change has reached the history, reordering, and actual change * extents, but that means that any changes made with - * {@link EditSession#rawSetBlock(Vector, BaseBlock)} will skip your + * {@link EditSession#rawSetBlock(BlockVector3, BlockStateHolder)} will skip your * custom {@link Extent} because that method bypasses history (and reorder). * It is thus recommended that loggers intercept at {@link Stage#BEFORE_CHANGE} * and block interceptors intercept at BOTH {@link Stage#BEFORE_CHANGE} and diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/event/extent/PasteEvent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/event/extent/PasteEvent.java index f004f8621..386a2d80e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/event/extent/PasteEvent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/event/extent/PasteEvent.java @@ -19,12 +19,13 @@ package com.sk89q.worldedit.event.extent; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.Cancellable; import com.sk89q.worldedit.event.Event; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.math.BlockVector3; + import java.net.URI; @@ -35,11 +36,11 @@ public class PasteEvent extends Event implements Cancellable { private final Player player; private final Clipboard clipboard; private final URI uri; - private final Vector to; + private final BlockVector3 to; private final Extent extent; private boolean cancelled; - public PasteEvent(Player player, Clipboard clipboard, URI uri, Extent extent, Vector to) { + public PasteEvent(Player player, Clipboard clipboard, URI uri, Extent extent, BlockVector3 to) { this.player = player; this.clipboard = clipboard; this.uri = uri; @@ -59,7 +60,7 @@ public class PasteEvent extends Event implements Cancellable { return uri; } - public Vector getPosition() { + public BlockVector3 getPosition() { return to; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/BlockFactory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/BlockFactory.java index 141124855..8ee07c223 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/BlockFactory.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/BlockFactory.java @@ -21,10 +21,12 @@ package com.sk89q.worldedit.extension.factory; import com.sk89q.util.StringUtil; import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.extension.factory.parser.DefaultBlockParser; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.internal.registry.AbstractFactory; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BaseBlock; import java.util.HashSet; import java.util.Set; @@ -36,7 +38,7 @@ import java.util.Set; *

Instances of this class can be taken from * {@link WorldEdit#getBlockFactory()}.

*/ -public class BlockFactory extends AbstractFactory { +public class BlockFactory extends AbstractFactory { /** * Create a new instance. @@ -46,7 +48,7 @@ public class BlockFactory extends AbstractFactory { public BlockFactory(WorldEdit worldEdit) { super(worldEdit); - parsers.add(new DefaultBlockParser(worldEdit)); + register(new DefaultBlockParser(worldEdit)); } /** @@ -57,8 +59,8 @@ public class BlockFactory extends AbstractFactory { * @return a set of blocks * @throws InputParseException thrown in error with the input */ - public Set parseFromListInput(String input, ParserContext context) throws InputParseException { - Set blocks = new HashSet<>(); + public Set parseFromListInput(String input, ParserContext context) throws InputParseException { + Set blocks = new HashSet<>(); String[] splits = input.split(","); for (String token : StringUtil.parseListInQuotes(splits, ',', '[', ']')) { blocks.add(parseFromInput(token, context)); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/ItemFactory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/ItemFactory.java index 321fc6280..e2a2bee29 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/ItemFactory.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/ItemFactory.java @@ -21,6 +21,7 @@ package com.sk89q.worldedit.extension.factory; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.blocks.BaseItem; +import com.sk89q.worldedit.extension.factory.parser.DefaultItemParser; import com.sk89q.worldedit.internal.registry.AbstractFactory; public class ItemFactory extends AbstractFactory { @@ -33,7 +34,7 @@ public class ItemFactory extends AbstractFactory { public ItemFactory(WorldEdit worldEdit) { super(worldEdit); - parsers.add(new DefaultItemParser(worldEdit)); + register(new DefaultItemParser(worldEdit)); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/MaskFactory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/MaskFactory.java index 01fef9803..0f9f04fde 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/MaskFactory.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/MaskFactory.java @@ -20,8 +20,24 @@ package com.sk89q.worldedit.extension.factory; import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.factory.parser.mask.BlockCategoryMaskParser; +import com.sk89q.worldedit.extension.factory.parser.mask.DefaultMaskParser; +import com.sk89q.worldedit.extension.factory.parser.mask.ExistingMaskParser; +import com.sk89q.worldedit.extension.factory.parser.mask.LazyRegionMaskParser; +import com.sk89q.worldedit.extension.factory.parser.mask.NegateMaskParser; +import com.sk89q.worldedit.extension.factory.parser.mask.NoiseMaskParser; +import com.sk89q.worldedit.extension.factory.parser.mask.RegionMaskParser; +import com.sk89q.worldedit.extension.factory.parser.mask.SolidMaskParser; +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.function.mask.Mask; +import com.sk89q.worldedit.function.mask.MaskIntersection; import com.sk89q.worldedit.internal.registry.AbstractFactory; +import com.sk89q.worldedit.internal.registry.InputParser; + +import java.util.ArrayList; +import java.util.List; /** * A registry of known {@link Mask}s. Provides methods to instantiate @@ -40,7 +56,42 @@ public final class MaskFactory extends AbstractFactory { public MaskFactory(WorldEdit worldEdit) { super(worldEdit); - parsers.add(new DefaultMaskParser(worldEdit)); + register(new ExistingMaskParser(worldEdit)); + register(new SolidMaskParser(worldEdit)); + register(new LazyRegionMaskParser(worldEdit)); + register(new RegionMaskParser(worldEdit)); + register(new BlockCategoryMaskParser(worldEdit)); + register(new NoiseMaskParser(worldEdit)); + register(new NegateMaskParser(worldEdit)); + register(new DefaultMaskParser(worldEdit)); + } + + @Override + public Mask parseFromInput(String input, ParserContext context) throws InputParseException { + List masks = new ArrayList<>(); + + for (String component : input.split(" ")) { + if (component.isEmpty()) { + continue; + } + + for (InputParser parser : getParsers()) { + Mask match = parser.parseFromInput(component, context); + + if (match != null) { + masks.add(match); + } + } + } + + switch (masks.size()) { + case 0: + throw new NoMatchException("No match for '" + input + "'"); + case 1: + return masks.get(0); + default: + return new MaskIntersection(masks); + } } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/PatternFactory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/PatternFactory.java index dde70291e..7b93c0d61 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/PatternFactory.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/PatternFactory.java @@ -20,6 +20,11 @@ package com.sk89q.worldedit.extension.factory; import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.factory.parser.pattern.BlockCategoryPatternParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.ClipboardPatternParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.DefaultPatternParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.RandomPatternParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.SingleBlockPatternParser; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.internal.registry.AbstractFactory; @@ -40,7 +45,11 @@ public final class PatternFactory extends AbstractFactory { public PatternFactory(WorldEdit worldEdit) { super(worldEdit); - parsers.add(new HashTagPatternParser(worldEdit)); +// register(new ClipboardPatternParser(worldEdit)); +// register(new SingleBlockPatternParser(worldEdit)); +// register(new RandomPatternParser(worldEdit)); + register(new BlockCategoryPatternParser(worldEdit)); + register(new DefaultPatternParser(worldEdit)); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultBlockParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultBlockParser.java similarity index 91% rename from worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultBlockParser.java rename to worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultBlockParser.java index 39ff01699..904c67d95 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultBlockParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultBlockParser.java @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.sk89q.worldedit.extension.factory; +package com.sk89q.worldedit.extension.factory.parser; import com.boydti.fawe.command.SuggestInputParseException; import com.boydti.fawe.jnbt.JSON2NBT; @@ -26,10 +26,14 @@ import com.boydti.fawe.util.MathMan; import com.boydti.fawe.util.StringMan; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.BaseItem; +import com.sk89q.worldedit.IncompleteRegionException; +import com.sk89q.worldedit.NotABlockException; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.blocks.MobSpawnerBlock; import com.sk89q.worldedit.blocks.SignBlock; import com.sk89q.worldedit.blocks.SkullBlock; @@ -44,11 +48,15 @@ import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.SlottableBlockBag; import com.sk89q.worldedit.internal.registry.InputParser; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.world.World; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.world.block.FuzzyBlockState; import com.sk89q.worldedit.world.registry.LegacyMapper; import java.util.Arrays; @@ -61,7 +69,7 @@ import java.util.stream.Stream; /** * Parses block input strings. */ -public class DefaultBlockParser extends InputParser { +public class DefaultBlockParser extends InputParser { public DefaultBlockParser(WorldEdit worldEdit) { super(worldEdit); @@ -70,7 +78,7 @@ public class DefaultBlockParser extends InputParser { private static BlockState getBlockInHand(Actor actor, HandSide handSide) throws InputParseException { if (actor instanceof Player) { try { - return ((Player) actor).getBlockInHand(handSide); + return ((Player) actor).getBlockInHand(handSide).toImmutableState(); } catch (NotABlockException e) { throw new InputParseException("You're not holding a block!"); } catch (WorldEditException e) { @@ -81,13 +89,14 @@ public class DefaultBlockParser extends InputParser { } } - public BlockStateHolder parseFromInput(String input, ParserContext context) + @Override + public BaseBlock parseFromInput(String input, ParserContext context) throws InputParseException { String originalInput = input; input = input.replace(";", "|"); Exception suppressed = null; try { - BlockStateHolder modified = parseLogic(input, context); + BaseBlock modified = parseLogic(input, context); if (modified != null) { return modified; } @@ -156,7 +165,7 @@ public class DefaultBlockParser extends InputParser { } } - private BlockStateHolder parseLogic(String input, ParserContext context) throws InputParseException { + private BaseBlock parseLogic(String input, ParserContext context) throws InputParseException { String[] blockAndExtraData = input.trim().split("\\|", 2); blockAndExtraData[0] = woolMapper(blockAndExtraData[0]); @@ -172,7 +181,7 @@ public class DefaultBlockParser extends InputParser { } else if (MathMan.isInteger(split[0])) { state = LegacyMapper.getInstance().getBlockFromLegacy(Integer.parseInt(split[0]), Integer.parseInt(split[1])); } else { - BlockTypes type = BlockTypes.get(split[0].toLowerCase()); + BlockType type = BlockTypes.get(split[0].toLowerCase()); if (type != null) { state = LegacyMapper.getInstance().getBlockFromLegacy(type.getLegacyCombinedId() >> 4, Integer.parseInt(split[1])); } @@ -198,7 +207,7 @@ public class DefaultBlockParser extends InputParser { int index = Integer.parseInt(typeString.replaceAll("[a-z]+", "")); // Get the block type from the "primary position" final World world = context.requireWorld(); - final Vector primaryPosition; + final BlockVector3 primaryPosition; try { primaryPosition = context.requireSession().getRegionSelector(world).getVerticies().get(index - 1); } catch (IncompleteRegionException e) { @@ -231,13 +240,13 @@ public class DefaultBlockParser extends InputParser { state = item.getType().getBlockType().getDefaultState(); nbt = item.getNbtData(); } else { - BlockTypes type = BlockTypes.parse(typeString.toLowerCase()); + BlockType type = BlockTypes.parse(typeString.toLowerCase()); if (type != null) state = type.getDefaultState(); if (state == null) { throw new NoMatchException("Does not match a valid block type: '" + input + "'"); } } - if (nbt == null) nbt = state.getNbtData(); +// if (nbt == null) nbt = state.getNbtData(); if (stateString != null) { state = BlockState.get(state.getBlockType(), "[" + stateString + "]", state); @@ -254,12 +263,12 @@ public class DefaultBlockParser extends InputParser { } // Check if the item is allowed - BlockTypes blockType = state.getBlockType(); + BlockType blockType = state.getBlockType(); if (context.isRestricted()) { Actor actor = context.requireActor(); if (actor != null) { - if (!actor.hasPermission("worldedit.anyblock") && worldEdit.getConfiguration().disallowedBlocks.contains(blockType)) { + if (!actor.hasPermission("worldedit.anyblock") && worldEdit.getConfiguration().disallowedBlocks.contains(blockType.getId())) { throw new DisallowedUsageException("You are not allowed to use '" + input + "'"); } if (nbt != null) { @@ -312,7 +321,7 @@ public class DefaultBlockParser extends InputParser { return new SkullBlock(state, type.replace(" ", "_")); // valid MC usernames } else { - return state; + return state.toBaseBlock(); } } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultItemParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultItemParser.java similarity index 71% rename from worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultItemParser.java rename to worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultItemParser.java index 523ea1898..f6c396b93 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultItemParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultItemParser.java @@ -17,14 +17,12 @@ * along with this program. If not, see . */ -package com.sk89q.worldedit.extension.factory; +package com.sk89q.worldedit.extension.factory.parser; -import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.ParserContext; -import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.internal.registry.InputParser; import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemTypes; @@ -32,7 +30,7 @@ import com.sk89q.worldedit.world.registry.LegacyMapper; public class DefaultItemParser extends InputParser { - protected DefaultItemParser(WorldEdit worldEdit) { + public DefaultItemParser(WorldEdit worldEdit) { super(worldEdit); } @@ -46,17 +44,8 @@ public class DefaultItemParser extends InputParser { ItemType type; if (split.length == 1) { type = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(split[0])); - } else if (MathMan.isInteger(split[0])) { - type = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(split[0]), Integer.parseInt(split[1])); } else { - type = ItemTypes.parse(input); - if (type != null) { - Integer legacy = LegacyMapper.getInstance().getLegacyCombined(type); - if (legacy != null) { - ItemTypes newType = LegacyMapper.getInstance().getItemFromLegacy(legacy >> 4, Integer.parseInt(split[1])); - if (newType != null) type = newType; - } - } + type = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(split[0]), Integer.parseInt(split[1])); } item = new BaseItem(type); } catch (NumberFormatException e) { @@ -64,8 +53,10 @@ public class DefaultItemParser extends InputParser { } if (item == null) { - item = WorldEdit.getInstance().getPlatformManager() - .queryCapability(Capability.GAME_HOOKS).getRegistries().getItemRegistry().createFromId(input.toLowerCase()); + ItemType type = ItemTypes.get(input.toLowerCase()); + if (type != null) { + item = new BaseItem(type); + } } if (item == null) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/BlockCategoryMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/BlockCategoryMaskParser.java new file mode 100644 index 000000000..478ba22e6 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/BlockCategoryMaskParser.java @@ -0,0 +1,55 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extension.factory.parser.mask; + +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.input.InputParseException; +import com.sk89q.worldedit.extension.input.ParserContext; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.function.mask.BlockCategoryMask; +import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.internal.registry.InputParser; +import com.sk89q.worldedit.session.request.Request; +import com.sk89q.worldedit.world.block.BlockCategories; +import com.sk89q.worldedit.world.block.BlockCategory; + +public class BlockCategoryMaskParser extends InputParser { + + public BlockCategoryMaskParser(WorldEdit worldEdit) { + super(worldEdit); + } + + @Override + public Mask parseFromInput(String input, ParserContext context) throws InputParseException { + if (input.startsWith("##")) { + Extent extent = Request.request().getEditSession(); + + // This means it's a tag mask. + BlockCategory category = BlockCategories.get(input.substring(2).toLowerCase()); + if (category == null) { + throw new InputParseException("Unrecognised tag '" + input.substring(2) + '\''); + } else { + return new BlockCategoryMask(extent, category); + } + } + + return null; + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/DefaultMaskParser.java similarity index 84% rename from worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultMaskParser.java rename to worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/DefaultMaskParser.java index 95248cd5b..29ebdec39 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultMaskParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/DefaultMaskParser.java @@ -1,4 +1,23 @@ -package com.sk89q.worldedit.extension.factory; +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extension.factory.parser.mask; import com.boydti.fawe.command.FaweParser; import com.boydti.fawe.command.SuggestInputParseException; @@ -14,11 +33,23 @@ import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.BlockMaskBuilder; +import com.sk89q.worldedit.function.mask.BiomeMask2D; +import com.sk89q.worldedit.function.mask.BlockMask; +import com.sk89q.worldedit.function.mask.ExistingBlockMask; +import com.sk89q.worldedit.function.mask.ExpressionMask; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.MaskIntersection; import com.sk89q.worldedit.function.mask.MaskUnion; import com.sk89q.worldedit.internal.command.ActorAuthorizer; import com.sk89q.worldedit.internal.command.WorldEditBinding; +import com.sk89q.worldedit.function.mask.Masks; +import com.sk89q.worldedit.function.mask.OffsetMask; +import com.sk89q.worldedit.internal.expression.Expression; +import com.sk89q.worldedit.internal.expression.ExpressionException; +import com.sk89q.worldedit.internal.registry.InputParser; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; +import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment; import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.util.command.Dispatcher; import com.sk89q.worldedit.util.command.SimpleDispatcher; @@ -27,6 +58,11 @@ import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; import java.util.ArrayList; +import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.world.biome.Biomes; +import com.sk89q.worldedit.world.registry.BiomeRegistry; + +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.regex.Pattern; @@ -36,7 +72,6 @@ import java.util.stream.Stream; public class DefaultMaskParser extends FaweParser { private final Dispatcher dispatcher; private final Pattern INTERSECTION_PATTERN = Pattern.compile("[&|;]+(?![^\\[]*\\])"); - public DefaultMaskParser(WorldEdit worldEdit) { super(worldEdit); this.dispatcher = new SimpleDispatcher(); @@ -150,9 +185,9 @@ public class DefaultMaskParser extends FaweParser { } } } else { - List args = entry.getValue(); - String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " ")); - try { + List args = entry.getValue(); + String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " ")); + try { mask = (Mask) dispatcher.call(command + cmdArgs, locals, new String[0]); } catch (SuggestInputParseException rethrow) { throw rethrow; @@ -206,5 +241,6 @@ public class DefaultMaskParser extends FaweParser { } else { return null; } + } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/ExistingMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/ExistingMaskParser.java new file mode 100644 index 000000000..a1dea6f48 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/ExistingMaskParser.java @@ -0,0 +1,51 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extension.factory.parser.mask; + +import com.google.common.collect.Lists; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.input.InputParseException; +import com.sk89q.worldedit.extension.input.ParserContext; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.function.mask.ExistingBlockMask; +import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.internal.registry.SimpleInputParser; +import com.sk89q.worldedit.session.request.Request; + +import java.util.List; + +public class ExistingMaskParser extends SimpleInputParser { + + public ExistingMaskParser(WorldEdit worldEdit) { + super(worldEdit); + } + + @Override + public List getMatchedAliases() { + return Lists.newArrayList("#existing"); + } + + @Override + public Mask parseFromSimpleInput(String input, ParserContext context) throws InputParseException { + Extent extent = Request.request().getEditSession(); + + return new ExistingBlockMask(extent); + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/LazyRegionMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/LazyRegionMaskParser.java new file mode 100644 index 000000000..82bc14d2b --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/LazyRegionMaskParser.java @@ -0,0 +1,48 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extension.factory.parser.mask; + +import com.google.common.collect.Lists; +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.Mask; +import com.sk89q.worldedit.function.mask.RegionMask; +import com.sk89q.worldedit.internal.registry.SimpleInputParser; +import com.sk89q.worldedit.session.request.RequestSelection; + +import java.util.List; + +public class LazyRegionMaskParser extends SimpleInputParser { + + public LazyRegionMaskParser(WorldEdit worldEdit) { + super(worldEdit); + } + + @Override + public List getMatchedAliases() { + return Lists.newArrayList("#dregion", "#dselection", "#dsel"); + } + + @Override + public Mask parseFromSimpleInput(String input, ParserContext context) throws InputParseException { + return new RegionMask(new RequestSelection()); + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/NegateMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/NegateMaskParser.java new file mode 100644 index 000000000..9e1c2e9df --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/NegateMaskParser.java @@ -0,0 +1,47 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extension.factory.parser.mask; + +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.Mask; +import com.sk89q.worldedit.function.mask.Masks; +import com.sk89q.worldedit.internal.registry.InputParser; + +public class NegateMaskParser extends InputParser { + + public NegateMaskParser(WorldEdit worldEdit) { + super(worldEdit); + } + + @Override + public Mask parseFromInput(String input, ParserContext context) throws InputParseException { + if (!input.startsWith("!")) { + return null; + } + + if (input.length() > 1) { + return Masks.negate(worldEdit.getMaskFactory().parseFromInput(input.substring(1), context)); + } else { + throw new InputParseException("Can't negate nothing!"); + } + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/NoiseMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/NoiseMaskParser.java new file mode 100644 index 000000000..0cb1a85e8 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/NoiseMaskParser.java @@ -0,0 +1,45 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extension.factory.parser.mask; + +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.Mask; +import com.sk89q.worldedit.function.mask.NoiseFilter; +import com.sk89q.worldedit.internal.registry.InputParser; +import com.sk89q.worldedit.math.noise.RandomNoise; + +public class NoiseMaskParser extends InputParser { + + public NoiseMaskParser(WorldEdit worldEdit) { + super(worldEdit); + } + + @Override + public Mask parseFromInput(String input, ParserContext context) throws InputParseException { + if (!input.startsWith("%")) { + return null; + } + + int i = Integer.parseInt(input.substring(1)); + return new NoiseFilter(new RandomNoise(), ((double) i) / 100); + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/RegionMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/RegionMaskParser.java new file mode 100644 index 000000000..21963835d --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/RegionMaskParser.java @@ -0,0 +1,52 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extension.factory.parser.mask; + +import com.google.common.collect.Lists; +import com.sk89q.worldedit.IncompleteRegionException; +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.Mask; +import com.sk89q.worldedit.function.mask.RegionMask; +import com.sk89q.worldedit.internal.registry.SimpleInputParser; + +import java.util.List; + +public class RegionMaskParser extends SimpleInputParser { + + public RegionMaskParser(WorldEdit worldEdit) { + super(worldEdit); + } + + @Override + public List getMatchedAliases() { + return Lists.newArrayList("#region", "#selection", "#sel"); + } + + @Override + public Mask parseFromSimpleInput(String input, ParserContext context) throws InputParseException { + try { + return new RegionMask(context.requireSession().getSelection(context.requireWorld()).clone()); + } catch (IncompleteRegionException e) { + throw new InputParseException("Please make a selection first."); + } + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/SolidMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/SolidMaskParser.java new file mode 100644 index 000000000..84df2fec8 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/SolidMaskParser.java @@ -0,0 +1,51 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extension.factory.parser.mask; + +import com.google.common.collect.Lists; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.input.InputParseException; +import com.sk89q.worldedit.extension.input.ParserContext; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.function.mask.SolidBlockMask; +import com.sk89q.worldedit.internal.registry.SimpleInputParser; +import com.sk89q.worldedit.session.request.Request; + +import java.util.List; + +public class SolidMaskParser extends SimpleInputParser { + + public SolidMaskParser(WorldEdit worldEdit) { + super(worldEdit); + } + + @Override + public List getMatchedAliases() { + return Lists.newArrayList("#solid"); + } + + @Override + public Mask parseFromSimpleInput(String input, ParserContext context) throws InputParseException { + Extent extent = Request.request().getEditSession(); + + return new SolidBlockMask(extent); + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/BlockCategoryPatternParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/BlockCategoryPatternParser.java new file mode 100644 index 000000000..3b89b3cef --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/BlockCategoryPatternParser.java @@ -0,0 +1,64 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extension.factory.parser.pattern; + +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.input.InputParseException; +import com.sk89q.worldedit.extension.input.ParserContext; +import com.sk89q.worldedit.function.pattern.BlockPattern; +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.world.block.BlockCategories; +import com.sk89q.worldedit.world.block.BlockCategory; +import com.sk89q.worldedit.world.block.BlockType; + +import java.util.List; +import java.util.stream.Collectors; + +public class BlockCategoryPatternParser extends InputParser { + + public BlockCategoryPatternParser(WorldEdit worldEdit) { + super(worldEdit); + } + + @Override + public List getSuggestions() { + return BlockCategory.REGISTRY.keySet().stream().map(str -> "##" + str).collect(Collectors.toList()); + } + + @Override + public Pattern parseFromInput(String input, ParserContext context) throws InputParseException { + if(!input.startsWith("##")) { + return null; + } + BlockCategory category = BlockCategories.get(input.substring(2).toLowerCase()); + if (category == null) { + throw new InputParseException("Unknown block tag: " + input.substring(2)); + } + RandomPattern randomPattern = new RandomPattern(); + + for (BlockType blockType : category.getAll()) { + randomPattern.add(new BlockPattern(blockType.getDefaultState()), 1.0 / category.getAll().size()); + } + + return randomPattern; + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/ClipboardPatternParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/ClipboardPatternParser.java new file mode 100644 index 000000000..720bf8956 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/ClipboardPatternParser.java @@ -0,0 +1,207 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extension.factory.parser.pattern; + +import com.boydti.fawe.command.FaweParser; +import com.boydti.fawe.command.SuggestInputParseException; +import com.boydti.fawe.config.BBC; +import com.boydti.fawe.object.random.TrueRandom; +import com.boydti.fawe.util.StringMan; +import com.sk89q.minecraft.util.commands.CommandException; +import com.sk89q.minecraft.util.commands.CommandLocals; + +import com.google.common.collect.Lists; +import com.sk89q.worldedit.EmptyClipboardException; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.command.PatternCommands; +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.extension.platform.Actor; +import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.function.pattern.RandomPattern; +import com.sk89q.worldedit.internal.command.ActorAuthorizer; +import com.sk89q.worldedit.internal.command.WorldEditBinding; +import com.sk89q.worldedit.internal.expression.Expression; +import com.sk89q.worldedit.internal.expression.ExpressionException; +import com.sk89q.worldedit.util.command.Dispatcher; +import com.sk89q.worldedit.util.command.SimpleDispatcher; +import com.sk89q.worldedit.util.command.parametric.ParametricBuilder; +import com.sk89q.worldedit.world.block.BlockTypes; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class ClipboardPatternParser extends FaweParser { + private final Dispatcher dispatcher; + + public ClipboardPatternParser(WorldEdit worldEdit) { + super(worldEdit); + this.dispatcher = new SimpleDispatcher(); + this.register(new PatternCommands(worldEdit)); + } + + @Override + public Dispatcher getDispatcher() { + return dispatcher; + } + + public void register(Object clazz) { + ParametricBuilder builder = new ParametricBuilder(); + builder.setAuthorizer(new ActorAuthorizer()); + builder.addBinding(new WorldEditBinding(worldEdit)); + builder.registerMethodsAsCommands(dispatcher, clazz); + } + + @Override + public Pattern parseFromInput(String input, ParserContext context) throws InputParseException { + if (input.isEmpty()) { + throw new SuggestInputParseException("No input provided", "", () -> Stream.concat(Stream.of("#", ",", "&"), BlockTypes.getNameSpaces().stream().map(n -> n + ":")).collect(Collectors.toList())); + } + List chances = new ArrayList<>(); + List patterns = new ArrayList<>(); + final CommandLocals locals = new CommandLocals(); + Actor actor = context != null ? context.getActor() : null; + if (actor != null) { + locals.put(Actor.class, actor); + } + try { + for (Map.Entry> entry : parse(input)) { + ParseEntry pe = entry.getKey(); + final String command = pe.input; + String full = pe.full; + Pattern pattern = null; + double chance = 1; + if (command.isEmpty()) { + pattern = parseFromInput(StringMan.join(entry.getValue(), ','), context); + } else if (dispatcher.get(command) == null) { + // Legacy patterns + char char0 = command.charAt(0); + boolean charMask = input.length() > 1 && input.charAt(1) != '['; + if (charMask && input.charAt(0) == '=') { + return parseFromInput(char0 + "[" + input.substring(1) + "]", context); + } + if (char0 == '#') { + throw new SuggestInputParseException(new NoMatchException("Unknown pattern: " + full + ", See: //patterns"), full, + () -> { + if (full.length() == 1) return new ArrayList<>(dispatcher.getPrimaryAliases()); + return dispatcher.getAliases().stream().filter( + s -> s.startsWith(command.toLowerCase()) + ).collect(Collectors.toList()); + } + ); + } + + + if (charMask) { + switch (char0) { + case '$': { + String value = command.substring(1) + ((entry.getValue().isEmpty()) ? "" : "[" + StringMan.join(entry.getValue(), "][") + "]"); + if (value.contains(":")) { + if (value.charAt(0) == ':') value.replaceFirst(":", ""); + value = value.replaceAll(":", "]["); + } + pattern = parseFromInput(char0 + "[" + value + "]", context); + break; + } + } + } + if (pattern == null) { + if (command.startsWith("[")) { + int end = command.lastIndexOf(']'); + pattern = parseFromInput(command.substring(1, end == -1 ? command.length() : end), context); + } else { + int percentIndex = command.indexOf('%'); + if (percentIndex != -1) { // Legacy percent pattern + chance = Expression.compile(command.substring(0, percentIndex)).evaluate(); + String value = command.substring(percentIndex + 1); + if (!entry.getValue().isEmpty()) { + if (!value.isEmpty()) value += " "; + value += StringMan.join(entry.getValue(), " "); + } + pattern = parseFromInput(value, context); + } else { // legacy block pattern + try { + pattern = worldEdit.getBlockFactory().parseFromInput(pe.full, context); + } catch (NoMatchException e) { + throw new NoMatchException(e.getMessage() + " See: //patterns"); + } + } + } + } + } else { + List args = entry.getValue(); + String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " ")); + try { + pattern = (Pattern) dispatcher.call(command + cmdArgs, locals, new String[0]); + } catch (SuggestInputParseException rethrow) { + throw rethrow; + } catch (Throwable e) { + throw SuggestInputParseException.of(e, full, () -> { + try { + List suggestions = dispatcher.get(command).getCallable().getSuggestions(cmdArgs, locals); + if (suggestions.size() <= 2) { + for (int i = 0; i < suggestions.size(); i++) { + String suggestion = suggestions.get(i); + if (suggestion.indexOf(' ') != 0) { + String[] split = suggestion.split(" "); + suggestion = BBC.color("[" + StringMan.join(split, "][") + "]"); + suggestions.set(i, suggestion); + } + } + } + return suggestions; + } catch (CommandException e1) { + throw new InputParseException(e1.getMessage()); + } catch (Throwable e2) { + e2.printStackTrace(); + throw new InputParseException(e2.getMessage()); + } + }); + } + } + if (pattern != null) { + patterns.add(pattern); + chances.add(chance); + } + } + } catch (InputParseException rethrow) { + throw rethrow; + } catch (Throwable e) { + e.printStackTrace(); + throw new InputParseException(e.getMessage(), e); + } + if (patterns.isEmpty()) { + return null; + } else if (patterns.size() == 1) { + return patterns.get(0); + } else { + RandomPattern random = new RandomPattern(new TrueRandom()); + for (int i = 0; i < patterns.size(); i++) { + random.add(patterns.get(i), chances.get(i)); + } + return random; + } + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/HashTagPatternParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/DefaultPatternParser.java similarity index 88% rename from worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/HashTagPatternParser.java rename to worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/DefaultPatternParser.java index f32db3a77..bb5e353ae 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/HashTagPatternParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/DefaultPatternParser.java @@ -1,4 +1,23 @@ -package com.sk89q.worldedit.extension.factory; +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extension.factory.parser.pattern; import com.boydti.fawe.command.FaweParser; import com.boydti.fawe.command.SuggestInputParseException; @@ -7,6 +26,10 @@ import com.boydti.fawe.object.random.TrueRandom; import com.boydti.fawe.util.StringMan; import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandLocals; + +import com.google.common.collect.Lists; +import com.sk89q.worldedit.EmptyClipboardException; +import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.command.PatternCommands; import com.sk89q.worldedit.extension.input.InputParseException; @@ -30,10 +53,10 @@ import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; -public class HashTagPatternParser extends FaweParser { +public class DefaultPatternParser extends FaweParser { private final Dispatcher dispatcher; - public HashTagPatternParser(WorldEdit worldEdit) { + public DefaultPatternParser(WorldEdit worldEdit) { super(worldEdit); this.dispatcher = new SimpleDispatcher(); this.register(new PatternCommands(worldEdit)); @@ -179,8 +202,6 @@ public class HashTagPatternParser extends FaweParser { random.add(patterns.get(i), chances.get(i)); } return random; - } + } } - - } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/RandomPatternParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/RandomPatternParser.java similarity index 88% rename from worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/RandomPatternParser.java rename to worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/RandomPatternParser.java index 2cc9eae94..f9a05c9e3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/RandomPatternParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/RandomPatternParser.java @@ -17,21 +17,22 @@ * along with this program. If not, see . */ -package com.sk89q.worldedit.extension.factory; +package com.sk89q.worldedit.extension.factory.parser.pattern; import com.sk89q.util.StringUtil; import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.factory.BlockFactory; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.function.pattern.BlockPattern; 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.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BaseBlock; -class RandomPatternParser extends InputParser { +public class RandomPatternParser extends InputParser { - RandomPatternParser(WorldEdit worldEdit) { + public RandomPatternParser(WorldEdit worldEdit) { super(worldEdit); } @@ -42,7 +43,7 @@ class RandomPatternParser extends InputParser { String[] splits = input.split(","); for (String token : StringUtil.parseListInQuotes(splits, ',', '[', ']')) { - BlockStateHolder block; + BaseBlock block; double chance; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/SingleBlockPatternParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/SingleBlockPatternParser.java similarity index 89% rename from worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/SingleBlockPatternParser.java rename to worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/SingleBlockPatternParser.java index cd3adb5e7..960983780 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/SingleBlockPatternParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/SingleBlockPatternParser.java @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.sk89q.worldedit.extension.factory; +package com.sk89q.worldedit.extension.factory.parser.pattern; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.extension.input.InputParseException; @@ -26,9 +26,9 @@ import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.internal.registry.InputParser; -class SingleBlockPatternParser extends InputParser { +public class SingleBlockPatternParser extends InputParser { - SingleBlockPatternParser(WorldEdit worldEdit) { + public SingleBlockPatternParser(WorldEdit worldEdit) { super(worldEdit); } 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 e214d2e5f..66fb43d85 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 @@ -19,28 +19,28 @@ package com.sk89q.worldedit.extension.platform; -import com.sk89q.worldedit.NotABlockException; -import com.sk89q.worldedit.PlayerDirection; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.blocks.BlockMaterial; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.internal.cui.CUIEvent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; +import com.sk89q.worldedit.util.Direction; +import com.sk89q.worldedit.util.HandSide; +import com.sk89q.worldedit.util.Location; +import com.sk89q.worldedit.util.TargetBlock; +import com.sk89q.worldedit.util.auth.AuthorizationException; import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.blocks.BlockType; import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.block.BlockTypeUtil; import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.gamemode.GameModes; import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemTypes; -import com.sk89q.worldedit.entity.Player; -import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.internal.cui.CUIEvent; -import com.sk89q.worldedit.util.HandSide; -import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.util.TargetBlock; -import com.sk89q.worldedit.util.auth.AuthorizationException; +import com.sk89q.worldedit.world.registry.BlockMaterial; import java.io.File; @@ -62,25 +62,25 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { * @param rot yaw * @return the direction */ - private static PlayerDirection getDirection(double rot) { + private static Direction getDirection(double rot) { if (0 <= rot && rot < 22.5) { - return PlayerDirection.SOUTH; + return Direction.SOUTH; } else if (22.5 <= rot && rot < 67.5) { - return PlayerDirection.SOUTH_WEST; + return Direction.SOUTHWEST; } else if (67.5 <= rot && rot < 112.5) { - return PlayerDirection.WEST; + return Direction.WEST; } else if (112.5 <= rot && rot < 157.5) { - return PlayerDirection.NORTH_WEST; + return Direction.NORTHWEST; } else if (157.5 <= rot && rot < 202.5) { - return PlayerDirection.NORTH; + return Direction.NORTH; } else if (202.5 <= rot && rot < 247.5) { - return PlayerDirection.NORTH_EAST; + return Direction.NORTHEAST; } else if (247.5 <= rot && rot < 292.5) { - return PlayerDirection.EAST; + return Direction.EAST; } else if (292.5 <= rot && rot < 337.5) { - return PlayerDirection.SOUTH_EAST; + return Direction.SOUTHEAST; } else if (337.5 <= rot && rot < 360.0) { - return PlayerDirection.SOUTH; + return Direction.SOUTH; } else { return null; } @@ -107,7 +107,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { byte free = 0; while (y <= world.getMaximumPoint().getBlockY() + 2) { - if (!world.getBlock(new Vector(x, y, z)).getBlockType().getMaterial().isMovementBlocker()) { + if (!world.getBlock(BlockVector3.at(x, y, z)).getBlockType().getMaterial().isMovementBlocker()) { ++free; } else { free = 0; @@ -115,9 +115,10 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { if (free == 2) { if (y - 1 != origY) { - final Vector pos = new Vector(x, y - 2, z); + final BlockVector3 pos = BlockVector3.at(x, y - 2, z); final BlockStateHolder state = world.getBlock(pos); - setPosition(new Vector(x + 0.5, y - 2 + BlockType.centralTopLimit(state), z + 0.5)); + setPosition(Vector3.at(x + 0.5, y - 2 + BlockTypeUtil.centralTopLimit(state), z + 0.5)); +// setPosition(Vector3.at(x + 0.5, y - 2 + 1, z + 0.5)); } return; @@ -135,10 +136,10 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { int z = searchPos.getBlockZ(); while (y >= 0) { - final Vector pos = new Vector(x, y, z); - final BlockStateHolder id = world.getBlock(pos); + final BlockVector3 pos = BlockVector3.at(x, y, z); + final BlockState id = world.getBlock(pos); if (id.getBlockType().getMaterial().isMovementBlocker()) { - setPosition(new Vector(x + 0.5, y + BlockType.centralTopLimit(id), z + 0.5)); + setPosition(Vector3.at(x + 0.5, y + + BlockTypeUtil.centralTopLimit(id), z + 0.5)); return; } @@ -162,7 +163,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { int maxY = world.getMaxY(); if (y >= maxY) return false; - BlockMaterial initialMaterial = world.getBlockType(new Vector(x, y, z)).getMaterial(); + BlockMaterial initialMaterial = world.getBlockType(BlockVector3.at(x, y, z)).getMaterial(); boolean lastState = initialMaterial.isMovementBlocker() && initialMaterial.isFullCube(); @@ -172,22 +173,22 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { for (int level = y + 1; level <= maxY + 2; level++) { BlockState state; if (level >= maxY) state = BlockTypes.VOID_AIR.getDefaultState(); - else state = world.getBlock(new Vector(x, level, z)); - BlockTypes type = state.getBlockType(); + else state = world.getBlock(BlockVector3.at(x, level, z)); + BlockType type = state.getBlockType(); BlockMaterial material = type.getMaterial(); if (!material.isFullCube() || !material.isMovementBlocker()) { if (!lastState) { - lastState = BlockType.centralBottomLimit(state) != 1; + lastState = BlockTypeUtil.centralBottomLimit(state) != 1; continue; } if (freeStart == -1) { - freeStart = level + BlockType.centralTopLimit(state); + freeStart = level + BlockTypeUtil.centralTopLimit(state); } else { - double bottomLimit = BlockType.centralBottomLimit(state); + double bottomLimit = BlockTypeUtil.centralBottomLimit(state); double space = level + bottomLimit - freeStart; if (space >= height) { - setPosition(new Vector(x + 0.5, freeStart, z + 0.5)); + setPosition(Vector3.at(x + 0.5, freeStart, z + 0.5)); return true; } // Not enough room, reset the free position @@ -211,7 +212,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { final int z = pos.getBlockZ(); final Extent world = pos.getExtent(); - BlockMaterial initialMaterial = world.getBlockType(new Vector(x, y, z)).getMaterial(); + BlockMaterial initialMaterial = world.getBlockType(BlockVector3.at(x, y, z)).getMaterial(); boolean lastState = initialMaterial.isMovementBlocker() && initialMaterial.isFullCube(); @@ -224,23 +225,23 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { for (int level = y + 1; level > 0; level--) { BlockState state; if (level >= maxY) state = BlockTypes.VOID_AIR.getDefaultState(); - else state = world.getBlock(new Vector(x, level, z)); - BlockTypes type = state.getBlockType(); + else state = world.getBlock(BlockVector3.at(x, level, z)); + BlockType type = state.getBlockType(); BlockMaterial material = type.getMaterial(); if (!material.isFullCube() || !material.isMovementBlocker()) { if (!lastState) { - lastState = BlockType.centralTopLimit(state) != 0; + lastState = BlockTypeUtil.centralTopLimit(state) != 0; continue; } if (freeEnd == -1) { - freeEnd = level + BlockType.centralBottomLimit(state); + freeEnd = level + BlockTypeUtil.centralBottomLimit(state); } else { - double topLimit = BlockType.centralTopLimit(state); + double topLimit = BlockTypeUtil.centralTopLimit(state); double freeStart = level + topLimit; double space = freeEnd - freeStart; if (space >= height) { - setPosition(new Vector(x + 0.5, freeStart, z + 0.5)); + setPosition(Vector3.at(x + 0.5, freeStart, z + 0.5)); return true; } // Not enough room, reset the free position @@ -271,13 +272,13 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { Extent world = getLocation().getExtent(); // No free space above - if (!world.getBlock(new Vector(x, y, z)).getBlockType().getMaterial().isAir()) { + if (!world.getBlock(BlockVector3.at(x, y, z)).getBlockType().getMaterial().isAir()) { return false; } while (y <= world.getMaximumPoint().getY()) { // Found a ceiling! - if (world.getBlock(new Vector(x, y, z)).getBlockType().getMaterial().isMovementBlocker()) { + if (world.getBlock(BlockVector3.at(x, y, z)).getBlockType().getMaterial().isMovementBlocker()) { int platformY = Math.max(initialY, y - 3 - clearance); floatAt(x, platformY + 1, z, alwaysGlass); return true; @@ -305,7 +306,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { final Extent world = getLocation().getExtent(); while (y <= world.getMaximumPoint().getY() + 2) { - if (world.getBlock(new Vector(x, y, z)).getBlockType().getMaterial().isMovementBlocker()) { + if (world.getBlock(BlockVector3.at(x, y, z)).getBlockType().getMaterial().isMovementBlocker()) { break; // Hit something } else if (y > maxY + 1) { break; @@ -322,26 +323,25 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { @Override public void floatAt(int x, int y, int z, boolean alwaysGlass) { - Vector spot = new Vector(x, y - 1, z); - if (!getLocation().getExtent().getBlock(spot).getBlockType().getMaterial().isMovementBlocker()) { - try { - getLocation().getExtent().setBlock(new Vector(x, y - 1, z), BlockTypes.GLASS.getDefaultState()); - } catch (WorldEditException e) { - e.printStackTrace(); + try { + BlockVector3 spot = BlockVector3.at(x, y - 1, z); + if (!getLocation().getExtent().getBlock(spot).getBlockType().getMaterial().isMovementBlocker()) { + getLocation().getExtent().setBlock(spot, BlockTypes.GLASS.getDefaultState()); } + }catch (WorldEditException e) { + e.printStackTrace(); } - setPosition(new Vector(x + 0.5, y, z + 0.5)); + setPosition(Vector3.at(x + 0.5, y, z + 0.5)); } @Override public Location getBlockIn() { - Location loc = getLocation(); - return new Location(loc.getExtent(), loc.toBlockVector(), loc.getDirection()); + return getLocation().setPosition(getLocation().floor()); } @Override public Location getBlockOn() { - return getLocation().setY(getLocation().getY() - 1); + return getLocation().setPosition(getLocation().setY(getLocation().getY() - 1).floor()); } @Override @@ -368,17 +368,17 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { } @Override - public PlayerDirection getCardinalDirection() { + public Direction getCardinalDirection() { return getCardinalDirection(0); } @Override - public PlayerDirection getCardinalDirection(int yawOffset) { + public Direction getCardinalDirection(int yawOffset) { if (getLocation().getPitch() > 67.5) { - return PlayerDirection.DOWN; + return Direction.DOWN; } if (getLocation().getPitch() < -67.5) { - return PlayerDirection.UP; + return Direction.UP; } // From hey0's code @@ -390,12 +390,12 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { } @Override - public BlockState getBlockInHand(HandSide handSide) throws WorldEditException { + public BaseBlock getBlockInHand(HandSide handSide) throws WorldEditException { final ItemType typeId = getItemInHand(handSide).getType(); if (typeId.hasBlockType()) { - return typeId.getBlockType().getDefaultState(); + return typeId.getBlockType().getDefaultState().toBaseBlock(); } else { - throw new NotABlockException(); + return BlockTypes.AIR.getDefaultState().toBaseBlock(); } } @@ -416,7 +416,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { boolean inFree = false; while ((block = hitBlox.getNextBlock()) != null) { - boolean free = !world.getBlock(block.toVector()).getBlockType().getMaterial().isMovementBlocker(); + boolean free = !world.getBlock(block.toBlockPoint()).getBlockType().getMaterial().isMovementBlocker(); if (firstBlock) { firstBlock = false; @@ -450,7 +450,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { } @Override - public void setPosition(Vector pos) { + public void setPosition(Vector3 pos) { setPosition(pos, getLocation().getPitch(), getLocation().getYaw()); } @@ -522,4 +522,8 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable { return false; } -} \ No newline at end of file + @Override + public > void sendFakeBlock(BlockVector3 pos, B block) { + + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/Actor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/Actor.java index 43f665423..cf64b5974 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/Actor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/Actor.java @@ -38,6 +38,15 @@ public interface Actor extends Identifiable, SessionOwner, Subject { */ String getName(); + /** + * Gets the display name of the actor. This can be a nickname, and is not guaranteed to be unique. + * + * @return The display name + */ + default String getDisplayName() { + return getName(); + } + /** * Print a message. * diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java index f0b547cc2..8ecbef23c 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/CommandManager.java @@ -359,7 +359,7 @@ public final class CommandManager { return split; } - public void handleCommandOnCurrentThread(final CommandEvent event) { + public void handleCommandOnCurrentThread(CommandEvent event) { Actor actor = platformManager.createProxyActor(event.getActor()); final String args = event.getArguments(); final String[] split = commandDetection(args.split(" ")); @@ -408,12 +408,8 @@ public final class CommandManager { final Actor finalActor = actor; locals.put("arguments", args); - ThrowableSupplier task = new ThrowableSupplier() { - @Override - public Object get() throws Throwable { - return dispatcher.call(Joiner.on(" ").join(split), locals, new String[0]); - } - }; + ThrowableSupplier task = + () -> dispatcher.call(Joiner.on(" ").join(split), locals, new String[0]); handleCommandTask(task, locals, actor, session, failedPermissions, fp); } @@ -517,29 +513,21 @@ public final class CommandManager { String args = event.getArguments(); CommandEvent finalEvent = new CommandEvent(actor, args); final FawePlayer fp = FawePlayer.wrap(actor); - TaskManager.IMP.taskNow(new Runnable() { - @Override - public void run() { - int space0 = args.indexOf(' '); - String arg0 = space0 == -1 ? args : args.substring(0, space0); - CommandMapping cmd = dispatcher.get(arg0); - if (cmd != null && cmd.getCallable() instanceof AParametricCallable) { - Command info = ((AParametricCallable) cmd.getCallable()).getDefinition(); - if (!info.queued()) { - handleCommandOnCurrentThread(finalEvent); - return; - } + TaskManager.IMP.taskNow(() -> { + int space0 = args.indexOf(' '); + String arg0 = space0 == -1 ? args : args.substring(0, space0); + CommandMapping cmd = dispatcher.get(arg0); + if (cmd != null && cmd.getCallable() instanceof AParametricCallable) { + Command info = ((AParametricCallable) cmd.getCallable()).getDefinition(); + if (!info.queued()) { + handleCommandOnCurrentThread(finalEvent); + return; } - if (!fp.runAction(new Runnable() { - @Override - public void run() { - handleCommandOnCurrentThread(finalEvent); - } - }, false, true)) { - BBC.WORLDEDIT_COMMAND_LIMIT.send(fp); - } - finalEvent.setCancelled(true); } + if (!fp.runAction(() -> handleCommandOnCurrentThread(finalEvent), false, true)) { + BBC.WORLDEDIT_COMMAND_LIMIT.send(fp); + } + finalEvent.setCancelled(true); }, Fawe.isMainThread()); } @@ -548,6 +536,7 @@ public final class CommandManager { try { CommandLocals locals = new CommandLocals(); locals.put(Actor.class, event.getActor()); + locals.put("arguments", event.getArguments()); event.setSuggestions(dispatcher.getSuggestions(event.getArguments(), locals)); } catch (CommandException e) { event.getActor().printError(e.getMessage()); @@ -568,4 +557,4 @@ public final class CommandManager { } -} \ No newline at end of file +} 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 53bbe3bb3..38f4654cd 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 @@ -28,12 +28,21 @@ import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.wrappers.LocationMaskedPlayerWrapper; import com.boydti.fawe.wrappers.PlayerWrapper; import com.boydti.fawe.wrappers.WorldWrapper; -import com.sk89q.worldedit.*; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.tool.*; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.LocalConfiguration; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.command.tool.BlockTool; +import com.sk89q.worldedit.command.tool.DoubleActionBlockTool; +import com.sk89q.worldedit.command.tool.DoubleActionTraceTool; +import com.sk89q.worldedit.command.tool.Tool; +import com.sk89q.worldedit.command.tool.TraceTool; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.event.platform.*; import com.sk89q.worldedit.extension.platform.permission.ActorSelectorLimits; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.util.HandSide; @@ -62,8 +71,8 @@ public class PlatformManager { private final WorldEdit worldEdit; private final CommandManager commandManager; - private final List platforms = new ArrayList(); - private final Map preferences = new EnumMap(Capability.class); + private final List platforms = new ArrayList<>(); + private final Map preferences = new EnumMap<>(Capability.class); private @Nullable String firstSeenVersion; private final AtomicBoolean initialized = new AtomicBoolean(); private final AtomicBoolean configured = new AtomicBoolean(); @@ -159,8 +168,13 @@ public class PlatformManager { if (platform != null) { return platform; } else { - if (preferences.isEmpty() && !platforms.isEmpty()) { - return platforms.get(0); // Use the first available if preferences have not been decided yet. + if (preferences.isEmpty()) { + // Use the first available if preferences have not been decided yet. + if (platforms.isEmpty()) { + // No platforms registered, this is being called too early! + throw new NoCapablePlatformException("No platforms have been registered yet! Please wait until WorldEdit is initialized."); + } + return platforms.get(0); } throw new NoCapablePlatformException("No platform was found supporting " + capability.name()); } @@ -214,7 +228,7 @@ public class PlatformManager { * @return a list of platforms */ public synchronized List getPlatforms() { - return new ArrayList(platforms); + return new ArrayList<>(platforms); } /** @@ -294,7 +308,7 @@ public class PlatformManager { final Actor actor = createProxyActor(event.getCause()); try { final Location location = event.getLocation(); - final Vector vector = location.toVector(); + final BlockVector3 vector = location.toBlockPoint(); // At this time, only handle interaction from players if (actor instanceof Player) { @@ -308,7 +322,7 @@ public class PlatformManager { } if (event.getType() == Interaction.HIT) { - if (session.isToolControlEnabled() && playerActor.getItemInHand(HandSide.MAIN_HAND).getType().equals(getConfiguration().wandItem)) { + if (session.isToolControlEnabled() && playerActor.getItemInHand(HandSide.MAIN_HAND).getType().getId().equals(getConfiguration().wandItem)) { FawePlayer fp = FawePlayer.wrap(playerActor); if (!actor.hasPermission("worldedit.selection.pos")) { return; @@ -318,7 +332,7 @@ public class PlatformManager { fp.runAction(new Runnable() { @Override public void run() { - if (selector.selectPrimary(location.toVector(), ActorSelectorLimits.forActor(player))) { + if (selector.selectPrimary(vector, ActorSelectorLimits.forActor(player))) { selector.explainPrimarySelection(actor, session, vector); } } @@ -342,6 +356,7 @@ public class PlatformManager { return; } } +//<<<<<<< HEAD final Tool tool = session.getTool(playerActor); if (tool != null && tool instanceof DoubleActionBlockTool) { if (tool.canUse(playerActor)) { @@ -356,9 +371,17 @@ public class PlatformManager { event.setCancelled(true); return; } +//======= +// +// RegionSelector selector = session.getRegionSelector(player.getWorld()); +// +// BlockVector3 blockPoint = vector.toBlockPoint(); +// if (selector.selectPrimary(blockPoint, ActorSelectorLimits.forActor(player))) { +// selector.explainPrimarySelection(actor, session, blockPoint); +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner } } else if (event.getType() == Interaction.OPEN) { - if (session.isToolControlEnabled() && playerActor.getItemInHand(HandSide.MAIN_HAND).getType().equals(getConfiguration().wandItem)) { + if (session.isToolControlEnabled() && playerActor.getItemInHand(HandSide.MAIN_HAND).getType().getId().equals(getConfiguration().wandItem)) { FawePlayer fp = FawePlayer.wrap(playerActor); if (!actor.hasPermission("worldedit.selection.pos")) { return; @@ -379,6 +402,7 @@ public class PlatformManager { return; } +//<<<<<<< HEAD final Tool tool = session.getTool(playerActor); if (tool != null && tool instanceof BlockTool) { if (tool.canUse(playerActor)) { @@ -399,6 +423,23 @@ public class PlatformManager { return; } } +//======= +// RegionSelector selector = session.getRegionSelector(player.getWorld()); +// BlockVector3 blockPoint = vector.toBlockPoint(); +// if (selector.selectSecondary(blockPoint, ActorSelectorLimits.forActor(player))) { +// selector.explainSecondarySelection(actor, session, blockPoint); +// } +// +// event.setCancelled(true); +// return; +// } +// +// Tool tool = session.getTool(player.getItemInHand(HandSide.MAIN_HAND).getType()); +// if (tool instanceof BlockTool) { +// if (tool.canUse(player)) { +// ((BlockTool) tool).actPrimary(queryCapability(Capability.WORLD_EDITING), getConfiguration(), player, session, location); +// event.setCancelled(true); +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner } } } @@ -523,4 +564,4 @@ public class PlatformManager { -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlayerProxy.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlayerProxy.java index dfc18b3ec..61aebf909 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlayerProxy.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlayerProxy.java @@ -19,15 +19,19 @@ package com.sk89q.worldedit.extension.platform; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockStateHolder; + +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.internal.cui.CUIEvent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.session.SessionKey; import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.util.Location; @@ -46,7 +50,7 @@ public class PlayerProxy extends AbstractPlayerActor { private final Actor permActor; private final Actor cuiActor; private final World world; - private Vector offset = Vector.ZERO; + private Vector3 offset = Vector3.ZERO; public PlayerProxy(Player basePlayer, Actor permActor, Actor cuiActor, World world) { checkNotNull(basePlayer); @@ -59,13 +63,13 @@ public class PlayerProxy extends AbstractPlayerActor { this.world = world; } - public void setOffset(Vector position) { + public void setOffset(Vector3 position) { this.offset = position; } @Override - public BlockState getBlockInHand(HandSide handSide) throws WorldEditException { + public BaseBlock getBlockInHand(HandSide handSide) throws WorldEditException { return basePlayer.getBlockInHand(handSide); } @@ -94,6 +98,11 @@ public class PlayerProxy extends AbstractPlayerActor { return basePlayer.getName(); } + @Override + public String getDisplayName() { + return basePlayer.getDisplayName(); + } + @Override public BaseEntity getState() { throw new UnsupportedOperationException("Can't withPropertyId() on a player"); @@ -102,11 +111,16 @@ public class PlayerProxy extends AbstractPlayerActor { @Override public Location getLocation() { Location loc = this.basePlayer.getLocation(); - return new Location(loc.getExtent(), loc.toVector().add(offset), loc.getDirection()); + return new Location(loc.getExtent(), loc.add(offset), loc.getDirection()); } @Override - public void setPosition(Vector pos, float pitch, float yaw) { + public boolean setLocation(Location location) { + return basePlayer.setLocation(location); + } + + @Override + public void setPosition(Vector3 pos, float pitch, float yaw) { basePlayer.setPosition(pos, pitch, yaw); } @@ -170,4 +184,10 @@ public class PlayerProxy extends AbstractPlayerActor { public void setGameMode(GameMode gameMode) { basePlayer.setGameMode(gameMode); } -} \ No newline at end of file + + @Override + public > void sendFakeBlock(BlockVector3 pos, B block) { + basePlayer.sendFakeBlock(pos, block); + } +} + 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 43ed8caed..1aa31fdd8 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 @@ -22,39 +22,36 @@ package com.sk89q.worldedit.extent; import com.boydti.fawe.jnbt.anvil.generator.GenBase; import com.boydti.fawe.jnbt.anvil.generator.Resource; import com.boydti.fawe.object.extent.LightingExtent; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.blocks.BlockMaterial; +import static com.google.common.base.Preconditions.checkNotNull; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.OperationQueue; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.registry.BundledBlockData; import java.util.List; import javax.annotation.Nullable; - -import static com.google.common.base.Preconditions.checkNotNull; - /** * A base class for {@link Extent}s that merely passes extents onto another. */ public class AbstractDelegateExtent implements LightingExtent { private transient final Extent extent; - private MutableBlockVector mutable = new MutableBlockVector(0, 0, 0); +// private MutableBlockVector3 mutable = new MutableBlockVector3(0, 0, 0); /** * Create a new instance. @@ -79,12 +76,12 @@ public class AbstractDelegateExtent implements LightingExtent { } @Override - public BlockType getBlockType(Vector position) { + public BlockType getBlockType(BlockVector3 position) { return extent.getBlockType(position); } @Override - public BlockState getFullBlock(Vector position) { + public BaseBlock getFullBlock(BlockVector3 position) { return extent.getFullBlock(position); } @@ -127,36 +124,35 @@ public class AbstractDelegateExtent implements LightingExtent { return extent; } - @Override - public BlockState getBlock(Vector position) { - return extent.getLazyBlock(position); - } - @Override public BlockState getLazyBlock(int x, int y, int z) { - mutable.mutX(x); - mutable.mutY(y); - mutable.mutZ(z); - return extent.getLazyBlock(mutable); +// mutable.mutX(x); +// mutable.mutY(y); +// mutable.mutZ(z); + return extent.getLazyBlock(BlockVector3.at(x, y, z)); } @Override - public BlockState getLazyBlock(Vector position) { + public BlockState getLazyBlock(BlockVector3 position) { return extent.getLazyBlock(position); } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { - mutable.mutX(x); - mutable.mutY(y); - mutable.mutZ(z); - return setBlock(mutable, block); + public > boolean setBlock(int x, int y, int z, T block) throws WorldEditException { +// mutable.mutX(x); +// mutable.mutY(y); +// mutable.mutZ(z); + return setBlock(BlockVector3.at(x, y, z), block); } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, T block) throws WorldEditException { return extent.setBlock(location, block); } + + public BlockState getBlock(BlockVector3 position) { + return extent.getBlock(position); + } @Override @Nullable @@ -175,12 +171,12 @@ public class AbstractDelegateExtent implements LightingExtent { } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return extent.getBiome(position); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return extent.setBiome(position, biome); } @@ -195,12 +191,12 @@ public class AbstractDelegateExtent implements LightingExtent { } @Override - public Vector getMinimumPoint() { + public BlockVector3 getMinimumPoint() { return extent.getMinimumPoint(); } @Override - public Vector getMaximumPoint() { + public BlockVector3 getMaximumPoint() { return extent.getMaximumPoint(); } @@ -254,7 +250,7 @@ public class AbstractDelegateExtent implements LightingExtent { } @Override - public boolean contains(Vector pt) { + public boolean contains(BlockVector3 pt) { return extent.contains(pt); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/ChangeSetExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/ChangeSetExtent.java index 602eff780..a53638f3b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/ChangeSetExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/ChangeSetExtent.java @@ -19,20 +19,29 @@ package com.sk89q.worldedit.extent; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockState; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; +import com.sk89q.worldedit.history.change.BiomeChange; import com.sk89q.worldedit.history.change.BlockChange; import com.sk89q.worldedit.history.change.EntityCreate; import com.sk89q.worldedit.history.change.EntityRemove; import com.sk89q.worldedit.history.changeset.ChangeSet; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import javax.annotation.Nullable; +import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockStateHolder; import java.util.ArrayList; import java.util.List; @@ -59,12 +68,19 @@ public class ChangeSetExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { BlockStateHolder previous = getBlock(location); - changeSet.add(new BlockChange(location.toBlockVector(), previous, block)); + changeSet.add(new BlockChange(location, previous, block)); return super.setBlock(location, block); } + @Override + public boolean setBiome(BlockVector2 position, BaseBiome biome) { + BaseBiome previous = getBiome(position); + changeSet.add(new BiomeChange(position, previous, new BaseBiome(biome))); + return super.setBiome(position, biome); + } + @Nullable @Override public Entity createEntity(Location location, BaseEntity state) { @@ -110,6 +126,12 @@ public class ChangeSetExtent extends AbstractDelegateExtent { return entity.getLocation(); } + @Override + public boolean setLocation(Location location) { + // TODO Add a changeset for this. + return entity.setLocation(location); + } + @Override public Extent getExtent() { return entity.getExtent(); 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 ae697294b..cca0e4075 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 @@ -23,7 +23,7 @@ import com.boydti.fawe.jnbt.anvil.generator.*; import com.boydti.fawe.object.PseudoRandom; import com.boydti.fawe.object.clipboard.WorldCopyClipboard; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.util.Countable; @@ -35,8 +35,11 @@ import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.registry.state.PropertyGroup; import com.sk89q.worldedit.session.ClipboardHolder; -import com.sk89q.worldedit.util.Location; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.Region; +import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockState; @@ -63,7 +66,7 @@ public interface Extent extends InputExtent, OutputExtent { * * @return the minimum point */ - Vector getMinimumPoint(); + BlockVector3 getMinimumPoint(); /** * Get the maximum point in the extent. @@ -73,7 +76,7 @@ public interface Extent extends InputExtent, OutputExtent { * * @return the maximum point */ - Vector getMaximumPoint(); + BlockVector3 getMaximumPoint(); /** * Get a list of all entities within the given region. @@ -114,25 +117,25 @@ public interface Extent extends InputExtent, OutputExtent { } @Override - default BlockState getBlock(Vector position) { - return getFullBlock(position); + default BlockState getBlock(BlockVector3 position) { + return getFullBlock(position).toImmutableState(); } @Override - default BlockState getLazyBlock(Vector position) { - return getFullBlock(position); + default BlockState getLazyBlock(BlockVector3 position) { + return getFullBlock(position).toImmutableState(); } default BlockState getLazyBlock(int x, int y, int z) { - return getLazyBlock(MutableBlockVector.get(x, y, z)); + return getLazyBlock(BlockVector3.at(x, y, z)); } - default boolean setBlock(int x, int y, int z, BlockStateHolder state) throws WorldEditException { - return setBlock(MutableBlockVector.get(x, y, z), state); + default > boolean setBlock(int x, int y, int z, T state) throws WorldEditException { + return setBlock(BlockVector3.at(x, y, z), state); } default boolean setBiome(int x, int y, int z, BaseBiome biome) { - return setBiome(MutableBlockVector2D.get(x, z), biome); + return setBiome(BlockVector2.at(x, z), biome); } default int getHighestTerrainBlock(final int x, final int z, int minY, int maxY) { @@ -252,7 +255,7 @@ public interface Extent extends InputExtent, OutputExtent { } default void generate(Region region, GenBase gen) throws WorldEditException { - for (Vector2D chunkPos : region.getChunks()) { + for (BlockVector2 chunkPos : region.getChunks()) { gen.generate(chunkPos, this); } } @@ -263,7 +266,7 @@ public interface Extent extends InputExtent, OutputExtent { default void spawnResource(Region region, Resource gen, int rarity, int frequency) throws WorldEditException { ThreadLocalRandom random = ThreadLocalRandom.current(); - for (Vector2D chunkPos : region.getChunks()) { + for (BlockVector2 chunkPos : region.getChunks()) { for (int i = 0; i < frequency; i++) { if (random.nextInt(100) > rarity) { continue; @@ -275,9 +278,9 @@ public interface Extent extends InputExtent, OutputExtent { } } - default boolean contains(Vector pt) { - Vector min = getMinimumPoint(); - Vector max = getMaximumPoint(); + default boolean contains(BlockVector3 pt) { + BlockVector3 min = getMinimumPoint(); + BlockVector3 max = getMaximumPoint(); return (pt.containedWithin(min, max)); } @@ -309,7 +312,7 @@ public interface Extent extends InputExtent, OutputExtent { default List> getBlockDistribution(final Region region) { int[] counter = new int[BlockTypes.size()]; - for (final Vector pt : region) { + for (final BlockVector3 pt : region) { BlockType type = getBlockType(pt); counter[type.getInternalId()]++; } @@ -333,7 +336,7 @@ public interface Extent extends InputExtent, OutputExtent { default List> getBlockDistributionWithData(final Region region) { int[][] counter = new int[BlockTypes.size()][]; - for (final Vector pt : region) { + for (final BlockVector3 pt : region) { BlockStateHolder blk = this.getBlock(pt); BlockType type = blk.getBlockType(); int[] stateCounter = counter[type.getInternalId()]; 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 2a2c97a0c..34a0994fa 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 @@ -19,14 +19,10 @@ package com.sk89q.worldedit.extent; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.blocks.LazyBlock; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockType; @@ -49,9 +45,9 @@ public interface InputExtent { * @param position position of the block * @return the block */ - BlockState getBlock(Vector position); + BlockState getBlock(BlockVector3 position); - default BlockType getBlockType(Vector position) { + default BlockType getBlockType(BlockVector3 position) { return getBlock(position).getBlockType(); } @@ -76,7 +72,7 @@ public interface InputExtent { * @param position position of the block * @return the block */ - BlockState getLazyBlock(Vector position); + BlockState getLazyBlock(BlockVector3 position); /** * Get a immutable snapshot of the block at the given location. @@ -84,7 +80,7 @@ public interface InputExtent { * @param position position of the block * @return the block */ - BlockState getFullBlock(Vector position); + BaseBlock getFullBlock(BlockVector3 position); /** * Get the biome at the given location. @@ -95,6 +91,6 @@ public interface InputExtent { * @param position the (x, z) location to check the biome at * @return the biome at the location */ - BaseBiome getBiome(Vector2D position); + BaseBiome getBiome(BlockVector2 position); } 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 a3d745c47..787073d21 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 @@ -19,14 +19,15 @@ package com.sk89q.worldedit.extent; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -38,7 +39,7 @@ import static com.google.common.base.Preconditions.checkNotNull; public class MaskingExtent extends AbstractDelegateExtent { private Mask mask; - private MutableBlockVector mutable = new MutableBlockVector(); +// private MutableBlockVector3 mutable = new MutableBlockVector3(); /** * Create a new instance. @@ -72,18 +73,18 @@ public class MaskingExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { return mask.test(location) && super.setBlock(location, block); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { - return mask.test(mutable.setComponents(position.getBlockX(), 0, position.getBlockZ())) && super.setBiome(position, biome); + public boolean setBiome(BlockVector2 position, BaseBiome biome) { + return mask.test(position.toBlockVector3()) && super.setBiome(position, biome); } @Override public boolean setBiome(int x, int y, int z, BaseBiome biome) { - return mask.test(mutable.setComponents(x, y, z)) && super.setBiome(x, y, z, biome); + return mask.test(BlockVector3.at(x, y, z)) && super.setBiome(x, y, z, biome); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/NullExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/NullExtent.java index 538bde2a2..074bf9dff 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/NullExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/NullExtent.java @@ -19,22 +19,29 @@ package com.sk89q.worldedit.extent; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.LazyBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockTypes; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.entity.BaseEntity; +import com.sk89q.worldedit.entity.Entity; +import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockTypes; import javax.annotation.Nullable; import java.util.Collections; @@ -46,18 +53,18 @@ import java.util.List; */ public class NullExtent implements Extent { - private final Vector nullPoint = new Vector(0, 0, 0); + private final BlockVector3 nullPoint = BlockVector3.at(0, 0, 0); public static final NullExtent INSTANCE = new NullExtent(); @Override - public Vector getMinimumPoint() { - return nullPoint; + public BlockVector3 getMinimumPoint() { + return BlockVector3.ZERO; } @Override - public Vector getMaximumPoint() { - return nullPoint; + public BlockVector3 getMaximumPoint() { + return BlockVector3.ZERO; } @Override @@ -77,33 +84,38 @@ public class NullExtent implements Extent { } @Override - public BlockState getBlock(Vector position) { + public BlockState getBlock(BlockVector3 position) { + return BlockTypes.AIR.getDefaultState(); + } + + public BlockState getLazyBlock(BlockVector3 position) { return BlockTypes.AIR.getDefaultState(); } @Override - public BlockState getLazyBlock(Vector position) { - return BlockTypes.AIR.getDefaultState(); - } - @Override - public BlockState getFullBlock(Vector position) { - return new BaseBlock(getBlock(position)); + public BaseBlock getFullBlock(BlockVector3 position) { + return getBlock(position).toBaseBlock(); } @Nullable @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return null; } @Override - public boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 position, B block) throws WorldEditException { + return false; + } + + @Override + public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { return false; } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return false; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/OutputExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/OutputExtent.java index 36747fd97..18f7f1675 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/OutputExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/OutputExtent.java @@ -19,10 +19,10 @@ package com.sk89q.worldedit.extent; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -50,7 +50,7 @@ public interface OutputExtent { * @return true if the block was successfully set (return value may not be accurate) * @throws WorldEditException thrown on an error */ - boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException; + > boolean setBlock(BlockVector3 position, T block) throws WorldEditException; /** * Set the biome. @@ -59,7 +59,7 @@ public interface OutputExtent { * @param biome the biome to set to * @return true if the biome was successfully set (return value may not be accurate) */ - boolean setBiome(Vector2D position, BaseBiome biome); + boolean setBiome(BlockVector2 position, BaseBiome biome); /** * Return an {@link Operation} that should be called to tie up loose ends diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/buffer/ForgetfulExtentBuffer.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/buffer/ForgetfulExtentBuffer.java index 3905f4ccb..0aa410916 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/buffer/ForgetfulExtentBuffer.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/buffer/ForgetfulExtentBuffer.java @@ -21,17 +21,17 @@ package com.sk89q.worldedit.extent.buffer; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Masks; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.AbstractRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionOperationException; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; @@ -44,19 +44,19 @@ import java.util.Map; * actual application of the changes. * *

This buffer will not attempt to return results from the buffer when - * accessor methods (such as {@link #getBlock(Vector)}) are called.

+ * accessor methods (such as {@link #getBlock(BlockVector3)}) are called.

*/ public class ForgetfulExtentBuffer extends AbstractDelegateExtent implements Pattern { - private final Map buffer = new LinkedHashMap<>(); + private final Map buffer = new LinkedHashMap<>(); private final Mask mask; - private Vector min = null; - private Vector max = null; + private BlockVector3 min = null; + private BlockVector3 max = null; /** * Create a new extent buffer that will buffer every change. * - * @param delegate the delegate extent for {@link Extent#getBlock(Vector)}, etc. calls + * @param delegate the delegate extent for {@link Extent#getBlock(BlockVector3)}, etc. calls */ public ForgetfulExtentBuffer(Extent delegate) { this(delegate, Masks.alwaysTrue()); @@ -66,7 +66,7 @@ public class ForgetfulExtentBuffer extends AbstractDelegateExtent implements Pat * Create a new extent buffer that will buffer changes that meet the criteria * of the given mask. * - * @param delegate the delegate extent for {@link Extent#getBlock(Vector)}, etc. calls + * @param delegate the delegate extent for {@link Extent#getBlock(BlockVector3)}, etc. calls * @param mask the mask */ public ForgetfulExtentBuffer(Extent delegate, Mask mask) { @@ -77,24 +77,23 @@ public class ForgetfulExtentBuffer extends AbstractDelegateExtent implements Pat } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { // Update minimum if (min == null) { min = location; } else { - min = Vector.getMinimum(min, location); + min = min.getMinimum(location); } // Update maximum if (max == null) { max = location; } else { - max = Vector.getMaximum(max, location); + max = max.getMaximum(location); } - BlockVector blockVector = location.toBlockVector(); - if (mask.test(blockVector)) { - buffer.put(blockVector, block); + if (mask.test(location)) { + buffer.put(location, block.toBaseBlock()); return true; } else { return getExtent().setBlock(location, block); @@ -102,12 +101,12 @@ public class ForgetfulExtentBuffer extends AbstractDelegateExtent implements Pat } @Override - public BlockStateHolder apply(Vector pos) { - BlockStateHolder block = buffer.get(pos.toBlockVector()); + public BaseBlock apply(BlockVector3 pos) { + BaseBlock block = buffer.get(pos); if (block != null) { return block; } else { - return BlockTypes.AIR.getDefaultState(); + return BlockTypes.AIR.getDefaultState().toBaseBlock(); } } @@ -119,32 +118,32 @@ public class ForgetfulExtentBuffer extends AbstractDelegateExtent implements Pat public Region asRegion() { return new AbstractRegion(null) { @Override - public Vector getMinimumPoint() { - return min != null ? min : new Vector(); + public BlockVector3 getMinimumPoint() { + return min != null ? min : BlockVector3.ZERO; } @Override - public Vector getMaximumPoint() { - return max != null ? max : new Vector(); + public BlockVector3 getMaximumPoint() { + return max != null ? max : BlockVector3.ZERO; } @Override - public void expand(Vector... changes) throws RegionOperationException { + public void expand(BlockVector3... changes) throws RegionOperationException { throw new UnsupportedOperationException("Cannot change the size of this region"); } @Override - public void contract(Vector... changes) throws RegionOperationException { + public void contract(BlockVector3... changes) throws RegionOperationException { throw new UnsupportedOperationException("Cannot change the size of this region"); } @Override - public boolean contains(Vector position) { - return buffer.containsKey(position.toBlockVector()); + public boolean contains(BlockVector3 position) { + return buffer.containsKey(position); } @Override - public Iterator iterator() { + public Iterator iterator() { return buffer.keySet().iterator(); } }; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/cache/LastAccessExtentCache.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/cache/LastAccessExtentCache.java index b4c4e267a..d6da35e10 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/cache/LastAccessExtentCache.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/cache/LastAccessExtentCache.java @@ -19,19 +19,22 @@ package com.sk89q.worldedit.extent.cache; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockStateHolder; /** * Returns the same cached {@link BlockState} for repeated calls to - * {@link #getBlock(Vector)} with the same position. + * {@link #getBlock(BlockVector3)} with the same position. */ public class LastAccessExtentCache extends AbstractDelegateExtent { - private CachedBlock lastBlock; + private CachedBlock lastBlock; + private CachedBlock lastFullBlock; /** * Create a new instance. @@ -43,23 +46,49 @@ public class LastAccessExtentCache extends AbstractDelegateExtent { } @Override - public BlockState getBlock(Vector position) { - BlockVector blockVector = position.toBlockVector(); - CachedBlock lastBlock = this.lastBlock; - if (lastBlock != null && lastBlock.position.equals(blockVector)) { + public BlockState getBlock(BlockVector3 position) { + CachedBlock lastBlock = this.lastBlock; + if (lastBlock != null && lastBlock.position.equals(position)) { return lastBlock.block; } else { BlockState block = super.getBlock(position); - this.lastBlock = new CachedBlock(blockVector, block); + this.lastBlock = new CachedBlock<>(position, block); return block; } } - private static class CachedBlock { - private final BlockVector position; - private final BlockState block; + @Override + public BaseBlock getFullBlock(BlockVector3 position) { + CachedBlock lastFullBlock = this.lastFullBlock; + if (lastFullBlock != null && lastFullBlock.position.equals(position)) { + return lastFullBlock.block; + } else { + BaseBlock block = super.getFullBlock(position); + this.lastFullBlock = new CachedBlock<>(position, block); + return block; + } + } - private CachedBlock(BlockVector position, BlockState block) { + @Override + public > boolean setBlock(BlockVector3 location, T block) throws WorldEditException { + if (super.setBlock(location, block)) { + if (lastFullBlock != null && lastFullBlock.position.equals(location)) { + this.lastFullBlock = new CachedBlock<>(location, block.toBaseBlock()); + } + if (lastBlock != null && lastBlock.position.equals(location)) { + this.lastBlock = new CachedBlock<>(location, block.toImmutableState()); + } + + return true; + } + return false; + } + + private static class CachedBlock> { + private final BlockVector3 position; + private final B block; + + private CachedBlock(BlockVector3 position, B block) { this.position = position; this.block = block; } 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 f4031bc5e..3c1ffa4f5 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 @@ -22,24 +22,27 @@ package com.sk89q.worldedit.extent.clipboard; import com.boydti.fawe.config.Settings; import com.boydti.fawe.object.clipboard.DiskOptimizedClipboard; import com.boydti.fawe.object.clipboard.FaweClipboard; +import com.boydti.fawe.object.clipboard.FaweClipboard.ClipboardEntity; import com.boydti.fawe.object.clipboard.MemoryOptimizedClipboard; import com.boydti.fawe.object.extent.LightingExtent; import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.biome.BaseBiome; import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockState; + import java.io.Closeable; import java.util.ArrayList; import java.util.Collections; @@ -56,15 +59,16 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable { - private Region region; + private Region region; + private BlockVector3 origin; public FaweClipboard IMP; - private Vector size; + private BlockVector3 size; private int mx; private int my; private int mz; - private Vector origin; - private MutableBlockVector mutable = new MutableBlockVector(); - + private BlockStateHolder[][][] blocks; + private final List entities = new ArrayList<>(); + public BlockArrayClipboard(Region region) { checkNotNull(region); this.region = region.clone(); @@ -74,6 +78,7 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable this.mx = origin.getBlockX(); this.my = origin.getBlockY(); this.mz = origin.getBlockZ(); + this.blocks = new BlockStateHolder[size.getBlockX()][size.getBlockY()][size.getBlockZ()]; } /** @@ -92,6 +97,7 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable this.mx = origin.getBlockX(); this.my = origin.getBlockY(); this.mz = origin.getBlockZ(); + this.blocks = new BlockStateHolder[size.getBlockX()][size.getBlockY()][size.getBlockZ()]; } public BlockArrayClipboard(Region region, FaweClipboard clipboard) { @@ -103,6 +109,7 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable this.my = origin.getBlockY(); this.mz = origin.getBlockZ(); this.IMP = clipboard; + this.blocks = new BlockStateHolder[size.getBlockX()][size.getBlockY()][size.getBlockZ()]; } public void init(Region region, FaweClipboard fc) { @@ -115,6 +122,7 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable this.mx = origin.getBlockX(); this.my = origin.getBlockY(); this.mz = origin.getBlockZ(); + this.blocks = new BlockStateHolder[size.getBlockX()][size.getBlockY()][size.getBlockZ()]; } @Override @@ -125,6 +133,7 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable @Override public void close() { IMP.close(); + } @Override @@ -137,36 +146,36 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable } @Override - public Vector getOrigin() { + public BlockVector3 getOrigin() { return origin; } @Override - public void setOrigin(Vector origin) { + public void setOrigin(BlockVector3 origin) { this.origin = origin; IMP.setOrigin(origin.subtract(region.getMinimumPoint())); } @Override - public Vector getDimensions() { + public BlockVector3 getDimensions() { return region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); } @Override - public Vector getMinimumPoint() { + public BlockVector3 getMinimumPoint() { return region.getMinimumPoint(); } @Override - public Vector getMaximumPoint() { + public BlockVector3 getMaximumPoint() { return region.getMaximumPoint(); } @Override public List getEntities(Region region) { - List filtered = new ArrayList(); + List filtered = new ArrayList<>(); for (Entity entity : getEntities()) { - if (region.contains(entity.getLocation().toVector())) { + if (region.contains(entity.getLocation().toBlockPoint())) { filtered.add(entity); } } @@ -185,32 +194,49 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable } @Override - public BlockState getBlock(Vector position) { + public BlockState getBlock(BlockVector3 position) { if (region.contains(position)) { int x = position.getBlockX() - mx; int y = position.getBlockY() - my; int z = position.getBlockZ() - mz; - return IMP.getBlock(x, y, z); + return IMP.getBlock(x, y, z).toImmutableState(); } return EditSession.nullBlock; } public BlockState getBlockAbs(int x, int y, int z) { - return IMP.getBlock(x, y, z); + return IMP.getBlock(x, y, z).toImmutableState(); } @Override - public BlockState getLazyBlock(Vector position) { +//<<<<<<< HEAD + public BlockState getLazyBlock(BlockVector3 position) { return getBlock(position); } +//======= +// public BaseBlock getFullBlock(BlockVector3 position) { +// if (region.contains(position)) { +// BlockVector3 v = position.subtract(region.getMinimumPoint()); +// BlockStateHolder block = blocks[v.getBlockX()][v.getBlockY()][v.getBlockZ()]; +// if (block != null) { +// return block.toBaseBlock(); +// } +// } +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner @Override - public BlockState getFullBlock(Vector position) { - return getLazyBlock(position); + public BaseBlock getFullBlock(BlockVector3 position) { + if(region.contains(position)) { + int x = position.getBlockX() - mx; + int y = position.getBlockY() - my; + int z = position.getBlockZ() - mz; + return IMP.getBlock(x, y, z); + } + return EditSession.nullBlock.toBaseBlock(); } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { if (region.contains(location)) { final int x = location.getBlockX(); final int y = location.getBlockY(); @@ -228,7 +254,7 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { x -= mx; y -= my; z -= mz; @@ -236,14 +262,14 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { int x = position.getBlockX() - mx; int z = position.getBlockZ() - mz; return IMP.getBiome(x, z); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { int x = position.getBlockX() - mx; int z = position.getBlockZ() - mz; IMP.setBiome(x, z, biome.getId()); @@ -275,17 +301,11 @@ public class BlockArrayClipboard implements Clipboard, LightingExtent, Closeable @Override public int getOpacity(int x, int y, int z) { - mutable.mutX(x); - mutable.mutY(y); - mutable.mutZ(z); - return getBlock(mutable).getBlockType().getMaterial().getLightOpacity(); + return getBlock(BlockVector3.at(x, y, z)).getBlockType().getMaterial().getLightOpacity(); } @Override public int getBrightness(int x, int y, int z) { - mutable.mutX(x); - mutable.mutY(y); - mutable.mutZ(z); - return getBlock(mutable).getBlockType().getMaterial().getLightValue(); + return getBlock(BlockVector3.at(x, y, z)).getBlockType().getMaterial().getLightValue(); } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/Clipboard.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/Clipboard.java index fa7ff1929..e0022d480 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 @@ -19,8 +19,8 @@ package com.sk89q.worldedit.extent.clipboard; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; /** @@ -42,20 +42,20 @@ public interface Clipboard extends Extent { * * @return the dimensions */ - Vector getDimensions(); + BlockVector3 getDimensions(); /** * Get the origin point from which the copy was made from. * * @return the origin */ - Vector getOrigin(); + BlockVector3 getOrigin(); /** * Set the origin point from which the copy was made from. * * @param origin the origin */ - void setOrigin(Vector origin); + void setOrigin(BlockVector3 origin); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/StoredEntity.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/StoredEntity.java index 4b56e5e06..ebece5abf 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/StoredEntity.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/StoredEntity.java @@ -68,6 +68,11 @@ abstract class StoredEntity implements Entity { return location; } + @Override + public boolean setLocation(Location location) { + throw new IllegalArgumentException("StoredEntities are immutable"); + } + @Override public Extent getExtent() { return location.getExtent(); 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 24ceded83..0f4cd464f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/BuiltInClipboardFormat.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/BuiltInClipboardFormat.java @@ -19,28 +19,220 @@ package com.sk89q.worldedit.extent.clipboard.io; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Map; +import java.util.Set; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +import com.boydti.fawe.object.clipboard.AbstractClipboardFormat; +import com.boydti.fawe.object.io.PGZIPOutputStream; +import com.boydti.fawe.object.io.ResettableFileInputStream; +import com.boydti.fawe.object.schematic.PNGWriter; +import com.boydti.fawe.object.schematic.StructureFormat; +import com.google.common.collect.ImmutableSet; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.NBTConstants; +import com.sk89q.jnbt.NBTInputStream; +import com.sk89q.jnbt.NBTOutputStream; +import com.sk89q.jnbt.NamedTag; +import com.sk89q.jnbt.Tag; + /** * A collection of supported clipboard formats. */ -@Deprecated -public class BuiltInClipboardFormat { - public static final ClipboardFormat MCEDIT_SCHEMATIC = ClipboardFormat.SCHEMATIC; - public static final ClipboardFormat SPONGE_SCHEMATIC = ClipboardFormat.SPONGE_SCHEMATIC; - public static final ClipboardFormat STRUCTURE = ClipboardFormat.STRUCTURE; - public static final ClipboardFormat PNG = ClipboardFormat.PNG; - +public enum BuiltInClipboardFormat implements ClipboardFormat{ + /** + * The Schematic format used by MCEdit. + */ @Deprecated - public static final ClipboardFormat[] values() { - return ClipboardFormat.values; - } - - @Deprecated - public static ClipboardFormat valueOf(String value) { - switch (value) { - case "MCEDIT_SCHEMATIC": - value = "SCHEMATIC"; - break; + MCEDIT_SCHEMATIC("mcedit", "mce", "schematic") { + @Override + public ClipboardReader getReader(InputStream inputStream) throws IOException { + if (inputStream instanceof FileInputStream) { + inputStream = new ResettableFileInputStream((FileInputStream) inputStream); + } + BufferedInputStream buffered = new BufferedInputStream(inputStream); + NBTInputStream nbtStream = new NBTInputStream(new BufferedInputStream(new GZIPInputStream(buffered))); + SchematicReader input = new SchematicReader(nbtStream); + input.setUnderlyingStream(inputStream); + return input; } - return ClipboardFormat.valueOf(value); + + @Override + public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { + throw new IOException("This format does not support saving, use `schem` as format"); + } + + @Override + public boolean isFormat(File file) { + try (NBTInputStream str = new NBTInputStream(new GZIPInputStream(new FileInputStream(file)))) { + NamedTag rootTag = str.readNamedTag(); + if (!rootTag.getName().equals("Schematic")) { + return false; + } + CompoundTag schematicTag = (CompoundTag) rootTag.getTag(); + + // Check + Map schematic = schematicTag.getValue(); + if (!schematic.containsKey("Materials")) { + return false; + } + } catch (Exception e) { + return false; + } + return true; + } + + @Override + public String getPrimaryFileExtension() { + return "schematic"; + } + }, + + @Deprecated + SPONGE_SCHEMATIC("sponge", "schem") { + @Override + public ClipboardReader getReader(InputStream inputStream) throws IOException { + if (inputStream instanceof FileInputStream) { + inputStream = new ResettableFileInputStream((FileInputStream) inputStream); + } + BufferedInputStream buffered = new BufferedInputStream(inputStream); + NBTInputStream nbtStream = new NBTInputStream(new BufferedInputStream(new GZIPInputStream(buffered))); + SpongeSchematicReader input = new SpongeSchematicReader(nbtStream); + return input; + } + + @Override + public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { + OutputStream gzip; + if (outputStream instanceof PGZIPOutputStream || outputStream instanceof GZIPOutputStream) { + gzip = outputStream; + } else { + outputStream = new BufferedOutputStream(outputStream); + PGZIPOutputStream pigz = new PGZIPOutputStream(outputStream); + gzip = pigz; + } + NBTOutputStream nbtStream = new NBTOutputStream(new BufferedOutputStream(gzip)); + return new SpongeSchematicWriter(nbtStream); + } + + @Override + public boolean isFormat(File file) { + try (NBTInputStream str = new NBTInputStream(new GZIPInputStream(new FileInputStream(file)))) { + NamedTag rootTag = str.readNamedTag(); + if (!rootTag.getName().equals("Schematic")) { + return false; + } + CompoundTag schematicTag = (CompoundTag) rootTag.getTag(); + + // Check + Map schematic = schematicTag.getValue(); + if (!schematic.containsKey("Version")) { + return false; + } + } catch (Exception e) { + return false; + } + + return true; + } + + @Override + public String getPrimaryFileExtension() { + return "schem"; + } + }, + + /** + * The structure block format: + * http://minecraft.gamepedia.com/Structure_block_file_format + */ + STRUCTURE("structure", "nbt") { + @Override + public ClipboardReader getReader(InputStream inputStream) throws IOException { + inputStream = new BufferedInputStream(inputStream); + NBTInputStream nbtStream = new NBTInputStream(new BufferedInputStream(new GZIPInputStream(inputStream))); + return new StructureFormat(nbtStream); + } + + @Override + public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { + outputStream = new BufferedOutputStream(outputStream); + OutputStream gzip; + if (outputStream instanceof PGZIPOutputStream || outputStream instanceof GZIPOutputStream) { + gzip = outputStream; + } else { + PGZIPOutputStream pigz = new PGZIPOutputStream(outputStream); + gzip = pigz; + } + NBTOutputStream nbtStream = new NBTOutputStream(new BufferedOutputStream(gzip)); + return new StructureFormat(nbtStream); + } + + @Override + public boolean isFormat(File file) { + return file.getName().endsWith(".nbt"); + } + + @Override + public String getPrimaryFileExtension() { + return "nbt"; + } + }, + + /** + * Isometric PNG writer + */ + PNG("png", "image") { + + @Override + public ClipboardReader getReader(InputStream inputStream) throws IOException { + return null; + } + + @Override + public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { + return new PNGWriter(new BufferedOutputStream(outputStream)); + } + + @Override + public boolean isFormat(File file) { + return file.getName().endsWith(".png"); + } + + @Override + public String getPrimaryFileExtension() { + return "png"; + } + }; + + private final ImmutableSet aliases; + + BuiltInClipboardFormat(String... aliases) { + this.aliases = ImmutableSet.copyOf(aliases); } + + @Override + public String getName() { + return name(); + } + + @Override + public Set getAliases() { + return this.aliases; + } + + @Override + public Set getFileExtensions() { + return ImmutableSet.of(getPrimaryFileExtension()); + } + } \ No newline at end of file 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 0415b5ed2..c6213806f 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 @@ -19,486 +19,51 @@ package com.sk89q.worldedit.extent.clipboard.io; -import com.boydti.fawe.config.BBC; -import com.boydti.fawe.config.Settings; -import com.boydti.fawe.jnbt.NBTStreamer; -import com.boydti.fawe.object.RunnableVal; -import com.boydti.fawe.object.clipboard.*; -import com.boydti.fawe.object.io.FastByteArrayOutputStream; -import com.boydti.fawe.object.io.PGZIPOutputStream; -import com.boydti.fawe.object.io.ResettableFileInputStream; -import com.boydti.fawe.object.schematic.PNGWriter; -import com.boydti.fawe.object.schematic.Schematic; -import com.boydti.fawe.object.schematic.StructureFormat; -import com.boydti.fawe.util.MainUtil; -import com.boydti.fawe.util.ReflectionUtils; -import com.google.common.io.ByteSource; -import com.google.common.io.Files; -import com.google.gson.Gson; -import com.sk89q.jnbt.*; -import com.sk89q.worldedit.LocalConfiguration; -import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.entity.Player; -import com.sk89q.worldedit.extension.platform.Actor; -import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; -import com.sk89q.worldedit.extent.clipboard.Clipboard; -import com.sk89q.worldedit.session.ClipboardHolder; -import com.sk89q.worldedit.world.block.BlockTypes; - -import java.io.*; -import java.lang.reflect.Array; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.net.URI; -import java.net.URISyntaxException; import java.net.URL; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Pattern; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import javax.annotation.Nullable; - +import java.util.HashMap; +import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; + +import com.boydti.fawe.config.Settings; +import com.boydti.fawe.object.RunnableVal; +import com.boydti.fawe.object.clipboard.URIClipboardHolder; +import com.boydti.fawe.object.io.PGZIPOutputStream; +import com.boydti.fawe.object.schematic.Schematic; +import com.boydti.fawe.util.MainUtil; +import com.google.gson.Gson; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.session.ClipboardHolder; + /** * A collection of supported clipboard formats. */ -public enum ClipboardFormat { - - /** - * The Schematic format used by many software. - */ - @Deprecated - SCHEMATIC(new AbstractClipboardFormat("SCHEMATIC", "mcedit", "mce", "schematic") { - @Override - public ClipboardReader getReader(InputStream inputStream) throws IOException { - if (inputStream instanceof FileInputStream) { - inputStream = new ResettableFileInputStream((FileInputStream) inputStream); - } - BufferedInputStream buffered = new BufferedInputStream(inputStream); - NBTInputStream nbtStream = new NBTInputStream(new BufferedInputStream(new GZIPInputStream(buffered))); - SchematicReader input = new SchematicReader(nbtStream); - input.setUnderlyingStream(inputStream); - return input; - } - - @Override - public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { - throw new UnsupportedOperationException("No longer supported."); - } - - @Override - public boolean isFormat(File file) { - if (!file.getName().toLowerCase().endsWith(".schematic")) return false; - DataInputStream str = null; - try { - str = new DataInputStream(new GZIPInputStream(new FileInputStream(file))); - if ((str.readByte() & 0xFF) != NBTConstants.TYPE_COMPOUND) { - return false; - } - byte[] nameBytes = new byte[str.readShort() & 0xFFFF]; - str.readFully(nameBytes); - String name = new String(nameBytes, NBTConstants.CHARSET); - return name.equals("Schematic"); - } catch (IOException e) { - return false; - } finally { - if (str != null) { - try { - str.close(); - } catch (IOException ignored) { - } - } - } - } - - @Override - public String getExtension() { - return "schematic"; - } - }), - - @Deprecated - SPONGE_SCHEMATIC(new AbstractClipboardFormat("SPONGE", "sponge", "schem") { - @Override - public ClipboardReader getReader(InputStream inputStream) throws IOException { - if (inputStream instanceof FileInputStream) { - inputStream = new ResettableFileInputStream((FileInputStream) inputStream); - } - BufferedInputStream buffered = new BufferedInputStream(inputStream); - NBTInputStream nbtStream = new NBTInputStream(new BufferedInputStream(new GZIPInputStream(buffered))); - SpongeSchematicReader input = new SpongeSchematicReader(nbtStream); - return input; - } - - @Override - public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { - OutputStream gzip; - if (outputStream instanceof PGZIPOutputStream || outputStream instanceof GZIPOutputStream) { - gzip = outputStream; - } else { - outputStream = new BufferedOutputStream(outputStream); - PGZIPOutputStream pigz = new PGZIPOutputStream(outputStream); - gzip = pigz; - } - NBTOutputStream nbtStream = new NBTOutputStream(new BufferedOutputStream(gzip)); - return new SpongeSchematicWriter(nbtStream); - } - - @Override - public boolean isFormat(File file) { - if (!file.getName().toLowerCase().endsWith(".schem")) return false; - DataInputStream str = null; - try { - str = new DataInputStream(new GZIPInputStream(new FileInputStream(file))); - if ((str.readByte() & 0xFF) != NBTConstants.TYPE_COMPOUND) { - return false; - } - byte[] nameBytes = new byte[str.readShort() & 0xFFFF]; - str.readFully(nameBytes); - String name = new String(nameBytes, NBTConstants.CHARSET); - return name.equals("Schematic"); - } catch (IOException e) { - return false; - } finally { - if (str != null) { - try { - str.close(); - } catch (IOException ignored) { - } - } - } - } - - @Override - public String getExtension() { - return "schem"; - } - }), - - /** - * The structure block format: - * http://minecraft.gamepedia.com/Structure_block_file_format - */ - STRUCTURE(new AbstractClipboardFormat("STRUCTURE", "structure", "nbt") { - @Override - public ClipboardReader getReader(InputStream inputStream) throws IOException { - inputStream = new BufferedInputStream(inputStream); - NBTInputStream nbtStream = new NBTInputStream(new BufferedInputStream(new GZIPInputStream(inputStream))); - return new StructureFormat(nbtStream); - } - - @Override - public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { - outputStream = new BufferedOutputStream(outputStream); - OutputStream gzip; - if (outputStream instanceof PGZIPOutputStream || outputStream instanceof GZIPOutputStream) { - gzip = outputStream; - } else { - PGZIPOutputStream pigz = new PGZIPOutputStream(outputStream); - gzip = pigz; - } - NBTOutputStream nbtStream = new NBTOutputStream(new BufferedOutputStream(gzip)); - return new StructureFormat(nbtStream); - } - - @Override - public boolean isFormat(File file) { - return file.getName().endsWith(".nbt"); - } - - @Override - public String getExtension() { - return "nbt"; - } - }), - - /** - * Isometric PNG writer - */ - PNG(new AbstractClipboardFormat("PNG", "png", "image") { - - @Override - public ClipboardReader getReader(InputStream inputStream) throws IOException { - return null; - } - - @Override - public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { - return new PNGWriter(new BufferedOutputStream(outputStream)); - } - - @Override - public boolean isFormat(File file) { - return file.getName().endsWith(".png"); - } - - @Override - public String getExtension() { - return "png"; - } - }), - - ; - - public static final ClipboardFormat[] values; - - private static final Map aliasMap; - - static { - aliasMap = new ConcurrentHashMap<>(8, 0.9f, 1); - for (ClipboardFormat emum : ClipboardFormat.values()) { - for (String alias : emum.getAliases()) { - aliasMap.put(alias, emum); - } - } - values = values(); - } - - private IClipboardFormat format; - - ClipboardFormat() { - - } - - ClipboardFormat(IClipboardFormat format) { - this.format = format; - } +public interface ClipboardFormat { /** * Returns the name of this format. * * @return The name of the format */ - public String getName() { - return name(); - } - - /** - * Get the file extension this format primarily uses. - * - * @return The primary file extension - */ - public String getPrimaryFileExtension() { - return getExtension(); - } - - /** - * Get the file extensions this format is commonly known to use. This should - * include {@link #getPrimaryFileExtension()}. - * - * @return The file extensions this format might be known by - */ - public Set getFileExtensions() { - return Collections.singleton(getPrimaryFileExtension()); - } - - - public URL uploadPublic(final Clipboard clipboard, String category, String user) { - // summary - // blocks - HashMap map = new HashMap(); - Vector dimensions = clipboard.getDimensions(); - map.put("width", dimensions.getX()); - map.put("height", dimensions.getY()); - map.put("length", dimensions.getZ()); - map.put("creator", user); - Gson gson = new Gson(); - String json = gson.toJson(map); - return MainUtil.upload(Settings.IMP.WEB.ASSETS, false, json, category, null, new RunnableVal() { - @Override - public void run(OutputStream value) { - write(value, clipboard); - } - }); - } - - public static MultiClipboardHolder loadAllFromInput(Actor player, String input, ClipboardFormat format, boolean message) throws IOException { - checkNotNull(player); - checkNotNull(input); - WorldEdit worldEdit = WorldEdit.getInstance(); - LocalConfiguration config = worldEdit.getConfiguration(); - if (input.startsWith("url:")) { - if (!player.hasPermission("worldedit.schematic.load.web")) { - if (message) BBC.NO_PERM.send(player, "worldedit.schematic.load.web"); - return null; - } - URL base = new URL(Settings.IMP.WEB.URL); - input = new URL(base, "uploads/" + input.substring(4) + ".schematic").toString(); - } - if (input.startsWith("http")) { - if (!player.hasPermission("worldedit.schematic.load.asset")) { - if (message) BBC.NO_PERM.send(player, "worldedit.schematic.load.asset"); - return null; - } - URL url = new URL(input); - URL webInterface = new URL(Settings.IMP.WEB.ASSETS); - if (!url.getHost().equalsIgnoreCase(webInterface.getHost())) { - if (message) BBC.WEB_UNAUTHORIZED.send(player, url); - return null; - } - MultiClipboardHolder clipboards = loadAllFromUrl(url); - return clipboards; - } else { - if (Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS && Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}").matcher(input).find() && !player.hasPermission("worldedit.schematic.load.other")) { - BBC.NO_PERM.send(player, "worldedit.schematic.load.other"); - return null; - } - File working = worldEdit.getWorkingDirectoryFile(config.saveDir); - File dir = Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS ? new File(working, player.getUniqueId().toString()) : working; - File f; - if (input.startsWith("#")) { - String[] extensions; - if (format != null) { - extensions = format.getFileExtensions().toArray(new String[0]); - } else { - extensions = ClipboardFormats.getFileExtensionArray(); - } - f = player.openFileOpenDialog(extensions); - if (f == null || !f.exists()) { - if (message) player.printError("Schematic " + input + " does not exist! (" + f + ")"); - return null; - } - } else { - if (Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS && Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}").matcher(input).find() && !player.hasPermission("worldedit.schematic.load.other")) { - if (message) BBC.NO_PERM.send(player, "worldedit.schematic.load.other"); - return null; - } - if (format == null && input.matches(".*\\.[\\w].*")) { - String extension = input.substring(input.lastIndexOf('.') + 1, input.length()); - format = ClipboardFormat.findByExtension(extension); - } - f = MainUtil.resolve(dir, input, format, true); - } - if (f == null || !f.exists()) { - if (!input.contains("../")) { - dir = worldEdit.getWorkingDirectoryFile(config.saveDir); - f = MainUtil.resolve(dir, input, format, true); - } - } - if (f == null || !f.exists() || !MainUtil.isInSubDirectory(working, f)) { - if (message) player.printError("Schematic " + input + " does not exist! (" + ((f == null) ? false : f.exists()) + "|" + f + "|" + (f == null ? false : !MainUtil.isInSubDirectory(working, f)) + ")"); - return null; - } - if (format == null && f.isFile()) { - format = ClipboardFormat.findByFile(f); - if (format == null) { - BBC.CLIPBOARD_INVALID_FORMAT.send(player, f.getName()); - return null; - } - } - if (!f.exists()) { - if (message) BBC.SCHEMATIC_NOT_FOUND.send(player, input); - return null; - } - if (!f.isDirectory()) { - ByteSource source = Files.asByteSource(f); - URI uri = f.toURI(); - return new MultiClipboardHolder(uri, new LazyClipboardHolder(f.toURI(), source, format, null)); - } - URIClipboardHolder[] clipboards = loadAllFromDirectory(f); - if (clipboards.length < 1) { - if (message) BBC.SCHEMATIC_NOT_FOUND.send(player, input); - return null; - } - return new MultiClipboardHolder(f.toURI(), clipboards); - } - } - - public static URIClipboardHolder[] loadAllFromDirectory(File dir) { - HashSet extensions = new HashSet<>(Arrays.asList(ClipboardFormats.getFileExtensionArray())); - File[] files = dir.listFiles(pathname -> { - String input = pathname.getName(); - String extension = input.substring(input.lastIndexOf('.') + 1, input.length()); - return (extensions.contains(extension.toLowerCase())); - }); - LazyClipboardHolder[] clipboards = new LazyClipboardHolder[files.length]; - for (int i = 0; i < files.length; i++) { - File file = files[i]; - ByteSource source = Files.asByteSource(file); - ClipboardFormat format = ClipboardFormat.findByFile(file); - clipboards[i] = new LazyClipboardHolder(file.toURI(), source, format, null); - } - return clipboards; - } - - public static MultiClipboardHolder loadAllFromUrl(URL url) throws IOException { - List clipboards = new ArrayList<>(); - try (ReadableByteChannel rbc = Channels.newChannel(url.openStream())) { - try (InputStream in = Channels.newInputStream(rbc)) { - try (ZipInputStream zip = new ZipInputStream(in)) { - ZipEntry entry; - byte[] buffer = new byte[8192]; - while ((entry = zip.getNextEntry()) != null) { - String filename = entry.getName(); - String extension = filename.substring(filename.lastIndexOf('.') + 1, filename.length()); - ClipboardFormat format = findByExtension(filename); - if (format != null) { - FastByteArrayOutputStream out = new FastByteArrayOutputStream(); - int len = 0; - while ((len = zip.read(buffer)) > 0) { - out.write(buffer, 0, len); - } - byte[] array = out.toByteArray(); - ByteSource source = ByteSource.wrap(array); - LazyClipboardHolder clipboard = new LazyClipboardHolder(url.toURI(), source, format, null); - clipboards.add(clipboard); - } - } - } catch (URISyntaxException e) { - e.printStackTrace(); - } - } - } - LazyClipboardHolder[] arr = clipboards.toArray(new LazyClipboardHolder[clipboards.size()]); - try { - MultiClipboardHolder multi = new MultiClipboardHolder(url.toURI()); - for (LazyClipboardHolder h : arr) multi.add(h); - return multi; - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - private void write(OutputStream value, Clipboard clipboard) { - try { - try (PGZIPOutputStream gzip = new PGZIPOutputStream(value)) { - try (ClipboardWriter writer = format.getWriter(gzip)) { - writer.write(clipboard); - } - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - public URL uploadAnonymous(final Clipboard clipboard) { - return MainUtil.upload(null, null, format.getExtension(), new RunnableVal() { - @Override - public void run(OutputStream value) { - write(value, clipboard); - } - }); - } - - public IClipboardFormat getFormat() { - return format; - } + String getName(); /** * Get a set of aliases. * * @return a set of aliases */ - public Set getAliases() { - return format.getAliases(); - } + Set getAliases(); /** * Create a reader. @@ -507,9 +72,7 @@ public enum ClipboardFormat { * @return a reader * @throws IOException thrown on I/O error */ - public ClipboardReader getReader(InputStream inputStream) throws IOException { - return format.getReader(inputStream); - } + ClipboardReader getReader(InputStream inputStream) throws IOException; /** * Create a writer. @@ -518,10 +81,31 @@ public enum ClipboardFormat { * @return a writer * @throws IOException thrown on I/O error */ - public ClipboardWriter getWriter(OutputStream outputStream) throws IOException { - return format.getWriter(outputStream); - } + ClipboardWriter getWriter(OutputStream outputStream) throws IOException; + /** + * Return whether the given file is of this format. + * + * @param file the file + * @return true if the given file is of this format + */ + boolean isFormat(File file); + + /** + * Get the file extension this format primarily uses. + * + * @return The primary file extension + */ + String getPrimaryFileExtension(); + + /** + * Get the file extensions this format is commonly known to use. This should + * include {@link #getPrimaryFileExtension()}. + * + * @return The file extensions this format might be known by + */ + Set getFileExtensions(); + /** * Set the player's clipboard * @param player @@ -530,7 +114,7 @@ public enum ClipboardFormat { * @return the held clipboard * @throws IOException */ - public ClipboardHolder hold(Player player, URI uri, InputStream in) throws IOException { + default ClipboardHolder hold(Player player, URI uri, InputStream in) throws IOException { checkNotNull(player); checkNotNull(uri); checkNotNull(in); @@ -546,95 +130,53 @@ public enum ClipboardFormat { session.setClipboard(holder); return holder; } - - public Schematic load(File file) throws IOException { + + default Schematic load(File file) throws IOException { return load(new FileInputStream(file)); } - public Schematic load(InputStream stream) throws IOException { - return new Schematic(this.getReader(stream).read()); + default Schematic load(InputStream stream) throws IOException { + return new Schematic(getReader(stream).read()); } - - /** - * Get the file extension used - * - * @return file extension string - */ - public String getExtension() { - return format.getExtension(); - } - - /** - * Return whether the given file is of this format. - * - * @param file the file - * @return true if the given file is of this format - */ - public boolean isFormat(File file) { - return format.isFormat(file); - } - - /** - * Find the clipboard format named by the given alias. - * - * @param alias the alias - * @return the format, otherwise null if none is matched - */ - @Nullable - public static ClipboardFormat findByAlias(String alias) { - checkNotNull(alias); - return aliasMap.get(alias.toLowerCase(Locale.ENGLISH).trim()); - } - - @Nullable - public static ClipboardFormat findByExtension(String extension) { - checkNotNull(extension); - extension = extension.toLowerCase(); - for (ClipboardFormat format : values) { - if (format.getFileExtensions().contains(extension)) { - return format; + + + default URL uploadPublic(final Clipboard clipboard, String category, String user) { + // summary + // blocks + HashMap map = new HashMap<>(); + BlockVector3 dimensions = clipboard.getDimensions(); + map.put("width", dimensions.getX()); + map.put("height", dimensions.getY()); + map.put("length", dimensions.getZ()); + map.put("creator", user); + Gson gson = new Gson(); + String json = gson.toJson(map); + return MainUtil.upload(Settings.IMP.WEB.ASSETS, false, json, category, null, new RunnableVal() { + @Override + public void run(OutputStream value) { + write(value, clipboard); } - } - return null; + }); } - - /** - * Detect the format given a file. - * - * @param file the file - * @return the format, otherwise null if one cannot be detected - */ - @Nullable - public static ClipboardFormat findByFile(File file) { - checkNotNull(file); - for (ClipboardFormat format : EnumSet.allOf(ClipboardFormat.class)) { - if (format.isFormat(file)) { - return format; + + default URL uploadAnonymous(final Clipboard clipboard) { + return MainUtil.upload(null, null, getPrimaryFileExtension(), new RunnableVal() { + @Override + public void run(OutputStream value) { + write(value, clipboard); } - } - - return null; + }); } - - public static ClipboardFormat addFormat(IClipboardFormat instance) { - ClipboardFormat newEnum = ReflectionUtils.addEnum(ClipboardFormat.class, instance.getName()); - newEnum.format = instance; - for (String alias : newEnum.getAliases()) { - aliasMap.put(alias, newEnum); - } - - ArrayList newValues = new ArrayList<>(Arrays.asList(values)); - newValues.add(newEnum); - ClipboardFormat[] newValuesArray = newValues.toArray(new ClipboardFormat[newValues.size()]); + + default void write(OutputStream value, Clipboard clipboard) { try { - ReflectionUtils.setFailsafeFieldValue(ClipboardFormat.class.getDeclaredField("values"), null, newValuesArray); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { + try (PGZIPOutputStream gzip = new PGZIPOutputStream(value)) { + try (ClipboardWriter writer = getWriter(gzip)) { + writer.write(clipboard); + } + } + } catch (IOException e) { e.printStackTrace(); } - return newEnum; } - - -} \ No newline at end of file +} 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 cdc0e0461..e2598b3f8 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 @@ -19,17 +19,77 @@ package com.sk89q.worldedit.extent.clipboard.io; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.boydti.fawe.config.BBC; +import com.boydti.fawe.config.Settings; +import com.boydti.fawe.object.clipboard.LazyClipboardHolder; +import com.boydti.fawe.object.clipboard.MultiClipboardHolder; +import com.boydti.fawe.object.clipboard.URIClipboardHolder; +import com.boydti.fawe.object.io.FastByteArrayOutputStream; +import com.boydti.fawe.util.MainUtil; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; +import com.google.common.io.ByteSource; +import com.google.common.io.Files; +import com.sk89q.worldedit.LocalConfiguration; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.platform.Actor; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; import javax.annotation.Nullable; -import java.io.File; -import java.util.*; - -import static com.google.common.base.Preconditions.checkNotNull; public class ClipboardFormats { + + private static final Map aliasMap = new HashMap<>(); + private static final Multimap fileExtensionMap = HashMultimap.create(); + private static final List registeredFormats = new ArrayList<>(); + + public static void registerClipboardFormat(ClipboardFormat format) { + checkNotNull(format); + + for (String key : format.getAliases()) { + String lowKey = key.toLowerCase(Locale.ENGLISH); + ClipboardFormat old = aliasMap.put(lowKey, format); + if (old != null) { + aliasMap.put(lowKey, old); + WorldEdit.logger.warning(format.getClass().getName() + " cannot override existing alias '" + lowKey + "' used by " + old.getClass().getName()); + } + } + for (String ext : format.getFileExtensions()) { + String lowExt = ext.toLowerCase(Locale.ENGLISH); + fileExtensionMap.put(lowExt, format); + } + registeredFormats.add(format); + } + + static { + for (BuiltInClipboardFormat format : BuiltInClipboardFormat.values()) { + registerClipboardFormat(format); + } + } + /** * Find the clipboard format named by the given alias. * @@ -39,7 +99,8 @@ public class ClipboardFormats { */ @Nullable public static ClipboardFormat findByAlias(String alias) { - return ClipboardFormat.findByAlias(alias); + checkNotNull(alias); + return aliasMap.get(alias.toLowerCase(Locale.ENGLISH).trim()); } /** @@ -53,7 +114,7 @@ public class ClipboardFormats { public static ClipboardFormat findByFile(File file) { checkNotNull(file); - for (ClipboardFormat format : ClipboardFormat.values) { + for (ClipboardFormat format : registeredFormats) { if (format.isFormat(file)) { return format; } @@ -61,22 +122,36 @@ public class ClipboardFormats { return null; } + + /** + * Detect the format using the given extension + * @param string + * the extension + * @return the format, otherwise null if one cannot be detected + */ + @Nullable + public static ClipboardFormat findByExtension(String extension) { + checkNotNull(extension); + + Collection> entries = getFileExtensionMap().entries(); + for(Map.Entry entry : entries) { + if(entry.getKey().equalsIgnoreCase(extension)) { + return entry.getValue(); + } + } + return null; + + } /** * @return a multimap from a file extension to the potential matching formats. */ public static Multimap getFileExtensionMap() { - HashMultimap map = HashMultimap.create(); - for (ClipboardFormat format : ClipboardFormat.values) { - for (String ext : format.getFileExtensions()) { - map.put(ext, format); - } - } - return map; + return Multimaps.unmodifiableMultimap(fileExtensionMap); } public static Collection getAll() { - return Arrays.asList(ClipboardFormat.values); + return Collections.unmodifiableCollection(registeredFormats); } /** @@ -84,13 +159,156 @@ public class ClipboardFormats { * It is not in SchematicCommands because it may rely on internal register calls. */ public static String[] getFileExtensionArray() { - List exts = new ArrayList<>(); - HashMultimap map = HashMultimap.create(); - for (ClipboardFormat format : ClipboardFormat.values) { - exts.addAll(format.getFileExtensions()); - } - return exts.toArray(new String[exts.size()]); + return fileExtensionMap.keySet().toArray(new String[fileExtensionMap.keySet().size()]); } - private ClipboardFormats() {} + private ClipboardFormats() { + } + + public static MultiClipboardHolder loadAllFromInput(Actor player, String input, ClipboardFormat format, boolean message) throws IOException { + checkNotNull(player); + checkNotNull(input); + WorldEdit worldEdit = WorldEdit.getInstance(); + LocalConfiguration config = worldEdit.getConfiguration(); + if (input.startsWith("url:")) { + if (!player.hasPermission("worldedit.schematic.load.web")) { + if (message) BBC.NO_PERM.send(player, "worldedit.schematic.load.web"); + return null; + } + URL base = new URL(Settings.IMP.WEB.URL); + input = new URL(base, "uploads/" + input.substring(4) + ".schematic").toString(); + } + if (input.startsWith("http")) { + if (!player.hasPermission("worldedit.schematic.load.asset")) { + if (message) BBC.NO_PERM.send(player, "worldedit.schematic.load.asset"); + return null; + } + URL url = new URL(input); + URL webInterface = new URL(Settings.IMP.WEB.ASSETS); + if (!url.getHost().equalsIgnoreCase(webInterface.getHost())) { + if (message) BBC.WEB_UNAUTHORIZED.send(player, url); + return null; + } + MultiClipboardHolder clipboards = loadAllFromUrl(url); + return clipboards; + } else { + if (Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS && Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}").matcher(input).find() && !player.hasPermission("worldedit.schematic.load.other")) { + BBC.NO_PERM.send(player, "worldedit.schematic.load.other"); + return null; + } + File working = worldEdit.getWorkingDirectoryFile(config.saveDir); + File dir = Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS ? new File(working, player.getUniqueId().toString()) : working; + File f; + if (input.startsWith("#")) { + String[] extensions; + if (format != null) { + extensions = format.getFileExtensions().toArray(new String[0]); + } else { + extensions = ClipboardFormats.getFileExtensionArray(); + } + f = player.openFileOpenDialog(extensions); + if (f == null || !f.exists()) { + if (message) player.printError("Schematic " + input + " does not exist! (" + f + ")"); + return null; + } + } else { + if (Settings.IMP.PATHS.PER_PLAYER_SCHEMATICS && Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}").matcher(input).find() && !player.hasPermission("worldedit.schematic.load.other")) { + if (message) BBC.NO_PERM.send(player, "worldedit.schematic.load.other"); + return null; + } + if (format == null && input.matches(".*\\.[\\w].*")) { + String extension = input.substring(input.lastIndexOf('.') + 1, input.length()); + format = findByExtension(extension); + } + f = MainUtil.resolve(dir, input, format, true); + } + if (f == null || !f.exists()) { + if (!input.contains("../")) { + dir = worldEdit.getWorkingDirectoryFile(config.saveDir); + f = MainUtil.resolve(dir, input, format, true); + } + } + if (f == null || !f.exists() || !MainUtil.isInSubDirectory(working, f)) { + if (message) player.printError("Schematic " + input + " does not exist! (" + ((f == null) ? false : f.exists()) + "|" + f + "|" + (f == null ? false : !MainUtil.isInSubDirectory(working, f)) + ")"); + return null; + } + if (format == null && f.isFile()) { + format = findByFile(f); + if (format == null) { + BBC.CLIPBOARD_INVALID_FORMAT.send(player, f.getName()); + return null; + } + } + if (!f.exists()) { + if (message) BBC.SCHEMATIC_NOT_FOUND.send(player, input); + return null; + } + if (!f.isDirectory()) { + ByteSource source = Files.asByteSource(f); + URI uri = f.toURI(); + return new MultiClipboardHolder(uri, new LazyClipboardHolder(f.toURI(), source, format, null)); + } + URIClipboardHolder[] clipboards = loadAllFromDirectory(f); + if (clipboards.length < 1) { + if (message) BBC.SCHEMATIC_NOT_FOUND.send(player, input); + return null; + } + return new MultiClipboardHolder(f.toURI(), clipboards); + } + } + + public static URIClipboardHolder[] loadAllFromDirectory(File dir) { + HashSet extensions = new HashSet<>(Arrays.asList(ClipboardFormats.getFileExtensionArray())); + File[] files = dir.listFiles(pathname -> { + String input = pathname.getName(); + String extension = input.substring(input.lastIndexOf('.') + 1, input.length()); + return (extensions.contains(extension.toLowerCase())); + }); + LazyClipboardHolder[] clipboards = new LazyClipboardHolder[files.length]; + for (int i = 0; i < files.length; i++) { + File file = files[i]; + ByteSource source = Files.asByteSource(file); + ClipboardFormat format = findByFile(file); + clipboards[i] = new LazyClipboardHolder(file.toURI(), source, format, null); + } + return clipboards; + } + + public static MultiClipboardHolder loadAllFromUrl(URL url) throws IOException { + List clipboards = new ArrayList<>(); + try (ReadableByteChannel rbc = Channels.newChannel(url.openStream())) { + try (InputStream in = Channels.newInputStream(rbc)) { + try (ZipInputStream zip = new ZipInputStream(in)) { + ZipEntry entry; + byte[] buffer = new byte[8192]; + while ((entry = zip.getNextEntry()) != null) { + String filename = entry.getName(); + String extension = filename.substring(filename.lastIndexOf('.') + 1, filename.length()); + ClipboardFormat format = findByExtension(filename); + if (format != null) { + FastByteArrayOutputStream out = new FastByteArrayOutputStream(); + int len = 0; + while ((len = zip.read(buffer)) > 0) { + out.write(buffer, 0, len); + } + byte[] array = out.toByteArray(); + ByteSource source = ByteSource.wrap(array); + LazyClipboardHolder clipboard = new LazyClipboardHolder(url.toURI(), source, format, null); + clipboards.add(clipboard); + } + } + } catch (URISyntaxException e) { + e.printStackTrace(); + } + } + } + LazyClipboardHolder[] arr = clipboards.toArray(new LazyClipboardHolder[clipboards.size()]); + try { + MultiClipboardHolder multi = new MultiClipboardHolder(url.toURI()); + for (LazyClipboardHolder h : arr) multi.add(h); + return multi; + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } } \ No newline at end of file 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 new file mode 100644 index 000000000..94b67a3db --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/MCEditSchematicReader.java @@ -0,0 +1,317 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extent.clipboard.io; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.jnbt.ByteArrayTag; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.IntTag; +import com.sk89q.jnbt.ListTag; +import com.sk89q.jnbt.NBTInputStream; +import com.sk89q.jnbt.NamedTag; +import com.sk89q.jnbt.ShortTag; +import com.sk89q.jnbt.StringTag; +import com.sk89q.jnbt.Tag; +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.entity.BaseEntity; +import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; +import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.legacycompat.NBTCompatibilityHandler; +import com.sk89q.worldedit.extent.clipboard.io.legacycompat.SignCompatibilityHandler; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.regions.Region; +import com.sk89q.worldedit.util.Location; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.entity.EntityType; +import com.sk89q.worldedit.world.entity.EntityTypes; +import com.sk89q.worldedit.world.registry.LegacyMapper; +import com.sk89q.worldedit.world.storage.NBTConversions; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Reads schematic files that are compatible with MCEdit and other editors. + */ +public class MCEditSchematicReader extends NBTSchematicReader { + + private static final List COMPATIBILITY_HANDLERS = new ArrayList<>(); + + static { + COMPATIBILITY_HANDLERS.add(new SignCompatibilityHandler()); + // TODO Add a handler for skulls, flower pots, note blocks, etc. + } + + private static final Logger log = Logger.getLogger(MCEditSchematicReader.class.getCanonicalName()); + private final NBTInputStream inputStream; + + /** + * Create a new instance. + * + * @param inputStream the input stream to read from + */ + public MCEditSchematicReader(NBTInputStream inputStream) { + checkNotNull(inputStream); + this.inputStream = inputStream; + } + + @Override + public Clipboard read() throws IOException { + // Schematic tag + NamedTag rootTag = inputStream.readNamedTag(); + if (!rootTag.getName().equals("Schematic")) { + throw new IOException("Tag 'Schematic' does not exist or is not first"); + } + CompoundTag schematicTag = (CompoundTag) rootTag.getTag(); + + // Check + Map schematic = schematicTag.getValue(); + if (!schematic.containsKey("Blocks")) { + throw new IOException("Schematic file is missing a 'Blocks' tag"); + } + + // Check type of Schematic + String materials = requireTag(schematic, "Materials", StringTag.class).getValue(); + if (!materials.equals("Alpha")) { + throw new IOException("Schematic file is not an Alpha schematic"); + } + + // ==================================================================== + // Metadata + // ==================================================================== + + BlockVector3 origin; + Region region; + + // Get information + short width = requireTag(schematic, "Width", ShortTag.class).getValue(); + short height = requireTag(schematic, "Height", ShortTag.class).getValue(); + short length = requireTag(schematic, "Length", ShortTag.class).getValue(); + + try { + int originX = requireTag(schematic, "WEOriginX", IntTag.class).getValue(); + int originY = requireTag(schematic, "WEOriginY", IntTag.class).getValue(); + int originZ = requireTag(schematic, "WEOriginZ", IntTag.class).getValue(); + BlockVector3 min = BlockVector3.at(originX, originY, originZ); + + int offsetX = requireTag(schematic, "WEOffsetX", IntTag.class).getValue(); + int offsetY = requireTag(schematic, "WEOffsetY", IntTag.class).getValue(); + int offsetZ = requireTag(schematic, "WEOffsetZ", IntTag.class).getValue(); + BlockVector3 offset = BlockVector3.at(offsetX, offsetY, offsetZ); + + origin = min.subtract(offset); + region = new CuboidRegion(min, min.add(width, height, length).subtract(BlockVector3.ONE)); + } catch (IOException ignored) { + origin = BlockVector3.ZERO; + region = new CuboidRegion(origin, origin.add(width, height, length).subtract(BlockVector3.ONE)); + } + + // ==================================================================== + // Blocks + // ==================================================================== + + // Get blocks + byte[] blockId = requireTag(schematic, "Blocks", ByteArrayTag.class).getValue(); + byte[] blockData = requireTag(schematic, "Data", ByteArrayTag.class).getValue(); + byte[] addId = new byte[0]; + short[] blocks = new short[blockId.length]; // Have to later combine IDs + + // We support 4096 block IDs using the same method as vanilla Minecraft, where + // the highest 4 bits are stored in a separate byte array. + if (schematic.containsKey("AddBlocks")) { + addId = requireTag(schematic, "AddBlocks", ByteArrayTag.class).getValue(); + } + + // Combine the AddBlocks data with the first 8-bit block ID + for (int index = 0; index < blockId.length; index++) { + if ((index >> 1) >= addId.length) { // No corresponding AddBlocks index + blocks[index] = (short) (blockId[index] & 0xFF); + } else { + if ((index & 1) == 0) { + blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (blockId[index] & 0xFF)); + } else { + blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (blockId[index] & 0xFF)); + } + } + } + + // Need to pull out tile entities + List tileEntities = requireTag(schematic, "TileEntities", ListTag.class).getValue(); + Map> tileEntitiesMap = new HashMap<>(); + + for (Tag tag : tileEntities) { + if (!(tag instanceof CompoundTag)) continue; + CompoundTag t = (CompoundTag) tag; + + int x = 0; + int y = 0; + int z = 0; + + Map values = new HashMap<>(); + + for (Map.Entry entry : t.getValue().entrySet()) { + switch (entry.getKey()) { + case "x": + if (entry.getValue() instanceof IntTag) { + x = ((IntTag) entry.getValue()).getValue(); + } + break; + case "y": + if (entry.getValue() instanceof IntTag) { + y = ((IntTag) entry.getValue()).getValue(); + } + break; + case "z": + if (entry.getValue() instanceof IntTag) { + z = ((IntTag) entry.getValue()).getValue(); + } + break; + } + + values.put(entry.getKey(), entry.getValue()); + } + + int index = y * width * length + z * width + x; + BlockState block = LegacyMapper.getInstance().getBlockFromLegacy(blocks[index], blockData[index]); + if (block != null) { + for (NBTCompatibilityHandler handler : COMPATIBILITY_HANDLERS) { + if (handler.isAffectedBlock(block)) { + handler.updateNBT(block, values); + } + } + } + + BlockVector3 vec = BlockVector3.at(x, y, z); + tileEntitiesMap.put(vec, values); + } + + BlockArrayClipboard clipboard = new BlockArrayClipboard(region); + clipboard.setOrigin(origin); + + // Don't log a torrent of errors + int failedBlockSets = 0; + + for (int x = 0; x < width; ++x) { + for (int y = 0; y < height; ++y) { + for (int z = 0; z < length; ++z) { + int index = y * width * length + z * width + x; + BlockVector3 pt = BlockVector3.at(x, y, z); + BlockState state = LegacyMapper.getInstance().getBlockFromLegacy(blocks[index], blockData[index]); + + try { + if (state != null) { + if (tileEntitiesMap.containsKey(pt)) { + clipboard.setBlock(region.getMinimumPoint().add(pt), state.toBaseBlock(new CompoundTag(tileEntitiesMap.get(pt)))); + } else { + clipboard.setBlock(region.getMinimumPoint().add(pt), state); + } + } else { + log.warning("Unknown block when pasting schematic: " + blocks[index] + ":" + blockData[index] + ". Please report this issue."); + } + } catch (WorldEditException e) { + switch (failedBlockSets) { + case 0: + log.log(Level.WARNING, "Failed to set block on a Clipboard", e); + break; + case 1: + log.log(Level.WARNING, "Failed to set block on a Clipboard (again) -- no more messages will be logged", e); + break; + default: + } + + failedBlockSets++; + } + } + } + } + + // ==================================================================== + // Entities + // ==================================================================== + + try { + List entityTags = requireTag(schematic, "Entities", ListTag.class).getValue(); + + for (Tag tag : entityTags) { + if (tag instanceof CompoundTag) { + CompoundTag compound = (CompoundTag) tag; + String id = convertEntityId(compound.getString("id")); + Location location = NBTConversions.toLocation(clipboard, compound.getListTag("Pos"), compound.getListTag("Rotation")); + + if (!id.isEmpty()) { + EntityType entityType = EntityTypes.get(id.toLowerCase()); + if (entityType != null) { + BaseEntity state = new BaseEntity(entityType, compound); + clipboard.createEntity(location, state); + } else { + log.warning("Unknown entity when pasting schematic: " + id.toLowerCase()); + } + } + } + } + } catch (IOException ignored) { // No entities? No problem + } + + return clipboard; + } + + private String convertEntityId(String id) { + switch(id) { + case "xp_orb": + return "experience_orb"; + case "xp_bottle": + return "experience_bottle"; + case "eye_of_ender_signal": + return "eye_of_ender"; + case "ender_crystal": + return "end_crystal"; + case "fireworks_rocket": + return "firework_rocket"; + case "commandblock_minecart": + return "command_block_minecart"; + case "snowman": + return "snow_golem"; + case "villager_golem": + return "iron_golem"; + case "evocation_fangs": + return "evoker_fangs"; + case "evocation_illager": + return "evoker"; + case "vindication_illager": + return "vindicator"; + case "illusion_illager": + return "illusioner"; + } + return id; + } + + @Override + public void close() throws IOException { + inputStream.close(); + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicReader.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicReader.java index 31aed23d3..a7661ed9b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicReader.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicReader.java @@ -42,15 +42,16 @@ import com.sk89q.jnbt.NamedTag; import com.sk89q.jnbt.ShortTag; import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.entity.BaseEntity; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.legacycompat.NBTCompatibilityHandler; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.block.BlockState; @@ -107,17 +108,22 @@ public class SpongeSchematicReader extends NBTSchematicReader { public Clipboard read(UUID uuid) throws IOException { return readVersion1(uuid); } - +// private Clipboard readVersion1(Map schematic) throws IOException { +// BlockVector3 origin; +// Region region; +// +// Map metadata = requireTag(schematic, "Metadata", CompoundTag.class).getValue(); +// } private int width, height, length; private int offsetX, offsetY, offsetZ; private char[] palette; - private Vector min; + private BlockVector3 min; private FaweClipboard fc; private FaweClipboard setupClipboard(int size, UUID uuid) { if (fc != null) { if (fc.getDimensions().getX() == 0) { - fc.setDimensions(new Vector(size, 1, 1)); + fc.setDimensions(BlockVector3.at(size, 1, 1)); } return fc; } @@ -129,11 +135,11 @@ public class SpongeSchematicReader extends NBTSchematicReader { return fc = new MemoryOptimizedClipboard(size, 1, 1); } } - + private Clipboard readVersion1(UUID uuid) throws IOException { width = height = length = offsetX = offsetY = offsetZ = Integer.MIN_VALUE; - final BlockArrayClipboard clipboard = new BlockArrayClipboard(new CuboidRegion(new Vector(0, 0, 0), new Vector(0, 0, 0)), fc); + final BlockArrayClipboard clipboard = new BlockArrayClipboard(new CuboidRegion(BlockVector3.at(0, 0, 0), BlockVector3.at(0, 0, 0)), fc); FastByteArrayOutputStream blocksOut = new FastByteArrayOutputStream(); FastByteArrayOutputStream biomesOut = new FastByteArrayOutputStream(); @@ -141,7 +147,7 @@ public class SpongeSchematicReader extends NBTSchematicReader { streamer.addReader("Schematic.Width", (BiConsumer) (i, v) -> width = v); streamer.addReader("Schematic.Height", (BiConsumer) (i, v) -> height = v); streamer.addReader("Schematic.Length", (BiConsumer) (i, v) -> length = v); - streamer.addReader("Schematic.Offset", (BiConsumer) (i, v) -> min = new BlockVector(v[0], v[1], v[2])); + streamer.addReader("Schematic.Offset", (BiConsumer) (i, v) -> min = BlockVector3.at(v[0], v[1], v[2])); streamer.addReader("Schematic.Metadata.WEOffsetX", (BiConsumer) (i, v) -> offsetX = v); streamer.addReader("Schematic.Metadata.WEOffsetY", (BiConsumer) (i, v) -> offsetY = v); streamer.addReader("Schematic.Metadata.WEOffsetZ", (BiConsumer) (i, v) -> offsetZ = v); @@ -210,15 +216,13 @@ public class SpongeSchematicReader extends NBTSchematicReader { }); streamer.readFully(); if (fc == null) setupClipboard(length * width * height, uuid); - fc.setDimensions(new Vector(width, height, length)); - Vector origin = min; + fc.setDimensions(BlockVector3.at(width, height, length)); + BlockVector3 origin = min; CuboidRegion region; if (offsetX != Integer.MIN_VALUE && offsetY != Integer.MIN_VALUE && offsetZ != Integer.MIN_VALUE) { - origin = origin.subtract(new Vector(offsetX, offsetY, offsetZ)); - region = new CuboidRegion(min, min.add(width, height, length).subtract(Vector.ONE)); - } else { - region = new CuboidRegion(min, min.add(width, height, length).subtract(Vector.ONE)); + origin = origin.subtract(BlockVector3.at(offsetX, offsetY, offsetZ)); } + region = new CuboidRegion(min, min.add(width, height, length).subtract(BlockVector3.ONE)); if (blocksOut.getSize() != 0) { try (FaweInputStream fis = new FaweInputStream(new LZ4BlockInputStream(new FastByteArraysInputStream(blocksOut.toByteArrays())))) { int volume = width * height * length; @@ -248,6 +252,7 @@ public class SpongeSchematicReader extends NBTSchematicReader { return clipboard; } + @Override public void close() throws IOException { inputStream.close(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicWriter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicWriter.java index 9956b9dbe..372c545a9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicWriter.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/SpongeSchematicWriter.java @@ -22,17 +22,25 @@ package com.sk89q.worldedit.extent.clipboard.io; import com.boydti.fawe.object.clipboard.FaweClipboard; import com.boydti.fawe.util.IOUtil; import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.DoubleTag; +import com.sk89q.jnbt.FloatTag; import com.sk89q.jnbt.IntArrayTag; +import com.sk89q.jnbt.ListTag; import com.sk89q.jnbt.NBTConstants; import com.sk89q.jnbt.NBTOutputStream; import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.entity.BaseEntity; +import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; +import com.sk89q.worldedit.math.Vector3; +import com.sk89q.worldedit.util.Location; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; import net.jpountz.lz4.LZ4BlockInputStream; import net.jpountz.lz4.LZ4BlockOutputStream; @@ -44,8 +52,10 @@ import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Vector; import static com.google.common.base.Preconditions.checkNotNull; @@ -75,9 +85,9 @@ public class SpongeSchematicWriter implements ClipboardWriter { public void write1(Clipboard clipboard) throws IOException { // metadata Region region = clipboard.getRegion(); - Vector origin = clipboard.getOrigin(); - BlockVector min = region.getMinimumPoint().toBlockVector(); - Vector offset = min.subtract(origin); + BlockVector3 origin = clipboard.getOrigin(); + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 offset = min.subtract(origin); int width = region.getWidth(); int height = region.getHeight(); int length = region.getLength(); @@ -124,24 +134,25 @@ public class SpongeSchematicWriter implements ClipboardWriter { FaweClipboard.BlockReader reader = new FaweClipboard.BlockReader() { @Override - public void run(int x, int y, int z, BlockState block) { + public > void run(int x, int y, int z, B block) { try { - CompoundTag tile = block.getNbtData(); - if (tile != null) { - Map values = tile.getValue(); + boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); + if (hasNbt) { + BaseBlock localBlock = (BaseBlock)block; + Map values = localBlock.getNbtData().getValue(); values.remove("id"); // Remove 'id' if it exists. We want 'Id' // Positions are kept in NBT, we don't want that. values.remove("x"); values.remove("y"); values.remove("z"); - if (!values.containsKey("Id")) values.put("Id", new StringTag(block.getNbtId())); + if (!values.containsKey("Id")) values.put("Id", new StringTag(localBlock.getNbtId())); values.put("Pos", new IntArrayTag(new int[]{ x, y, z })); numTiles[0]++; - tilesOut.writeTagPayload(tile); + tilesOut.writeTagPayload(localBlock.getNbtData()); } int ordinal = block.getOrdinal(); char value = palette[ordinal]; @@ -163,8 +174,8 @@ public class SpongeSchematicWriter implements ClipboardWriter { if (clipboard instanceof BlockArrayClipboard) { ((BlockArrayClipboard) clipboard).IMP.forEach(reader, true); } else { - for (Vector pt : region) { - BlockState block = clipboard.getBlock(pt); + for (BlockVector3 pt : region) { + BaseBlock block = clipboard.getFullBlock(pt); int x = pt.getBlockX() - min.getBlockX(); int y = pt.getBlockY() - min.getBlockY(); int z = pt.getBlockZ() - min.getBlockY(); @@ -201,9 +212,54 @@ public class SpongeSchematicWriter implements ClipboardWriter { } else { out.writeNamedEmptyList("TileEntities"); } + + + // Entities + List entities = new ArrayList(); + for (Entity entity : clipboard.getEntities()) { + BaseEntity state = entity.getState(); + + if (state != null) { + Map values = new HashMap(); + + // Put NBT provided data + CompoundTag rawTag = state.getNbtData(); + if (rawTag != null) { + values.putAll(rawTag.getValue()); + } + + // Store our location data, overwriting any + values.put("id", new StringTag(state.getType().getId())); + values.put("Pos", writeVector(entity.getLocation(), "Pos")); + values.put("Rotation", writeRotation(entity.getLocation(), "Rotation")); + + CompoundTag entityTag = new CompoundTag(values); + entities.add(entityTag); + } + } + if (entities.isEmpty()) { + out.writeNamedEmptyList("Entities"); + } else { + out.writeNamedTag("Entities", new ListTag(CompoundTag.class, entities)); + } }); } + private static Tag writeVector(Vector3 vector, String name) { + List list = new ArrayList(); + list.add(new DoubleTag(vector.getX())); + list.add(new DoubleTag(vector.getY())); + list.add(new DoubleTag(vector.getZ())); + return new ListTag(DoubleTag.class, list); + } + + private static Tag writeRotation(Location location, String name) { + List list = new ArrayList(); + list.add(new FloatTag(location.getYaw())); + list.add(new FloatTag(location.getPitch())); + return new ListTag(FloatTag.class, list); + } + @Override public void close() throws IOException { outputStream.close(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/NBTCompatibilityHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/NBTCompatibilityHandler.java index 16a60c80d..ede6aaaac 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/NBTCompatibilityHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/NBTCompatibilityHandler.java @@ -20,11 +20,12 @@ package com.sk89q.worldedit.extent.clipboard.io.legacycompat; import com.sk89q.jnbt.Tag; +import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import java.util.Map; public interface NBTCompatibilityHandler { - boolean isAffectedBlock(BlockStateHolder block); - void updateNBT(BlockStateHolder block, Map values); + > boolean isAffectedBlock(B block); + > void updateNBT(B block, Map values); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/SignCompatibilityHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/SignCompatibilityHandler.java index ae2d5f055..af78a4d36 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/SignCompatibilityHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/clipboard/io/legacycompat/SignCompatibilityHandler.java @@ -26,19 +26,21 @@ import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; +import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; import java.util.Map; public class SignCompatibilityHandler implements NBTCompatibilityHandler { + @Override - public boolean isAffectedBlock(BlockStateHolder block) { + public > boolean isAffectedBlock(B block) { return block.getBlockType() == BlockTypes.SIGN || block.getBlockType() == BlockTypes.WALL_SIGN; } @Override - public void updateNBT(BlockStateHolder block, Map values) { + public > void updateNBT(B block, Map values) { for (int i = 0; i < 4; ++i) { String key = "Text" + (i + 1); Tag value = values.get(key); 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 85bbe66a5..04ec91136 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/inventory/BlockBagExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/inventory/BlockBagExtent.java @@ -1,10 +1,14 @@ package com.sk89q.worldedit.extent.inventory; import com.boydti.fawe.object.exception.FaweException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.extent.AbstractDelegateExtent; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; @@ -82,32 +86,37 @@ public class BlockBagExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector pos, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 pos, B block) throws WorldEditException { return setBlock(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ(), block); } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { - BlockType type = block.getBlockType(); - if (!type.getMaterial().isAir()) { - try { - blockBag.fetchPlacedBlock(block.toImmutableState()); - } catch (UnplaceableBlockException e) { - throw new FaweException.FaweBlockBagException(); - } catch (BlockBagException e) { - missingBlocks[type.getInternalId()]++; - throw new FaweException.FaweBlockBagException(); - } - } - if (mine) { + public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { + if(blockBag != null) { BlockStateHolder lazyBlock = getExtent().getLazyBlock(x, y, z); BlockType fromType = lazyBlock.getBlockType(); - if (!fromType.getMaterial().isAir()) { - try { - blockBag.storeDroppedBlock(fromType.getDefaultState()); - } catch (BlockBagException ignored) { - } - } + if(!block.getBlockType().equals(fromType)) { + BlockType type = block.getBlockType(); + if (!type.getMaterial().isAir()) { + try { + blockBag.fetchPlacedBlock(block.toImmutableState()); + } catch (UnplaceableBlockException e) { + throw new FaweException.FaweBlockBagException(); + } catch (BlockBagException e) { + missingBlocks[type.getInternalId()]++; + throw new FaweException.FaweBlockBagException(); + } + } + if (mine) { + + if (!fromType.getMaterial().isAir()) { + try { + blockBag.storeDroppedBlock(fromType.getDefaultState()); + } catch (BlockBagException ignored) { + } + } + } + } } return getExtent().setBlock(x, y, z, block); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/logging/AbstractLoggingExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/logging/AbstractLoggingExtent.java index 2037be7e2..83bc2a9e3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/logging/AbstractLoggingExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/logging/AbstractLoggingExtent.java @@ -19,11 +19,11 @@ package com.sk89q.worldedit.extent.logging; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -47,11 +47,11 @@ public abstract class AbstractLoggingExtent extends AbstractDelegateExtent { * @param position the position * @param newBlock the new block to replace the old one */ - protected void onBlockChange(Vector position, BlockStateHolder newBlock) { + protected void onBlockChange(BlockVector3 position, BlockStateHolder newBlock) { } @Override - public final boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 position, B block) throws WorldEditException { onBlockChange(position, block); return super.setBlock(position, block); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/reorder/ChunkBatchingExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/reorder/ChunkBatchingExtent.java new file mode 100644 index 000000000..6a2686483 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/reorder/ChunkBatchingExtent.java @@ -0,0 +1,118 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extent.reorder; + +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.extent.AbstractDelegateExtent; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.function.operation.RunContext; +import com.sk89q.worldedit.function.operation.SetLocatedBlocks; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.util.collection.LocatedBlockList; +import com.sk89q.worldedit.world.block.BlockStateHolder; + +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.SortedMap; +import java.util.TreeMap; + +/** + * A special extent that batches changes into Minecraft chunks. This helps + * improve the speed of setting the blocks, since chunks do not need to be + * loaded repeatedly, however it does take more memory due to caching the + * blocks. + */ +public class ChunkBatchingExtent extends AbstractDelegateExtent { + + /** + * Comparator optimized for sorting chunks by the region file they reside + * in. This allows for file caches to be used while loading the chunk. + */ + private static final Comparator REGION_OPTIMIZED_SORT = + Comparator.comparing((BlockVector2 vec) -> vec.divide(32), BlockVector2.COMPARING_GRID_ARRANGEMENT) + .thenComparing(BlockVector2.COMPARING_GRID_ARRANGEMENT); + + private final SortedMap batches = new TreeMap<>(REGION_OPTIMIZED_SORT); + private boolean enabled; + + public ChunkBatchingExtent(Extent extent) { + this(extent, true); + } + + public ChunkBatchingExtent(Extent extent, boolean enabled) { + super(extent); + this.enabled = enabled; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + @Override + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { + if (!enabled) { + return getExtent().setBlock(location, block); + } + BlockVector2 chunkPos = BlockVector2.at(location.getBlockX() >> 4, location.getBlockZ() >> 4); + batches.computeIfAbsent(chunkPos, k -> new LocatedBlockList()).add(location, block); + return true; + } + + @Override + protected Operation commitBefore() { + if (!enabled) { + return null; + } + return new Operation() { + + // we get modified between create/resume -- only create this on resume to prevent CME + private Iterator batchIterator; + + @Override + public Operation resume(RunContext run) throws WorldEditException { + if (batchIterator == null) { + batchIterator = batches.values().iterator(); + } + if (!batchIterator.hasNext()) { + return null; + } + new SetLocatedBlocks(getExtent(), batchIterator.next()).resume(run); + batchIterator.remove(); + return this; + } + + @Override + public void cancel() { + } + + @Override + public void addStatusMessages(List messages) { + } + }; + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/reorder/MultiStageReorder.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/reorder/MultiStageReorder.java index a60fa79ec..918a03fbf 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/reorder/MultiStageReorder.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/reorder/MultiStageReorder.java @@ -19,24 +19,25 @@ package com.sk89q.worldedit.extent.reorder; -import com.google.common.collect.Iterators; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.blocks.Blocks; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.function.operation.BlockMapEntryPlacer; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.OperationQueue; import com.sk89q.worldedit.function.operation.RunContext; +import com.sk89q.worldedit.function.operation.SetLocatedBlocks; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.registry.state.Property; -import com.sk89q.worldedit.util.collection.TupleArrayList; +import com.sk89q.worldedit.util.LocatedBlock; +import com.sk89q.worldedit.util.collection.LocatedBlockList; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockCategories; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; +import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; @@ -50,11 +51,21 @@ import java.util.Set; */ public class MultiStageReorder extends AbstractDelegateExtent implements ReorderingExtent { - private TupleArrayList stage1 = new TupleArrayList<>(); - private TupleArrayList stage2 = new TupleArrayList<>(); - private TupleArrayList stage3 = new TupleArrayList<>(); + private static final int STAGE_COUNT = 4; + + private List stages = new ArrayList<>(); + private boolean enabled; + /** + * Create a new instance when the re-ordering is enabled. + * + * @param extent the extent + */ + public MultiStageReorder(Extent extent) { + this(extent, true); + } + /** * Create a new instance. * @@ -64,15 +75,10 @@ public class MultiStageReorder extends AbstractDelegateExtent implements Reorder public MultiStageReorder(Extent extent, boolean enabled) { super(extent); this.enabled = enabled; - } - /** - * Create a new instance when the re-ordering is enabled. - * - * @param extent the extent - */ - public MultiStageReorder(Extent extent) { - this(extent, true); + for (int i = 0; i < STAGE_COUNT; ++i) { + stages.add(new LocatedBlockList()); + } } /** @@ -93,62 +99,84 @@ public class MultiStageReorder extends AbstractDelegateExtent implements Reorder this.enabled = enabled; } - @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { - BlockStateHolder existing = getBlock(location); + public boolean commitRequired() { + return stages.stream().anyMatch(stage -> stage.size() > 0); + } + /** + * Gets the stage priority of the block. + * + * @param block The block + * @return The priority + */ + public > int getPlacementPriority(B block) { + if (Blocks.shouldPlaceLate(block.getBlockType())) { + return 1; + } else if (Blocks.shouldPlaceLast(block.getBlockType())) { + // Place torches, etc. last + return 2; + } else if (Blocks.shouldPlaceFinal(block.getBlockType())) { + // Place signs, reed, etc even later + return 3; + } else { + return 0; + } + } + + @Override + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { if (!enabled) { return super.setBlock(location, block); } - if (Blocks.shouldPlaceLast(block.getBlockType())) { - // Place torches, etc. last - stage2.put(location.toBlockVector(), block); - return !existing.equalsFuzzy(block); - } else if (Blocks.shouldPlaceFinal(block.getBlockType())) { - // Place signs, reed, etc even later - stage3.put(location.toBlockVector(), block); - return !existing.equalsFuzzy(block); - } else if (Blocks.shouldPlaceLast(existing.getBlockType())) { + BlockState existing = getBlock(location); + int priority = getPlacementPriority(block); + int srcPriority = getPlacementPriority(existing); + + if (srcPriority == 1 || srcPriority == 2) { // Destroy torches, etc. first super.setBlock(location, BlockTypes.AIR.getDefaultState()); return super.setBlock(location, block); - } else { - stage1.put(location.toBlockVector(), block); - return !existing.equalsFuzzy(block); } + + stages.get(priority).add(location, block); + return !existing.equalsFuzzy(block); } @Override public Operation commitBefore() { - return new OperationQueue( - new BlockMapEntryPlacer( - getExtent(), - Iterators.concat(stage1.iterator(), stage2.iterator())), - new Stage3Committer()); + List operations = new ArrayList<>(); + for (int i = 0; i < stages.size() - 1; ++i) { + operations.add(new SetLocatedBlocks(getExtent(), stages.get(i))); + } + + operations.add(new FinalStageCommitter()); + return new OperationQueue(operations); } - private class Stage3Committer implements Operation { + private class FinalStageCommitter implements Operation { + private Extent extent = getExtent(); + + private final Set blocks = new HashSet<>(); + private final Map blockTypes = new HashMap<>(); + + public FinalStageCommitter() { + for (LocatedBlock entry : stages.get(stages.size() - 1)) { + final BlockVector3 pt = entry.getLocation(); + blocks.add(pt); + blockTypes.put(pt, entry.getBlock()); + } + } @Override public Operation resume(RunContext run) throws WorldEditException { - Extent extent = getExtent(); - - final Set blocks = new HashSet<>(); - final Map blockTypes = new HashMap<>(); - for (Map.Entry entry : stage3) { - final BlockVector pt = entry.getKey(); - blocks.add(pt); - blockTypes.put(pt, entry.getValue()); - } - while (!blocks.isEmpty()) { - BlockVector current = blocks.iterator().next(); + BlockVector3 current = blocks.iterator().next(); if (!blocks.contains(current)) { continue; } - final Deque walked = new LinkedList<>(); + final Deque walked = new LinkedList<>(); while (true) { walked.addFirst(current); @@ -161,13 +189,13 @@ public class MultiStageReorder extends AbstractDelegateExtent implements Reorder Property halfProperty = blockStateHolder.getBlockType().getProperty("half"); if (blockStateHolder.getState(halfProperty).equals("lower")) { // Deal with lower door halves being attached to the floor AND the upper half - BlockVector upperBlock = current.add(0, 1, 0).toBlockVector(); + BlockVector3 upperBlock = current.add(0, 1, 0); if (blocks.contains(upperBlock) && !walked.contains(upperBlock)) { walked.addFirst(upperBlock); } } } else if (BlockCategories.RAILS.contains(blockStateHolder.getBlockType())) { - BlockVector lowerBlock = current.add(0, -1, 0).toBlockVector(); + BlockVector3 lowerBlock = current.add(0, -1, 0); if (blocks.contains(lowerBlock) && !walked.contains(lowerBlock)) { walked.addFirst(lowerBlock); } @@ -191,17 +219,20 @@ public class MultiStageReorder extends AbstractDelegateExtent implements Reorder } } - for (BlockVector pt : walked) { + for (BlockVector3 pt : walked) { extent.setBlock(pt, blockTypes.get(pt)); blocks.remove(pt); } } - stage1.clear(); - stage2.clear(); - stage3.clear(); + if (blocks.isEmpty()) { + for (LocatedBlockList stage : stages) { + stage.clear(); + } + return null; + } - return null; + return this; } @Override 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 30cfb8034..93a526377 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/transform/BlockTransformExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/transform/BlockTransformExtent.java @@ -1,265 +1,277 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + package com.sk89q.worldedit.extent.transform; +import static com.google.common.base.Preconditions.checkNotNull; + import com.boydti.fawe.object.extent.ResettableExtent; import com.boydti.fawe.util.ReflectionUtils; +import com.google.common.collect.Sets; import com.sk89q.jnbt.ByteTag; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.internal.helper.MCDirections; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.math.transform.Transform; -import com.sk89q.worldedit.registry.state.AbstractProperty; +import com.sk89q.worldedit.registry.state.BooleanProperty; import com.sk89q.worldedit.registry.state.DirectionalProperty; +import com.sk89q.worldedit.registry.state.EnumProperty; +import com.sk89q.worldedit.registry.state.IntegerProperty; +import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockTypes; -import javax.annotation.Nullable; -import java.util.Arrays; -import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.Set; +import java.util.stream.Collectors; + +import javax.annotation.Nullable; /** * Transforms blocks themselves (but not their position) according to a * given transform. */ public class BlockTransformExtent extends ResettableExtent { - private Transform transform; - private Transform transformInverse; - private int[] BLOCK_ROTATION_BITMASK; - private int[][] BLOCK_TRANSFORM; - private int[][] BLOCK_TRANSFORM_INVERSE; - private int[] ALL = new int[0]; + private Transform transform; + + public BlockTransformExtent(Extent parent) { this(parent, new AffineTransform()); } - public BlockTransformExtent(Extent parent, Transform transform) { - super(parent); + /** + * Create a new instance. + * + * @param extent the extent + */ + public BlockTransformExtent(Extent extent, Transform transform) { + super(extent); + checkNotNull(transform); this.transform = transform; - this.transformInverse = this.transform.inverse(); - cache(); } - private List getDirections(AbstractProperty property) { - if (property instanceof DirectionalProperty) { - DirectionalProperty directional = (DirectionalProperty) property; - directional.getValues(); - } else { - switch (property.getKey()) { - case HALF: + /** + * Get the transform. + * + * @return the transform + */ + public Transform getTransform() { + return transform; + } + + /** + * Set the transform + * @param affine + */ + public void setTransform(Transform affine) { + this.transform = affine; + } - case ROTATION: - case AXIS: + /** + * Transform a block without making a copy. + * + * @param block the block + * @param reverse true to transform in the opposite direction + * @return the same block + */ + protected > T transformBlock(T block, boolean reverse) { + return transform(block, reverse ? transform.inverse() : transform); + } + + @Override + public BlockState getLazyBlock(BlockVector3 position) { + return transformBlock(super.getLazyBlock(position), false).toImmutableState(); + } + + @Override + public BlockState getLazyBlock(int x, int y, int z) { + return transformBlock(super.getLazyBlock(x, y, z), false).toImmutableState(); + } - case FACING: + @Override + public BlockState getBlock(BlockVector3 position) { + return transformBlock(super.getBlock(position), false).toImmutableState(); + } - case SHAPE: + @Override + public BaseBlock getFullBlock(BlockVector3 position) { + return transformBlock(super.getFullBlock(position), false); + } + + @Override + public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { + return super.setBlock(x, y, z, transformBlock(block, true)); + } - case NORTH: - case EAST: - case SOUTH: - case WEST: + @Override + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { + return super.setBlock(location, transformBlock(block, true)); + } + + private static final Set directionNames = Sets.newHashSet("north", "south", "east", "west"); + + + + /** + * Transform the given block using the given transform. + * + *

The provided block is not modified.

+ * + * @param block the block + * @param transform the transform + * @return the same block + */ + public static > B transform(B block, Transform transform) { + checkNotNull(block); + checkNotNull(transform); + B result = block; + List> properties = block.getBlockType().getProperties(); + + for (Property property : properties) { + if (property instanceof DirectionalProperty) { + DirectionalProperty dirProp = (DirectionalProperty) property; + Direction value = (Direction) block.getState(property); + if (value != null) { + Vector3 newValue = getNewStateValue(dirProp.getValues(), transform, value.toVector()); + if (newValue != null) { + result = result.with(dirProp, Direction.findClosest(newValue, Direction.Flag.ALL)); + } + } + } else if (property instanceof EnumProperty) { + EnumProperty enumProp = (EnumProperty) property; + if (property.getName().equals("axis")) { + // We have an axis - this is something we can do the rotations to :sunglasses: + Direction value = null; + switch ((String) block.getState(property)) { + case "x": + value = Direction.EAST; + break; + case "y": + value = Direction.UP; + break; + case "z": + value = Direction.NORTH; + break; + } + if (value != null) { + Vector3 newValue = getNewStateValue(Direction.valuesOf(Direction.Flag.UPRIGHT | Direction.Flag.CARDINAL), transform, value.toVector()); + if (newValue != null) { + String axis = null; + Direction newDir = Direction.findClosest(newValue, Direction.Flag.UPRIGHT | Direction.Flag.CARDINAL); + if (newDir == Direction.NORTH || newDir == Direction.SOUTH) { + axis = "z"; + } else if (newDir == Direction.EAST || newDir == Direction.WEST) { + axis = "x"; + } else if (newDir == Direction.UP || newDir == Direction.DOWN) { + axis = "y"; + } + if (axis != null) { + result = result.with(enumProp, axis); + } + } + } + } + } else if (property instanceof IntegerProperty) { + IntegerProperty intProp = (IntegerProperty) property; + if (property.getName().equals("rotation")) { + if (intProp.getValues().size() == 16) { + Optional direction = Direction.fromRotationIndex(block.getState(intProp)); + int horizontalFlags = Direction.Flag.CARDINAL | Direction.Flag.ORDINAL | Direction.Flag.SECONDARY_ORDINAL; + if (direction.isPresent()) { + Vector3 vec = getNewStateValue(Direction.valuesOf(horizontalFlags), transform, direction.get().toVector()); + if (vec != null) { + OptionalInt newRotation = Direction.findClosest(vec, horizontalFlags).toRotationIndex(); + if (newRotation.isPresent()) { + result = result.with(intProp, newRotation.getAsInt()); + } + } + } + } + } } } - return null; + + List directionalProperties = properties.stream() + .filter(prop -> prop instanceof BooleanProperty) + .filter(prop -> directionNames.contains(prop.getName())) + .filter(property -> (Boolean) block.getState(property)) + .map(Property::getName) + .map(String::toUpperCase) + .map(Direction::valueOf) + .map(dir -> Direction.findClosest(transform.apply(dir.toVector()), Direction.Flag.CARDINAL)) + .filter(Objects::nonNull) + .map(Direction::name) + .map(String::toLowerCase) + .collect(Collectors.toList()); + + if (directionalProperties.size() > 0) { + for (String directionName : directionNames) { + result = result.with(block.getBlockType().getProperty(directionName), directionalProperties.contains(directionName)); + } + } + return result; } + /** + * Get the new value with the transformed direction. + * + * @param allowedStates the allowed states + * @param transform the transform + * @param oldDirection the old direction to transform + * @return a new state or null if none could be found + */ @Nullable - private static Integer getNewStateIndex(Transform transform, List directions, int oldIndex) { - Direction oldDirection = directions.get(oldIndex); - Vector oldVector = oldDirection.toVector(); - Vector newVector = transform.apply(oldVector).subtract(transform.apply(Vector.ZERO)).normalize(); - int newIndex = oldIndex; - double closest = oldVector.toVector().normalize().dot(newVector); + private static Vector3 getNewStateValue(List allowedStates, Transform transform, Vector3 oldDirection) { + Vector3 newDirection = transform.apply(oldDirection).subtract(transform.apply(Vector3.ZERO)).normalize(); + Vector3 newValue = null; + double closest = -2; boolean found = false; - for (int i = 0; i < directions.size(); i++) { - Direction v = directions.get(i); - double dot = v.toVector().normalize().dot(newVector); - if (dot > closest) { + for (Direction v : allowedStates) { + double dot = v.toVector().normalize().dot(newDirection); + if (dot >= closest) { closest = dot; - newIndex = i; + newValue = v.toVector(); found = true; } } if (found) { - return newIndex; + return newValue; } else { return null; } } - private void cache() { - BLOCK_ROTATION_BITMASK = new int[BlockTypes.size()]; - BLOCK_TRANSFORM = new int[BlockTypes.size()][]; - BLOCK_TRANSFORM_INVERSE = new int[BlockTypes.size()][]; - outer: - for (int i = 0; i < BLOCK_TRANSFORM.length; i++) { - BLOCK_TRANSFORM[i] = ALL; - BLOCK_TRANSFORM_INVERSE[i] = ALL; - BlockTypes type = BlockTypes.get(i); - int bitMask = 0; - for (AbstractProperty property : (Collection) type.getProperties()) { - Collection directions = getDirections(property); - if (directions != null) { - BLOCK_TRANSFORM[i] = null; - BLOCK_TRANSFORM_INVERSE[i] = null; - bitMask |= property.getBitMask(); - } - } - if (bitMask != 0) { - BLOCK_ROTATION_BITMASK[i] = bitMask; - } - } - } - - @Override - public ResettableExtent setExtent(Extent extent) { - return super.setExtent(extent); - } - - public Transform getTransform() { - return transform; - } - - public void setTransform(Transform affine) { - this.transform = affine; - this.transformInverse = this.transform.inverse(); - cache(); - } - - private final BlockState transform(BlockState state, int[][] transformArray, Transform transform) { - int typeId = state.getInternalBlockTypeId(); - int[] arr = transformArray[typeId]; - if (arr == ALL) return state; - if (arr == null) { - arr = transformArray[typeId] = new int[state.getBlockType().getMaxStateId() + 1]; - Arrays.fill(arr, -1); - } - int mask = BLOCK_ROTATION_BITMASK[typeId]; - int internalId = state.getInternalId(); - - int maskedId = internalId & mask; - int newMaskedId = arr[maskedId]; - if (newMaskedId != -1) { - return BlockState.getFromInternalId(newMaskedId | (internalId & (~mask))); - } - newMaskedId = state.getInternalId(); - - BlockTypes type = state.getBlockType(); - for (AbstractProperty property : (Collection) type.getProperties()) { - List directions = getDirections(property); - if (directions != null) { - Integer newIndex = getNewStateIndex(transform, directions, property.getIndex(state.getInternalId())); - if (newIndex != null) { - newMaskedId = property.modifyIndex(newMaskedId, newIndex); - } - } - } - arr[maskedId] = newMaskedId & mask; - return BlockState.getFromInternalId(newMaskedId); - } - - public final BlockState transformFast(BlockState block) { - BlockState transformed = transform(block, BLOCK_TRANSFORM, transform); - if (block.hasNbtData()) { - CompoundTag tag = block.getNbtData(); - if (tag.containsKey("Rot")) { - int rot = tag.asInt("Rot"); - - Direction direction = MCDirections.fromRotation(rot); - - if (direction != null) { - Vector applyAbsolute = transform.apply(direction.toVector()); - Vector applyOrigin = transform.apply(Vector.ZERO); - applyAbsolute.mutX(applyAbsolute.getX() - applyOrigin.getX()); - applyAbsolute.mutY(applyAbsolute.getY() - applyOrigin.getY()); - applyAbsolute.mutZ(applyAbsolute.getZ() - applyOrigin.getZ()); - - Direction newDirection = Direction.findClosest(applyAbsolute, Direction.Flag.CARDINAL | Direction.Flag.ORDINAL | Direction.Flag.SECONDARY_ORDINAL); - - if (newDirection != null) { - Map values = ReflectionUtils.getMap(tag.getValue()); - values.put("Rot", new ByteTag((byte) MCDirections.toRotation(newDirection))); - } - } - transformed = new BaseBlock(transformed, tag); - } - } - return transformed; - } - - public final BlockState transformFastInverse(BlockState block) { - BlockState transformed = transform(block, BLOCK_TRANSFORM_INVERSE, transformInverse); - if (block.hasNbtData()) { - CompoundTag tag = block.getNbtData(); - if (tag.containsKey("Rot")) { - int rot = tag.asInt("Rot"); - - Direction direction = MCDirections.fromRotation(rot); - - if (direction != null) { - Vector applyAbsolute = transformInverse.apply(direction.toVector()); - Vector applyOrigin = transformInverse.apply(Vector.ZERO); - applyAbsolute.mutX(applyAbsolute.getX() - applyOrigin.getX()); - applyAbsolute.mutY(applyAbsolute.getY() - applyOrigin.getY()); - applyAbsolute.mutZ(applyAbsolute.getZ() - applyOrigin.getZ()); - - Direction newDirection = Direction.findClosest(applyAbsolute, Direction.Flag.CARDINAL | Direction.Flag.ORDINAL | Direction.Flag.SECONDARY_ORDINAL); - - if (newDirection != null) { - Map values = ReflectionUtils.getMap(tag.getValue()); - values.put("Rot", new ByteTag((byte) MCDirections.toRotation(newDirection))); - } - } - } - transformed = new BaseBlock(transformed, tag); - } - return transformed; - } - - @Override - public BlockState getLazyBlock(int x, int y, int z) { - return transformFast(super.getLazyBlock(x, y, z)); - } - - @Override - public BlockState getLazyBlock(Vector position) { - return transformFast(super.getLazyBlock(position)); - } - - @Override - public BlockState getBlock(Vector position) { - return transformFast(super.getBlock(position)); - } - - @Override - public BaseBiome getBiome(Vector2D position) { - return super.getBiome(position); - } - - @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { - return super.setBlock(x, y, z, transformFastInverse((BlockState) block)); - } - - - @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { - return super.setBlock(location, transformFastInverse((BlockState) block)); - } - - } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/validation/BlockChangeLimiter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/validation/BlockChangeLimiter.java index a25477235..637ccd821 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/validation/BlockChangeLimiter.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/validation/BlockChangeLimiter.java @@ -22,7 +22,7 @@ package com.sk89q.worldedit.extent.validation; import static com.google.common.base.Preconditions.checkArgument; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; @@ -77,7 +77,7 @@ public class BlockChangeLimiter extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { if (limit >= 0) { if (count >= limit) { throw new MaxChangedBlocksException(limit); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/validation/DataValidatorExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/validation/DataValidatorExtent.java index ffb2b175a..9bc9aaf43 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/validation/DataValidatorExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/validation/DataValidatorExtent.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.extent.validation; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; @@ -49,7 +49,7 @@ public class DataValidatorExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { final int y = location.getBlockY(); final BlockType type = block.getBlockType(); if (y < 0 || y > world.getMaxY()) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/BlockQuirkExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/BlockQuirkExtent.java index 25591defb..9631f53ae 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/BlockQuirkExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/BlockQuirkExtent.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.extent.world; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; @@ -51,7 +51,7 @@ public class BlockQuirkExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector position, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 position, B block) throws WorldEditException { BlockType existing = getExtent().getBlock(position).getBlockType(); if (existing.getMaterial().hasContainer()) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/ChunkLoadingExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/ChunkLoadingExtent.java index 845276a58..31ff6f840 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/ChunkLoadingExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/ChunkLoadingExtent.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.extent.world; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; @@ -61,8 +61,11 @@ public class ChunkLoadingExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { world.checkLoadedChunk(location); + if (enabled) { + world.checkLoadedChunk(location); + } return super.setBlock(location, block); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/FastModeExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/FastModeExtent.java index 9ad839a32..a83a4c615 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/FastModeExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/FastModeExtent.java @@ -21,16 +21,18 @@ package com.sk89q.worldedit.extent.world; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.BlockVector2D; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.RunContext; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockTypes; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Set; @@ -40,8 +42,10 @@ import java.util.Set; public class FastModeExtent extends AbstractDelegateExtent { private final World world; - private final Set dirtyChunks = new HashSet<>(); + private final Set positions = new HashSet<>(); + private final Set dirtyChunks = new HashSet<>(); private boolean enabled = true; + private boolean postEditSimulation; /** * Create a new instance with fast mode enabled. @@ -63,6 +67,9 @@ public class FastModeExtent extends AbstractDelegateExtent { checkNotNull(world); this.world = world; this.enabled = enabled; + if (enabled) { + this.postEditSimulation = true; + } } /** @@ -83,16 +90,36 @@ public class FastModeExtent extends AbstractDelegateExtent { this.enabled = enabled; } + public boolean isPostEditSimulationEnabled() { + return postEditSimulation; + } + + public void setPostEditSimulationEnabled(boolean enabled) { + this.postEditSimulation = enabled; + } + @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { - if (enabled) { - dirtyChunks.add(new BlockVector2D(location.getBlockX() >> 4, location.getBlockZ() >> 4)); - return world.setBlock(location, block, false); + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { + if (enabled || postEditSimulation) { + dirtyChunks.add(BlockVector2.at(location.getBlockX() >> 4, location.getBlockZ() >> 4)); + + if (world.setBlock(location, block, false)) { + if (postEditSimulation) { + positions.add(location); + } + return true; + } + + return false; } else { return world.setBlock(location, block, true); } } + public boolean commitRequired() { + return !dirtyChunks.isEmpty() || !positions.isEmpty(); + } + @Override protected Operation commitBefore() { return new Operation() { @@ -101,6 +128,18 @@ public class FastModeExtent extends AbstractDelegateExtent { if (!dirtyChunks.isEmpty()) { world.fixAfterFastMode(dirtyChunks); } + + if (postEditSimulation) { + Iterator positionIterator = positions.iterator(); + while (run.shouldContinue() && positionIterator.hasNext()) { + BlockVector3 position = positionIterator.next(); + world.notifyAndLightBlock(position, BlockTypes.AIR.getDefaultState()); + positionIterator.remove(); + } + + return !positions.isEmpty() ? this : null; + } + return null; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/SurvivalModeExtent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/SurvivalModeExtent.java index 85a2eccdd..d935716c2 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/SurvivalModeExtent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extent/world/SurvivalModeExtent.java @@ -19,11 +19,12 @@ package com.sk89q.worldedit.extent.world; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -80,7 +81,7 @@ public class SurvivalModeExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(Vector location, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(BlockVector3 location, B block) throws WorldEditException { if (toolUse && block.getBlockType().getMaterial().isAir()) { world.simulateBlockMine(location); return true; @@ -90,9 +91,9 @@ public class SurvivalModeExtent extends AbstractDelegateExtent { } @Override - public boolean setBlock(int x, int y, int z, BlockStateHolder block) throws WorldEditException { + public > boolean setBlock(int x, int y, int z, B block) throws WorldEditException { if (toolUse && block.getBlockType().getMaterial().isAir()) { - world.simulateBlockMine(MutableBlockVector.get(x, y, z)); + world.simulateBlockMine(BlockVector3.at(x, y, z)); return true; } else { return super.setBlock(x, y, z, block); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/CombinedRegionFunction.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/CombinedRegionFunction.java index be8602416..d266025b2 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/CombinedRegionFunction.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/CombinedRegionFunction.java @@ -19,8 +19,10 @@ package com.sk89q.worldedit.function; -import com.sk89q.worldedit.Vector; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.math.BlockVector3; import java.util.*; @@ -95,7 +97,7 @@ public class CombinedRegionFunction implements RegionFunction { } @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { boolean ret = false; for (RegionFunction function : functions) { if (function.apply(position)) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/FlatRegionFunction.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/FlatRegionFunction.java index 41144fc8f..fa8e0f9da 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/FlatRegionFunction.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/FlatRegionFunction.java @@ -19,8 +19,8 @@ package com.sk89q.worldedit.function; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.regions.FlatRegion; /** @@ -36,6 +36,6 @@ public interface FlatRegionFunction { * @return true if something was changed * @throws WorldEditException thrown on an error */ - boolean apply(Vector2D position) throws WorldEditException; + boolean apply(BlockVector2 position) throws WorldEditException; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/FlatRegionMaskingFilter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/FlatRegionMaskingFilter.java index ff287632c..acafd1f61 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/FlatRegionMaskingFilter.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/FlatRegionMaskingFilter.java @@ -21,12 +21,12 @@ package com.sk89q.worldedit.function; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.mask.Mask2D; /** - * Passes calls to {@link #apply(com.sk89q.worldedit.Vector2D)} to the + * Passes calls to {@link #apply(BlockVector2)} to the * delegate {@link com.sk89q.worldedit.function.FlatRegionFunction} if they * match the given mask. */ @@ -50,7 +50,7 @@ public class FlatRegionMaskingFilter implements FlatRegionFunction { } @Override - public boolean apply(Vector2D position) throws WorldEditException { + public boolean apply(BlockVector2 position) throws WorldEditException { return mask.test(position) && function.apply(position); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/GroundFunction.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/GroundFunction.java index 2b14b57b2..630952678 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/GroundFunction.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/GroundFunction.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.mask.Mask; @@ -76,12 +76,12 @@ public class GroundFunction implements LayerFunction { } @Override - public boolean isGround(Vector position) { + public boolean isGround(BlockVector3 position) { return mask.test(position); } @Override - public boolean apply(Vector position, int depth) throws WorldEditException { + public boolean apply(BlockVector3 position, int depth) throws WorldEditException { if (depth == 0) { if (function.apply(position)) { affected++; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/LayerFunction.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/LayerFunction.java index bd9acb7cb..8d82f016f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/LayerFunction.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/LayerFunction.java @@ -19,9 +19,9 @@ package com.sk89q.worldedit.function; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.visitor.LayerVisitor; +import com.sk89q.worldedit.math.BlockVector3; /** * A function that takes a position and a depth. @@ -35,7 +35,7 @@ public interface LayerFunction { * @param position return whether the given block is the ground * @return true if the search should stop */ - boolean isGround(Vector position); + boolean isGround(BlockVector3 position); /** * Apply the function to the given position. @@ -48,5 +48,5 @@ public interface LayerFunction { * @return true whether this method should be called for further layers * @throws WorldEditException thrown on an error */ - boolean apply(Vector position, int depth) throws WorldEditException; + boolean apply(BlockVector3 position, int depth) throws WorldEditException; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionFunction.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionFunction.java index 91276d237..332565e35 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionFunction.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionFunction.java @@ -19,8 +19,8 @@ package com.sk89q.worldedit.function; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.math.BlockVector3; /** * Performs a function on points in a region. @@ -34,6 +34,6 @@ public interface RegionFunction { * @return true if something was changed * @throws WorldEditException thrown on an error */ - boolean apply(Vector position) throws WorldEditException; + boolean apply(BlockVector3 position) throws WorldEditException; } 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 7ce1c437b..00ce92250 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 @@ -19,9 +19,9 @@ package com.sk89q.worldedit.function; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; @@ -53,7 +53,7 @@ public class RegionMaskTestFunction implements RegionFunction { } @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { if (mask.test(position)) { return pass.apply(position); } else { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionMaskingFilter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionMaskingFilter.java index 673d411d2..9feb385b5 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionMaskingFilter.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/RegionMaskingFilter.java @@ -21,12 +21,12 @@ package com.sk89q.worldedit.function; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.mask.Mask; /** - * Passes calls to {@link #apply(com.sk89q.worldedit.Vector)} to the + * Passes calls to {@link #apply(BlockVector3)} to the * delegate {@link com.sk89q.worldedit.function.RegionFunction} if they * match the given mask. */ @@ -49,7 +49,7 @@ public class RegionMaskingFilter implements RegionFunction { } @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { return mask.test(position) && function.apply(position); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/biome/BiomeReplace.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/biome/BiomeReplace.java index ac5fdf98d..500408700 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/biome/BiomeReplace.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/biome/BiomeReplace.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function.biome; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.FlatRegionFunction; @@ -49,7 +49,7 @@ public class BiomeReplace implements FlatRegionFunction { } @Override - public boolean apply(Vector2D position) throws WorldEditException { + public boolean apply(BlockVector2 position) throws WorldEditException { return extent.setBiome(position, biome); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/BlockDistributionCounter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/BlockDistributionCounter.java new file mode 100644 index 000000000..cf5b47f48 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/BlockDistributionCounter.java @@ -0,0 +1,76 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.function.block; + +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.util.Countable; +import com.sk89q.worldedit.world.block.BlockState; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class BlockDistributionCounter implements RegionFunction { + + private Extent extent; + private boolean separateStates; + + private List> distribution = new ArrayList<>(); + private Map> map = new HashMap<>(); + + public BlockDistributionCounter(Extent extent, boolean separateStates) { + this.extent = extent; + this.separateStates = separateStates; + } + + @Override + public boolean apply(BlockVector3 position) throws WorldEditException { + BlockState blk = extent.getBlock(position); + if (!separateStates) { + blk = blk.getBlockType().getDefaultState(); + } + + if (map.containsKey(blk)) { + map.get(blk).increment(); + } else { + Countable c = new Countable<>(blk, 1); + map.put(blk, c); + distribution.add(c); + } + + return true; + } + + /** + * Gets the distribution list. + * + * @return The distribution + */ + public List> getDistribution() { + Collections.sort(distribution); + Collections.reverse(distribution); + return this.distribution; + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/BlockReplace.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/BlockReplace.java index 6a21edc94..b6581203e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/BlockReplace.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/BlockReplace.java @@ -19,12 +19,14 @@ package com.sk89q.worldedit.function.block; -import com.sk89q.worldedit.Vector; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.pattern.Pattern; - +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; import static com.google.common.base.Preconditions.checkNotNull; @@ -50,8 +52,8 @@ public class BlockReplace implements RegionFunction { } @Override - public boolean apply(Vector position) throws WorldEditException { - return pattern.apply(extent, position, position); + public boolean apply(BlockVector3 position) throws WorldEditException { + return pattern.apply(extent, position, position); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/Counter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/Counter.java index 8c5cd8001..06b5284bd 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/Counter.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/Counter.java @@ -19,17 +19,18 @@ package com.sk89q.worldedit.function.block; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.math.BlockVector3; /** - * Keeps a count of the number of times that {@link #apply(Vector)} is called. + * Keeps a count of the number of times that {@link #apply(BlockVector3)} is + * called. */ - public class Counter implements RegionFunction { +public class Counter implements RegionFunction { private int count; - + /** * Returns the number of blocks that have been counted. * @@ -40,7 +41,7 @@ import com.sk89q.worldedit.function.RegionFunction; } @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { count++; return false; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/ExtentBlockCopy.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/ExtentBlockCopy.java index 2ec5af6be..34a4671c9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/ExtentBlockCopy.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/ExtentBlockCopy.java @@ -23,13 +23,17 @@ import com.boydti.fawe.util.ReflectionUtils; import com.sk89q.jnbt.ByteTag; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.jnbt.CompoundTagBuilder; +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.internal.helper.MCDirections; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.Direction.Flag; @@ -39,6 +43,7 @@ import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; +//import com.sk89q.worldedit.world.block.BaseBlock; /** * Copies blocks from one extent to another. @@ -47,8 +52,8 @@ public class ExtentBlockCopy implements RegionFunction { private final Extent source; private final Extent destination; - private final Vector from; - private final Vector to; + private final BlockVector3 from; + private final BlockVector3 to; private final Transform transform; /** @@ -60,7 +65,7 @@ public class ExtentBlockCopy implements RegionFunction { * @param to the destination offset * @param transform a transform to apply to positions (after source offset, before destination offset) */ - public ExtentBlockCopy(Extent source, Vector from, Extent destination, Vector to, Transform transform) { + public ExtentBlockCopy(Extent source, BlockVector3 from, Extent destination, BlockVector3 to, Transform transform) { checkNotNull(source); checkNotNull(from); checkNotNull(destination); @@ -74,13 +79,12 @@ public class ExtentBlockCopy implements RegionFunction { } @Override - public boolean apply(Vector position) throws WorldEditException { - Vector orig = position.subtract(from); - Vector transformed = transform.apply(orig); + public boolean apply(BlockVector3 position) throws WorldEditException { + BlockVector3 orig = position.subtract(from); + BlockVector3 transformed = transform.apply(orig.toVector3()).toBlockPoint(); // Apply transformations to NBT data if necessary - BlockStateHolder block = transformNbtData(source.getBlock(position)); - + BaseBlock block = transformNbtData(source.getFullBlock(position)); return destination.setBlock(transformed.add(to), block); } @@ -91,8 +95,9 @@ public class ExtentBlockCopy implements RegionFunction { * @param state the existing state * @return a new state or the existing one */ - private BlockState transformNbtData(BlockState state) { + private BaseBlock transformNbtData(BaseBlock state) { CompoundTag tag = state.getNbtData(); + if (tag != null) { // Handle blocks which store their rotation in NBT if (tag.containsKey("Rot")) { @@ -101,21 +106,20 @@ public class ExtentBlockCopy implements RegionFunction { Direction direction = MCDirections.fromRotation(rot); if (direction != null) { - Vector applyAbsolute = transform.apply(direction.toVector()); - Vector applyOrigin = transform.apply(Vector.ZERO); - applyAbsolute.mutX(applyAbsolute.getX() - applyOrigin.getX()); - applyAbsolute.mutY(applyAbsolute.getY() - applyOrigin.getY()); - applyAbsolute.mutZ(applyAbsolute.getZ() - applyOrigin.getZ()); - - Direction newDirection = Direction.findClosest(applyAbsolute, Flag.CARDINAL | Flag.ORDINAL | Flag.SECONDARY_ORDINAL); + Vector3 vector = transform.apply(direction.toVector()).subtract(transform.apply(Vector3.ZERO)).normalize(); + Direction newDirection = Direction.findClosest(vector, Flag.CARDINAL | Flag.ORDINAL | Flag.SECONDARY_ORDINAL); if (newDirection != null) { - Map values = ReflectionUtils.getMap(tag.getValue()); - values.put("Rot", new ByteTag((byte) MCDirections.toRotation(newDirection))); + CompoundTagBuilder builder = tag.createBuilder(); + + builder.putByte("Rot", (byte) MCDirections.toRotation(newDirection)); + + return state.toBaseBlock(builder.build()); } } } } + return state; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/Naturalizer.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/Naturalizer.java index 62997afab..14d3124b4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/Naturalizer.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/block/Naturalizer.java @@ -21,7 +21,6 @@ package com.sk89q.worldedit.function.block; import com.google.common.collect.Sets; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.mask.BlockTypeMask; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -32,6 +31,8 @@ import com.sk89q.worldedit.function.mask.BlockTypeMask; import com.sk89q.worldedit.function.mask.Mask; import static com.google.common.base.Preconditions.checkNotNull; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BlockTypes; /** * Makes a layer of grass on top, three layers of dirt below, and smooth stone @@ -65,12 +66,12 @@ public class Naturalizer implements LayerFunction { } @Override - public boolean isGround(Vector position) { + public boolean isGround(BlockVector3 position) { return mask.test(position); } @Override - public boolean apply(Vector position, int depth) throws WorldEditException { + public boolean apply(BlockVector3 position, int depth) throws WorldEditException { if (mask.test(position)) { affected++; switch (depth) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/entity/ExtentEntityCopy.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/entity/ExtentEntityCopy.java index e49c3c142..fca42f721 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/entity/ExtentEntityCopy.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/entity/ExtentEntityCopy.java @@ -26,16 +26,18 @@ import com.sk89q.jnbt.FloatTag; import com.sk89q.jnbt.IntTag; import com.sk89q.jnbt.ListTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.EntityFunction; import com.sk89q.worldedit.internal.helper.MCDirections; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.Direction.Flag; +import com.sk89q.worldedit.world.entity.EntityTypes; import com.sk89q.worldedit.util.Location; import java.util.Arrays; import java.util.Map; @@ -50,8 +52,8 @@ import static com.google.common.base.Preconditions.checkNotNull; public class ExtentEntityCopy implements EntityFunction { private final Extent destination; - private final Vector from; - private final Vector to; + private final Vector3 from; + private final Vector3 to; private final Transform transform; private boolean removing; @@ -63,7 +65,7 @@ public class ExtentEntityCopy implements EntityFunction { * @param to the destination position * @param transform the transformation to apply to both position and orientation */ - public ExtentEntityCopy(Vector from, Extent destination, Vector to, Transform transform) { + public ExtentEntityCopy(Vector3 from, Extent destination, Vector3 to, Transform transform) { checkNotNull(from); checkNotNull(destination); checkNotNull(to); @@ -95,21 +97,35 @@ public class ExtentEntityCopy implements EntityFunction { @Override public boolean apply(Entity entity) throws WorldEditException { BaseEntity state = entity.getState(); - if (state != null) { + if (state != null && state.getType() != EntityTypes.PLAYER) { Location newLocation; Location location = entity.getLocation(); - Vector pivot = from.round().add(0.5, 0.5, 0.5); - Vector newPosition = transform.apply(location.toVector().subtract(pivot)); - Vector newDirection; - if (transform.isIdentity()) { - newDirection = entity.getLocation().getDirection(); - newLocation = new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection); - } else { - newDirection = new Vector(transform.apply(location.getDirection())).subtract(transform.apply(Vector.ZERO)).normalize(); - newLocation = new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection); - state = transformNbtData(state); - } +//<<<<<<< HEAD +// Vector pivot = from.round().add(0.5, 0.5, 0.5); +// Vector newPosition = transform.apply(location.subtract(pivot)); +// Vector newDirection; +// if (transform.isIdentity()) { +// newDirection = entity.getLocation().getDirection(); +// newLocation = new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection); +// } else { +// newDirection = new Vector(transform.apply(location.getDirection())).subtract(transform.apply(Vector.ZERO)).normalize(); +// newLocation = new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection); +// state = transformNbtData(state); +// } +//======= + Vector3 pivot = from.round().add(0.5, 0.5, 0.5); + Vector3 newPosition = transform.apply(location.subtract(pivot)); + Vector3 newDirection; + + newDirection = transform.isIdentity() ? + entity.getLocation().getDirection() + : transform.apply(location.getDirection()).subtract(transform.apply(Vector3.ZERO)).normalize(); + newLocation = new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection); + + // Some entities store their position data in NBT + state = transformNbtData(state); +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner boolean success = destination.createEntity(newLocation, state) != null; @@ -147,9 +163,14 @@ public class ExtentEntityCopy implements EntityFunction { boolean hasFacing = tag.containsKey("Facing"); if (hasTilePosition) { +//<<<<<<< HEAD changed = true; - Vector tilePosition = new Vector(tag.asInt("TileX"), tag.asInt("TileY"), tag.asInt("TileZ")); - Vector newTilePosition = transform.apply(tilePosition.subtract(from)).add(to); +// Vector tilePosition = new Vector(tag.asInt("TileX"), tag.asInt("TileY"), tag.asInt("TileZ")); +// Vector newTilePosition = transform.apply(tilePosition.subtract(from)).add(to); +//======= + Vector3 tilePosition = Vector3.at(tag.asInt("TileX"), tag.asInt("TileY"), tag.asInt("TileZ")); + BlockVector3 newTilePosition = transform.apply(tilePosition.subtract(from)).add(to).toBlockPoint(); +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner values.put("TileX", new IntTag(newTilePosition.getBlockX())); values.put("TileY", new IntTag(newTilePosition.getBlockY())); @@ -168,7 +189,7 @@ public class ExtentEntityCopy implements EntityFunction { Direction direction = MCDirections.fromHanging(d); if (direction != null) { - Vector vector = transform.apply(direction.toVector()).subtract(transform.apply(Vector.ZERO)).normalize(); + Vector3 vector = transform.apply(direction.toVector()).subtract(transform.apply(Vector3.ZERO)).normalize(); Direction newDirection = Direction.findClosest(vector, Flag.CARDINAL); if (newDirection != null) { @@ -188,10 +209,10 @@ public class ExtentEntityCopy implements EntityFunction { double pitch = Math.toRadians(rotation.getFloat(1)); double xz = Math.cos(pitch); - Vector direction = new Vector(-xz * Math.sin(yaw), -Math.sin(pitch), xz * Math.cos(yaw)); + Vector3 direction = Vector3.at(-xz * Math.sin(yaw), -Math.sin(pitch), xz * Math.cos(yaw)); direction = transform.apply(direction); - FloatTag yawTag = new FloatTag(direction.toYaw()); - FloatTag pitchTag = new FloatTag(direction.toPitch()); + FloatTag yawTag = new FloatTag((float)direction.toYaw()); + FloatTag pitchTag = new FloatTag((float)direction.toPitch()); values.put("Rotation", new ListTag(FloatTag.class, Arrays.asList(yawTag, pitchTag))); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/factory/Deform.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/factory/Deform.java index d80ad4570..ac52933be 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/factory/Deform.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/factory/Deform.java @@ -23,7 +23,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.sk89q.worldedit.util.GuavaUtil.firstNonNull; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.NullExtent; @@ -32,6 +31,7 @@ import com.sk89q.worldedit.function.EditContext; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.RunContext; import com.sk89q.worldedit.internal.expression.ExpressionException; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.NullRegion; import com.sk89q.worldedit.regions.Region; @@ -43,7 +43,7 @@ public class Deform implements Contextual { private Region region; private String expression; private Mode mode = Mode.UNIT_CUBE; - private Vector offset = new Vector(); + private Vector3 offset = Vector3.ZERO; public Deform(String expression) { this(new NullExtent(), new NullRegion(), expression); @@ -104,11 +104,11 @@ public class Deform implements Contextual { this.mode = mode; } - public Vector getOffset() { + public Vector3 getOffset() { return offset; } - public void setOffset(Vector offset) { + public void setOffset(Vector3 offset) { checkNotNull(offset, "offset"); this.offset = offset; } @@ -120,31 +120,31 @@ public class Deform implements Contextual { @Override public Operation createFromContext(final EditContext context) { - final Vector zero; - Vector unit; + final Vector3 zero; + Vector3 unit; Region region = firstNonNull(context.getRegion(), this.region); switch (mode) { case UNIT_CUBE: - final Vector min = region.getMinimumPoint(); - final Vector max = region.getMaximumPoint(); + final Vector3 min = region.getMinimumPoint().toVector3(); + final Vector3 max = region.getMaximumPoint().toVector3(); zero = max.add(min).multiply(0.5); unit = max.subtract(zero); - if (unit.getX() == 0) unit = unit.setX(1.0); - if (unit.getY() == 0) unit = unit.setY(1.0); - if (unit.getZ() == 0) unit = unit.setZ(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); break; case RAW_COORD: - zero = Vector.ZERO; - unit = Vector.ONE; + zero = Vector3.ZERO; + unit = Vector3.ONE; break; case OFFSET: default: zero = offset; - unit = Vector.ONE; + unit = Vector3.ONE; } return new DeformOperation(context.getDestination(), region, zero, unit, expression); @@ -153,11 +153,11 @@ public class Deform implements Contextual { private static final class DeformOperation implements Operation { private final Extent destination; private final Region region; - private final Vector zero; - private final Vector unit; + private final Vector3 zero; + private final Vector3 unit; private final String expression; - private DeformOperation(Extent destination, Region region, Vector zero, Vector unit, String expression) { + private DeformOperation(Extent destination, Region region, Vector3 zero, Vector3 unit, String expression) { this.destination = destination; this.region = region; this.zero = zero; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/FloraGenerator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/FloraGenerator.java index 3f6265de7..e1ab41b03 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/FloraGenerator.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/FloraGenerator.java @@ -20,13 +20,15 @@ package com.sk89q.worldedit.function.generator; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.RandomPattern; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockTypes; /** @@ -103,8 +105,8 @@ public class FloraGenerator implements RegionFunction { } @Override - public boolean apply(Vector position) throws WorldEditException { - BlockStateHolder block = editSession.getBlock(position); + public boolean apply(BlockVector3 position) throws WorldEditException { + BlockState block = editSession.getBlock(position); if (block.getBlockType() == BlockTypes.GRASS_BLOCK) { editSession.setBlock(position.add(0, 1, 0), temperatePattern.apply(position)); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/ForestGenerator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/ForestGenerator.java index 4446ccf81..e0332d550 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/ForestGenerator.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/generator/ForestGenerator.java @@ -20,11 +20,11 @@ package com.sk89q.worldedit.function.generator; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.util.TreeGenerator; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; @@ -49,8 +49,8 @@ public class ForestGenerator implements RegionFunction { } @Override - public boolean apply(Vector position) throws WorldEditException { - BlockStateHolder block = editSession.getBlock(position); + public boolean apply(BlockVector3 position) throws WorldEditException { + BlockState block = editSession.getBlock(position); BlockType t = block.getBlockType(); if (t == BlockTypes.GRASS_BLOCK || t == BlockTypes.DIRT) { 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 d6bba6356..0cc3266df 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 @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function.generator; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.pattern.BlockPattern; @@ -84,12 +84,12 @@ public class GardenPatchGenerator implements RegionFunction { * @param basePos the base position * @param pos the vine position */ - private void placeVine(Vector basePos, Vector pos) throws MaxChangedBlocksException { + private void placeVine(BlockVector3 basePos, BlockVector3 pos) throws MaxChangedBlocksException { if (pos.distance(basePos) > 4) return; if (!editSession.getBlock(pos).getBlockType().getMaterial().isAir()) return; for (int i = -1; i > -3; --i) { - Vector testPos = pos.add(0, i, 0); + BlockVector3 testPos = pos.add(0, i, 0); if (editSession.getBlock(testPos).getBlockType().getMaterial().isAir()) { pos = testPos; } else { @@ -102,7 +102,7 @@ public class GardenPatchGenerator implements RegionFunction { int t = random.nextInt(4); int h = random.nextInt(3) - 1; - Vector p; + BlockVector3 p; BlockStateHolder log = BlockTypes.OAK_LOG.getDefaultState(); @@ -158,7 +158,7 @@ public class GardenPatchGenerator implements RegionFunction { } @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { if (!editSession.getBlock(position).getBlockType().getMaterial().isAir()) { position = position.add(0, 1, 0); } @@ -198,7 +198,7 @@ public class GardenPatchGenerator implements RegionFunction { * @return if block was changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - private static boolean setBlockIfAir(EditSession session, Vector position, BlockStateHolder block) throws MaxChangedBlocksException { + private static > boolean setBlockIfAir(EditSession session, BlockVector3 position, B block) throws MaxChangedBlocksException { return session.getBlock(position).getBlockType().getMaterial().isAir() && session.setBlock(position, block); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BiomeMask2D.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BiomeMask2D.java index d7bf33c8a..c590a211a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BiomeMask2D.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BiomeMask2D.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function.mask; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.world.biome.BaseBiome; @@ -90,7 +90,7 @@ public class BiomeMask2D extends AbstractMask2D { } @Override - public boolean test(Vector2D vector) { + public boolean test(BlockVector2 vector) { BaseBiome biome = extent.getBiome(vector); return biomes.contains(biome); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockCategoryMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockCategoryMask.java index fae7888a0..625d8b781 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockCategoryMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BlockCategoryMask.java @@ -21,8 +21,8 @@ package com.sk89q.worldedit.function.mask; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockCategory; import javax.annotation.Nullable; @@ -41,7 +41,7 @@ public class BlockCategoryMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return category.contains(getExtent().getBlock(vector)); } 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 f3fa24a92..c3530fd47 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 @@ -3,16 +3,22 @@ package com.sk89q.worldedit.function.mask; import com.boydti.fawe.object.collection.FastBitSet; import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.StringMan; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.extent.NullExtent; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.registry.state.AbstractProperty; import com.sk89q.worldedit.registry.state.Property; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; import javax.annotation.Nullable; import java.util.ArrayList; @@ -59,7 +65,7 @@ public class BlockMask extends AbstractExtentMask { for (int i = 0; i < bitSets.length; i++) { if (bitSets[i] != null) { long[] set = bitSets[i]; - BlockTypes type = BlockTypes.get(i); + BlockType type = BlockTypes.get(i); if (set == ALL) { strings.add(type.getId()); } else { @@ -123,12 +129,18 @@ public class BlockMask extends AbstractExtentMask { return mask; } } +// public boolean test(BlockVector3 vector) { +// BlockStateHolder block = getExtent().getBlock(vector); +// for (BlockStateHolder testBlock : blocks) { +// if (testBlock.equalsFuzzy(block)) { +// return true; + private Mask getOptimizedMask(BlockType type, long[] bitSet) { boolean single = true; int and = type.getInternalId(); List properties = type.getProperties(); - for (AbstractProperty prop : (List) type.getProperties()) { + for (AbstractProperty prop : (List>) type.getProperties()) { List values = prop.getValues(); int numSet = 0; for (int i = 0; i < values.size(); i++) { @@ -218,7 +230,7 @@ public class BlockMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { BlockStateHolder block = getExtent().getBlock(vector); long[] bitSet = bitSets[block.getInternalBlockTypeId()]; if (bitSet == null) return 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 cc4bf7b19..7c3d86caf 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 @@ -90,15 +90,15 @@ public class BlockMaskBuilder { charSequence.setString(input); charSequence.setSubstring(0, propStart); - BlockTypes type = null; - List blockTypeList = null; + BlockType type = null; + List blockTypeList = null; if (StringMan.isAlphanumericUnd(charSequence)) { type = BlockTypes.parse(charSequence.toString()); add(type); } else { String regex = charSequence.toString(); blockTypeList = new ArrayList<>(); - for (BlockTypes myType : BlockTypes.values) { + for (BlockType myType : BlockTypes.values) { if (myType.getId().matches(regex)) { blockTypeList.add(myType); add(myType); @@ -135,14 +135,14 @@ public class BlockMaskBuilder { filtered = filterRegexOrOperator(type, key, operator, charSequence); } else { - for (BlockTypes myType : blockTypeList) { + for (BlockType myType : blockTypeList) { filtered |= filterRegexOrOperator(myType, key, operator, charSequence); } } if (!filtered) { String value = charSequence.toString(); final PropertyKey fKey = key; - Collection types = type != null ? Collections.singleton(type) : blockTypeList; + Collection types = type != null ? Collections.singleton(type) : blockTypeList; throw new SuggestInputParseException("No value for " + input, input, () -> { HashSet values = new HashSet<>(); types.forEach(t -> { @@ -206,7 +206,7 @@ public class BlockMaskBuilder { if (StringMan.isAlphanumericUnd(input)) { add(BlockTypes.parse(input)); } else { - for (BlockTypes myType : BlockTypes.values) { + for (BlockType myType : BlockTypes.values) { if (myType.getId().matches(input)) { add(myType); } @@ -225,7 +225,7 @@ public class BlockMaskBuilder { return (states == BlockMask.ALL || FastBitSet.get(states, localI)); } - private void suggest(String input, String property, Collection finalTypes) throws InputParseException { + private void suggest(String input, String property, Collection finalTypes) throws InputParseException { throw new SuggestInputParseException(input + " does not have: " + property, input, () -> { Set keys = new HashSet<>(); finalTypes.forEach(t -> t.getProperties().stream().forEach(p -> keys.add(p.getKey()))); @@ -346,7 +346,7 @@ public class BlockMaskBuilder { bitSets[i] = null; continue; } - List properties = (List) type.getProperties(); + List> properties = (List>) type.getProperties(); for (AbstractProperty prop : properties) { List values = prop.getValues(); for (int j = 0; j < values.size(); j++) { @@ -425,7 +425,7 @@ public class BlockMaskBuilder { if (!typePredicate.test(type)) { continue; } - for (AbstractProperty prop : (List) type.getProperties()) { + for (AbstractProperty prop : (List>) type.getProperties()) { List values = prop.getValues(); for (int j = 0; j < values.size(); j++) { int localI = j << prop.getBitOffset() >> BlockTypes.BIT_OFFSET; @@ -533,7 +533,7 @@ public class BlockMaskBuilder { } int set = 0; int clear = 0; - for (AbstractProperty prop : (List) type.getProperties()) { + for (AbstractProperty prop : (List>) type.getProperties()) { List values = prop.getValues(); for (int j = 0; j < values.size(); j++) { int localI = j << prop.getBitOffset() >> BlockTypes.BIT_OFFSET; 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 bc69a9846..c15c3d354 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 @@ -1,7 +1,9 @@ package com.sk89q.worldedit.function.mask; -import com.sk89q.worldedit.Vector; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; @@ -9,6 +11,8 @@ import java.util.Collection; import java.util.HashSet; import java.util.Set; +import javax.annotation.Nullable; + import static com.google.common.base.Preconditions.checkNotNull; public class BlockTypeMask extends AbstractExtentMask { @@ -75,7 +79,16 @@ public class BlockTypeMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return types[getExtent().getBlockType(vector).getInternalId()]; } +// public boolean test(BlockVector3 vector) { +// return blocks.contains(getExtent().getBlock(vector).getBlockType()); +// } + + @Nullable + @Override + public Mask2D toMask2D() { + return null; + } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BoundedHeightMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BoundedHeightMask.java index 3622926e3..2f72d5a1d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BoundedHeightMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/BoundedHeightMask.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function.mask; import static com.google.common.base.Preconditions.checkArgument; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import javax.annotation.Nullable; @@ -47,7 +47,7 @@ public class BoundedHeightMask extends AbstractMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return vector.getY() >= minY && vector.getY() <= maxY; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExistingBlockMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExistingBlockMask.java index e57a28b41..4c2b44ce9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExistingBlockMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExistingBlockMask.java @@ -19,7 +19,7 @@ package com.sk89q.worldedit.function.mask; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.extent.Extent; import javax.annotation.Nullable; @@ -40,8 +40,8 @@ public class ExistingBlockMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { - return !getExtent().getBlock(vector).getMaterial().isAir(); + public boolean test(BlockVector3 vector) { + return !getExtent().getBlock(vector).getBlockType().getMaterial().isAir(); } @Nullable diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExpressionMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExpressionMask.java index d662e0fa3..2c4017559 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExpressionMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExpressionMask.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function.mask; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.ExpressionException; import com.sk89q.worldedit.internal.expression.runtime.EvaluationException; @@ -61,10 +61,10 @@ public class ExpressionMask extends AbstractMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { try { if (expression.getEnvironment() instanceof WorldEditExpressionEnvironment) { - ((WorldEditExpressionEnvironment) expression.getEnvironment()).setCurrentBlock(vector); + ((WorldEditExpressionEnvironment) expression.getEnvironment()).setCurrentBlock(vector.toVector3()); } return expression.evaluate(vector.getX(), vector.getY(), vector.getZ()) > 0; } catch (EvaluationException e) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExpressionMask2D.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExpressionMask2D.java index 2b4031ca8..0afefab0c 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExpressionMask2D.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/ExpressionMask2D.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function.mask; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.ExpressionException; import com.sk89q.worldedit.internal.expression.runtime.EvaluationException; @@ -52,7 +52,7 @@ public class ExpressionMask2D extends AbstractMask2D { } @Override - public boolean test(Vector2D vector) { + public boolean test(BlockVector2 vector) { try { return expression.evaluate(vector.getX(), 0, vector.getZ()) > 0; } catch (EvaluationException e) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/InverseMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/InverseMask.java index 675a9b4f8..3999dfc44 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/InverseMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/InverseMask.java @@ -1,9 +1,9 @@ package com.sk89q.worldedit.function.mask; -import com.sk89q.worldedit.Vector; - import javax.annotation.Nullable; +import com.sk89q.worldedit.math.BlockVector3; + public class InverseMask extends AbstractMask { private final Mask mask; @@ -12,7 +12,7 @@ public class InverseMask extends AbstractMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return !mask.test(vector); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Mask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Mask.java index 81c5385fc..38b3783b1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Mask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Mask.java @@ -20,8 +20,8 @@ package com.sk89q.worldedit.function.mask; import com.sk89q.minecraft.util.commands.Link; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.command.UtilityCommands; +import com.sk89q.worldedit.math.BlockVector3; import javax.annotation.Nullable; @@ -40,7 +40,7 @@ public interface Mask { * @param vector the vector to test * @return true if the criteria is met */ - boolean test(Vector vector); + boolean test(BlockVector3 vector); /** * Get the 2D version of this mask if one exists. diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Mask2D.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Mask2D.java index ad48dcb5e..3e48a0e9a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Mask2D.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Mask2D.java @@ -19,7 +19,7 @@ package com.sk89q.worldedit.function.mask; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; /** * Tests whether a given vector meets a criteria. @@ -32,6 +32,6 @@ public interface Mask2D { * @param vector the vector to test * @return true if the criteria is met */ - boolean test(Vector2D vector); + boolean test(BlockVector2 vector); } 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 e9173e349..9321ec5cd 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 @@ -20,7 +20,10 @@ package com.sk89q.worldedit.function.mask; import com.google.common.base.Function; -import com.sk89q.worldedit.Vector; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.math.BlockVector3; import javax.annotation.Nullable; import java.util.*; @@ -166,8 +169,12 @@ public class MaskIntersection extends AbstractMask { } @Override - public boolean test(Vector vector) { - for (Mask mask : masksArray) { + public boolean test(BlockVector3 vector) { + if (masks.isEmpty()) { + return false; + } + + for (Mask mask : masks) { if (!mask.test(vector)) { return false; } @@ -178,7 +185,7 @@ public class MaskIntersection extends AbstractMask { @Nullable @Override public Mask2D toMask2D() { - List mask2dList = new ArrayList(); + List mask2dList = new ArrayList<>(); for (Mask mask : masks) { Mask2D mask2d = mask.toMask2D(); if (mask2d != null) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskIntersection2D.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskIntersection2D.java index 07e43be38..eec35eab9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskIntersection2D.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskIntersection2D.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function.mask; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import java.util.Arrays; import java.util.Collection; @@ -83,7 +83,7 @@ public class MaskIntersection2D implements Mask2D { } @Override - public boolean test(Vector2D vector) { + public boolean test(BlockVector2 vector) { if (masks.isEmpty()) { return false; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskUnion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskUnion.java index aa0141cb4..a3ac57a03 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskUnion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskUnion.java @@ -20,7 +20,8 @@ package com.sk89q.worldedit.function.mask; import com.google.common.base.Function; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; + import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -58,7 +59,7 @@ public class MaskUnion extends MaskIntersection { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { for (Mask mask : getMasksArray()) { if (mask.test(vector)) { return true; @@ -71,7 +72,7 @@ public class MaskUnion extends MaskIntersection { @Nullable @Override public Mask2D toMask2D() { - List mask2dList = new ArrayList(); + List mask2dList = new ArrayList<>(); for (Mask mask : getMasks()) { Mask2D mask2d = mask.toMask2D(); if (mask2d != null) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskUnion2D.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskUnion2D.java index 099dc9a05..678fcbdd4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskUnion2D.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/MaskUnion2D.java @@ -19,7 +19,7 @@ package com.sk89q.worldedit.function.mask; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import java.util.Collection; @@ -47,7 +47,7 @@ public class MaskUnion2D extends MaskIntersection2D { } @Override - public boolean test(Vector2D vector) { + public boolean test(BlockVector2 vector) { Collection masks = getMasks(); for (Mask2D mask : masks) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Masks.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Masks.java index c51da2073..4279d2fde 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Masks.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/Masks.java @@ -1,7 +1,9 @@ package com.sk89q.worldedit.function.mask; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import javax.annotation.Nullable; @@ -50,8 +52,36 @@ public final class Masks { * @param finalMask the mask * @return a new mask */ +//<<<<<<< HEAD public static Mask negate(final Mask finalMask) { return finalMask.inverse(); +//======= +// public static Mask negate(final Mask mask) { +// if (mask instanceof AlwaysTrue) { +// return ALWAYS_FALSE; +// } else if (mask instanceof AlwaysFalse) { +// return ALWAYS_TRUE; +// } +// +// checkNotNull(mask); +// return new AbstractMask() { +// @Override +// public boolean test(BlockVector3 vector) { +// return !mask.test(vector); +// } +// +// @Nullable +// @Override +// public Mask2D toMask2D() { +// Mask2D mask2d = mask.toMask2D(); +// if (mask2d != null) { +// return negate(mask2d); +// } else { +// return null; +// } +// } +// }; +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner } /** @@ -70,7 +100,7 @@ public final class Masks { checkNotNull(mask); return new AbstractMask2D() { @Override - public boolean test(Vector2D vector) { + public boolean test(BlockVector2 vector) { return !mask.test(vector); } }; @@ -85,8 +115,8 @@ public final class Masks { public static Mask asMask(final Mask2D mask) { return new AbstractMask() { @Override - public boolean test(Vector vector) { - return mask.test(vector.toVector2D()); + public boolean test(BlockVector3 vector) { + return mask.test(vector.toBlockVector2()); } @Nullable @@ -99,12 +129,12 @@ public final class Masks { protected static class AlwaysTrue implements Mask, Mask2D { @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return true; } @Override - public boolean test(Vector2D vector) { + public boolean test(BlockVector2 vector) { return true; } @@ -127,12 +157,12 @@ public final class Masks { protected static class AlwaysFalse implements Mask, Mask2D { @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return false; } @Override - public boolean test(Vector2D vector) { + public boolean test(BlockVector2 vector) { return false; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/NoiseFilter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/NoiseFilter.java index 04c793bde..ee9b6e44d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/NoiseFilter.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/NoiseFilter.java @@ -22,7 +22,7 @@ package com.sk89q.worldedit.function.mask; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.noise.NoiseGenerator; import javax.annotation.Nullable; @@ -85,8 +85,8 @@ public class NoiseFilter extends AbstractMask { } @Override - public boolean test(Vector vector) { - return noiseGenerator.noise(vector) <= density; + public boolean test(BlockVector3 vector) { + return noiseGenerator.noise(vector.toVector3()) <= density; } @Nullable diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/NoiseFilter2D.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/NoiseFilter2D.java index fdcbcd59b..a64889f54 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/NoiseFilter2D.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/NoiseFilter2D.java @@ -22,7 +22,7 @@ package com.sk89q.worldedit.function.mask; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.noise.NoiseGenerator; /** @@ -83,8 +83,8 @@ public class NoiseFilter2D extends AbstractMask2D { } @Override - public boolean test(Vector2D pos) { - return noiseGenerator.noise(pos) <= density; + public boolean test(BlockVector2 pos) { + return noiseGenerator.noise(pos.toVector2()) <= density; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/OffsetMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/OffsetMask.java index 96d50a8a7..b5e149dd5 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/OffsetMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/OffsetMask.java @@ -1,7 +1,9 @@ package com.sk89q.worldedit.function.mask; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.math.BlockVector3; + import javax.annotation.Nullable; @@ -14,8 +16,7 @@ import static com.google.common.base.Preconditions.checkNotNull; public class OffsetMask extends AbstractMask { private Mask mask; - private Vector offset; - private MutableBlockVector mutable = new MutableBlockVector(); + private BlockVector3 offset; /** * Create a new instance. @@ -23,7 +24,7 @@ public class OffsetMask extends AbstractMask { * @param mask the mask * @param offset the offset */ - public OffsetMask(Mask mask, Vector offset) { + public OffsetMask(Mask mask, BlockVector3 offset) { checkNotNull(mask); checkNotNull(offset); this.mask = mask; @@ -54,7 +55,7 @@ public class OffsetMask extends AbstractMask { * * @return the offset */ - public Vector getOffset() { + public BlockVector3 getOffset() { return offset; } @@ -63,17 +64,14 @@ public class OffsetMask extends AbstractMask { * * @param offset the offset */ - public void setOffset(Vector offset) { + public void setOffset(BlockVector3 offset) { checkNotNull(offset); this.offset = offset; } @Override - public boolean test(Vector vector) { - mutable.mutX((vector.getX() + offset.getX())); - mutable.mutY((vector.getY() + offset.getY())); - mutable.mutZ((vector.getZ() + offset.getZ())); - return getMask().test(mutable); + public boolean test(BlockVector3 vector) { + return getMask().test(vector.add(offset)); } @Nullable @@ -81,7 +79,7 @@ public class OffsetMask extends AbstractMask { public Mask2D toMask2D() { Mask2D childMask = getMask().toMask2D(); if (childMask != null) { - return new OffsetMask2D(childMask, getOffset().toVector2D()); + return new OffsetMask2D(childMask, getOffset().toBlockVector2()); } else { return null; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/OffsetMask2D.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/OffsetMask2D.java index 74daead9d..94b595fdf 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/OffsetMask2D.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/OffsetMask2D.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function.mask; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; /** * Checks whether another mask tests true for a position that is offset @@ -30,7 +30,7 @@ import com.sk89q.worldedit.Vector2D; public class OffsetMask2D extends AbstractMask2D { private Mask2D mask; - private Vector2D offset; + private BlockVector2 offset; /** * Create a new instance. @@ -38,7 +38,7 @@ public class OffsetMask2D extends AbstractMask2D { * @param mask the mask * @param offset the offset */ - public OffsetMask2D(Mask2D mask, Vector2D offset) { + public OffsetMask2D(Mask2D mask, BlockVector2 offset) { checkNotNull(mask); checkNotNull(offset); this.mask = mask; @@ -69,7 +69,7 @@ public class OffsetMask2D extends AbstractMask2D { * * @return the offset */ - public Vector2D getOffset() { + public BlockVector2 getOffset() { return offset; } @@ -78,13 +78,13 @@ public class OffsetMask2D extends AbstractMask2D { * * @param offset the offset */ - public void setOffset(Vector2D offset) { + public void setOffset(BlockVector2 offset) { checkNotNull(offset); this.offset = offset; } @Override - public boolean test(Vector2D vector) { + public boolean test(BlockVector2 vector) { return getMask().test(vector.add(offset)); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/RegionMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/RegionMask.java index 7d2d78dfc..28df2c206 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/RegionMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/RegionMask.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function.mask; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import javax.annotation.Nullable; @@ -62,7 +62,7 @@ public class RegionMask extends AbstractMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return region.contains(vector); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockStateBitMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockStateBitMask.java index 30128f523..24da28c8f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockStateBitMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockStateBitMask.java @@ -1,7 +1,7 @@ package com.sk89q.worldedit.function.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; public class SingleBlockStateBitMask extends AbstractExtentMask { private final int bitMask; @@ -12,7 +12,7 @@ public class SingleBlockStateBitMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { int internalId = getExtent().getBlock(vector).getInternalId(); return (internalId & bitMask) == internalId; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockStateMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockStateMask.java index c92f9c86d..e8514dafc 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockStateMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockStateMask.java @@ -1,7 +1,7 @@ package com.sk89q.worldedit.function.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; @@ -18,7 +18,7 @@ public class SingleBlockStateMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return state.equals(getExtent().getBlock(vector)); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockTypeMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockTypeMask.java index 0c3a4aee5..2f26b1aed 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockTypeMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SingleBlockTypeMask.java @@ -1,7 +1,7 @@ package com.sk89q.worldedit.function.mask; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; @@ -15,7 +15,7 @@ public class SingleBlockTypeMask extends AbstractExtentMask { } @Override - public boolean test(Vector vector) { + public boolean test(BlockVector3 vector) { return getExtent().getBlockType(vector).getInternalId() == internalId; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SolidBlockMask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SolidBlockMask.java index 67b30b9cd..8ba70fc5d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SolidBlockMask.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/mask/SolidBlockMask.java @@ -1,8 +1,10 @@ package com.sk89q.worldedit.function.mask; -import com.sk89q.worldedit.blocks.BaseBlock; + +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.blocks.BlockType; +import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.world.block.BlockTypes; @@ -12,7 +14,7 @@ public class SolidBlockMask extends BlockTypeMask { public static boolean[] getTypes() { boolean[] types = new boolean[BlockTypes.size()]; - for (BlockTypes type : BlockTypes.values) { + for (BlockType type : BlockTypes.values) { types[type.getInternalId()] = type.getMaterial().isSolid(); } return types; @@ -21,6 +23,12 @@ public class SolidBlockMask extends BlockTypeMask { public SolidBlockMask(Extent extent) { super(extent, getTypes()); } + @Override + public boolean test(BlockVector3 vector) { + Extent extent = getExtent(); + BlockState block = extent.getBlock(vector); + return block.getBlockType().getMaterial().isMovementBlocker(); + } @Nullable @Override 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 16bf2aec5..464c892ba 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 @@ -1,10 +1,10 @@ package com.sk89q.worldedit.function.operation; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; @@ -16,11 +16,11 @@ public class BackwardsExtentBlockCopy implements Operation { private final Extent destination; private final Extent source; private final RegionFunction function; - private final Vector origin; + private final BlockVector3 origin; - private Vector mutable = new MutableBlockVector(); +// private Vector mutable = new MutableBlockVector3(); - public BackwardsExtentBlockCopy(Extent source, Region region, Extent destination, Vector origin, Transform transform, RegionFunction function) { + public BackwardsExtentBlockCopy(Extent source, Region region, Extent destination, BlockVector3 origin, Transform transform, RegionFunction function) { this.source = source; this.region = region; this.destination = destination; @@ -33,8 +33,8 @@ public class BackwardsExtentBlockCopy implements Operation { public Operation resume(RunContext run) throws WorldEditException { CuboidRegion destRegion = transform(this.transform, this.region); Transform inverse = this.transform.inverse(); - for (Vector pt : destRegion) { - Vector copyFrom = transform(inverse, pt); + for (BlockVector3 pt : destRegion) { + BlockVector3 copyFrom = transform(inverse, pt); if (region.contains(copyFrom)) { function.apply(pt); } @@ -43,31 +43,32 @@ public class BackwardsExtentBlockCopy implements Operation { } private CuboidRegion transform(Transform transform, Region region) { - Vector min = new MutableBlockVector(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); - Vector max = new MutableBlockVector(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); - Vector pos1 = region.getMinimumPoint(); - Vector pos2 = region.getMaximumPoint(); + BlockVector3 min = BlockVector3.at(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); + BlockVector3 max = BlockVector3.at(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE); + BlockVector3 pos1 = region.getMinimumPoint(); + BlockVector3 pos2 = region.getMaximumPoint(); for (int x : new int[] { pos1.getBlockX(), pos2.getBlockX() }) { for (int y : new int[] { pos1.getBlockY(), pos2.getBlockY() }) { for (int z : new int[] { pos1.getBlockZ(), pos2.getBlockZ() }) { - Vector pt = transform(transform, new Vector(x, y, z)).toBlockVector(); - min = Vector.getMinimum(min, pt); - max = Vector.getMaximum(max, pt); + BlockVector3 pt = transform(transform, BlockVector3.at(x, y, z)); + min = min.getMinimum(pt); + max = max.getMaximum(pt); } } } return new CuboidRegion(min, max); } - private Vector transform(Transform transform, Vector pt) { - mutable.mutX(((pt.getBlockX() - origin.getBlockX()))); - mutable.mutY(((pt.getBlockY() - origin.getBlockY()))); - mutable.mutZ(((pt.getBlockZ() - origin.getBlockZ()))); - Vector tmp = transform.apply(mutable); - tmp.mutX((tmp.getBlockX() + origin.getBlockX())); - tmp.mutY((tmp.getBlockY() + origin.getBlockY())); - tmp.mutZ((tmp.getBlockZ() + origin.getBlockZ())); - return tmp; + private BlockVector3 transform(Transform transform, BlockVector3 pt) { +// mutable.mutX(((pt.getBlockX() - origin.getBlockX()))); +// mutable.mutY(((pt.getBlockY() - origin.getBlockY()))); +// mutable.mutZ(((pt.getBlockZ() - origin.getBlockZ()))); +// BlockVector3 tmp = transform.apply(new Vector3(pt.getBlockX() - origin.getBlockX(), pt.getBlockY() - origin.getBlockY(), pt.getBlockZ() - origin.getBlockZ())).toBlockPoint(); +// tmp.mutX((tmp.getBlockX() + origin.getBlockX())); +// tmp.mutY((tmp.getBlockY() + origin.getBlockY())); +// tmp.mutZ((tmp.getBlockZ() + origin.getBlockZ())); +// return tmp; + return transform.apply(Vector3.at(pt.getBlockX() - origin.getBlockX(), pt.getBlockY() - origin.getBlockY(), pt.getBlockZ() - origin.getBlockZ())).toBlockPoint().add(origin.getBlockX(), origin.getBlockY(), origin.getBlockZ()); } @Override diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/BlockMapEntryPlacer.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/BlockMapEntryPlacer.java index 78577b2e9..44e33a3af 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/BlockMapEntryPlacer.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/BlockMapEntryPlacer.java @@ -19,13 +19,15 @@ package com.sk89q.worldedit.function.operation; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; import java.util.Iterator; import java.util.List; @@ -40,7 +42,7 @@ import static com.google.common.base.Preconditions.checkNotNull; public class BlockMapEntryPlacer implements Operation { private final Extent extent; - private final Iterator> iterator; + private final Iterator> iterator; /** * Create a new instance. @@ -48,7 +50,7 @@ public class BlockMapEntryPlacer implements Operation { * @param extent the extent to set the blocks on * @param iterator the iterator */ - public BlockMapEntryPlacer(Extent extent, Iterator> iterator) { + public BlockMapEntryPlacer(Extent extent, Iterator> iterator) { checkNotNull(extent); checkNotNull(iterator); this.extent = extent; @@ -58,7 +60,7 @@ public class BlockMapEntryPlacer implements Operation { @Override public Operation resume(RunContext run) throws WorldEditException { while (iterator.hasNext()) { - Map.Entry entry = iterator.next(); + Map.Entry entry = iterator.next(); extent.setBlock(entry.getKey(), entry.getValue()); } 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 b8018657c..d22285d22 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 @@ -28,8 +28,10 @@ import com.boydti.fawe.object.function.block.CombinedBlockCopy; import com.boydti.fawe.object.function.block.SimpleBlockCopy; import com.boydti.fawe.util.MaskTraverser; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.collect.Lists; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.extent.Extent; @@ -38,6 +40,7 @@ import com.sk89q.worldedit.function.CombinedRegionFunction; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.RegionMaskTestFunction; import com.sk89q.worldedit.function.RegionMaskingFilter; +import com.sk89q.worldedit.function.block.ExtentBlockCopy; import com.sk89q.worldedit.function.entity.ExtentEntityCopy; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Masks; @@ -45,6 +48,7 @@ import com.sk89q.worldedit.function.visitor.EntityVisitor; import com.sk89q.worldedit.function.visitor.IntersectRegionFunction; import com.sk89q.worldedit.function.visitor.RegionVisitor; import com.sk89q.worldedit.math.transform.AffineTransform; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.transform.Identity; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.regions.Region; @@ -67,8 +71,8 @@ public class ForwardExtentCopy implements Operation { private final Extent source; private final Extent destination; private final Region region; - private final Vector from; - private final Vector to; + private final BlockVector3 from; + private final BlockVector3 to; private int repetitions = 1; private Mask sourceMask = Masks.alwaysTrue(); private boolean removingEntities; @@ -87,10 +91,10 @@ public class ForwardExtentCopy implements Operation { * @param source the source extent * @param region the region to copy * @param destination the destination extent - * @param to the destination position - * @see #ForwardExtentCopy(Extent, Region, Vector, Extent, Vector) the main constructor + * @param to the destination position + * @see #ForwardExtentCopy(Extent, Region, BlockVector3, Extent, BlockVector3) the main constructor */ - public ForwardExtentCopy(Extent source, Region region, Extent destination, Vector to) { + public ForwardExtentCopy(Extent source, Region region, Extent destination, BlockVector3 to) { this(source, region, region.getMinimumPoint(), destination, to); } @@ -103,7 +107,7 @@ public class ForwardExtentCopy implements Operation { * @param destination the destination extent * @param to the destination position */ - public ForwardExtentCopy(Extent source, Region region, Vector from, Extent destination, Vector to) { + public ForwardExtentCopy(Extent source, Region region, BlockVector3 from, Extent destination, BlockVector3 to) { checkNotNull(source); checkNotNull(region); checkNotNull(from); @@ -262,9 +266,9 @@ public class ForwardExtentCopy implements Operation { } Extent finalDest = destination; - Vector translation = to.subtract(from); + BlockVector3 translation = to.subtract(from); - if (!translation.equals(Vector.ZERO)) { + if (!translation.equals(BlockVector3.ZERO)) { finalDest = new BlockTranslateExtent(finalDest, translation.getBlockX(), translation.getBlockY(), translation.getBlockZ()); } @@ -301,29 +305,28 @@ public class ForwardExtentCopy implements Operation { RegionFunction maskFunc = null; if (sourceFunction != null) { - Vector disAbs = translation.positive(); - Vector size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); + BlockVector3 disAbs = translation.abs(); + BlockVector3 size = region.getMaximumPoint().subtract(region.getMinimumPoint()).add(1, 1, 1); boolean overlap = (disAbs.getBlockX() < size.getBlockX() && disAbs.getBlockY() < size.getBlockY() && disAbs.getBlockZ() < size.getBlockZ()); RegionFunction copySrcFunc = sourceFunction; if (overlap && translation.length() != 0) { - MutableBlockVector mutable = new MutableBlockVector(); int x = translation.getBlockX(); int y = translation.getBlockY(); int z = translation.getBlockZ(); maskFunc = position -> { - mutable.setComponents(position.getBlockX() + x, position.getBlockY() + y, position.getBlockZ() + z); - if (region.contains(mutable)) { - return sourceFunction.apply(mutable); + BlockVector3 bv = BlockVector3.at(position.getBlockX() + x, position.getBlockY() + y, position.getBlockZ() + z); + if (region.contains(bv)) { + return sourceFunction.apply(bv); } return false; }; copySrcFunc = position -> { - mutable.setComponents(position.getBlockX() - x, position.getBlockY() - y, position.getBlockZ() - z); - if (!region.contains(mutable)) { + BlockVector3 bv = BlockVector3.at(position.getBlockX() - x, position.getBlockY() - y, position.getBlockZ() - z); + if (!region.contains(bv)) { return sourceFunction.apply(position); } return false; @@ -354,7 +357,7 @@ public class ForwardExtentCopy implements Operation { .stream() .filter(entity -> entity.getState() != null && !entity.getState().getType().getId().equals("minecraft:player") && - region.contains(entity.getLocation().toVector())) + region.contains(entity.getLocation().toBlockPoint())) .collect(Collectors.toList()); } else { entities = new ArrayList<>(); @@ -365,7 +368,9 @@ public class ForwardExtentCopy implements Operation { Operations.completeBlindly(blockCopy); if (!entities.isEmpty()) { - ExtentEntityCopy entityCopy = new ExtentEntityCopy(from, destination, to, currentTransform); + ExtentEntityCopy entityCopy = new ExtentEntityCopy(from.toVector3(), destination, to.toVector3(), currentTransform); +// if (copyingEntities) { +// ExtentEntityCopy entityCopy = new ExtentEntityCopy(from, destination, to, currentTransform); entityCopy.setRemoving(removingEntities); EntityVisitor entityVisitor = new EntityVisitor(entities.iterator(), entityCopy); Operations.completeBlindly(entityVisitor); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/SetLocatedBlocks.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/SetLocatedBlocks.java new file mode 100644 index 000000000..cf644af7a --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/operation/SetLocatedBlocks.java @@ -0,0 +1,56 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.function.operation; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.util.LocatedBlock; + +import java.util.List; + +public class SetLocatedBlocks implements Operation { + + private final Extent extent; + private final Iterable blocks; + + public SetLocatedBlocks(Extent extent, Iterable blocks) { + this.extent = checkNotNull(extent); + this.blocks = checkNotNull(blocks); + } + + @Override + public Operation resume(RunContext run) throws WorldEditException { + for (LocatedBlock block : blocks) { + extent.setBlock(block.getLocation(), block.getBlock()); + } + return null; + } + + @Override + public void cancel() { + } + + @Override + public void addStatusMessages(List messages) { + } + +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/BlockPattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/BlockPattern.java index 6d2804125..7a41cc062 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/BlockPattern.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/BlockPattern.java @@ -1,30 +1,44 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ package com.sk89q.worldedit.function.pattern; -import com.boydti.fawe.FaweCache; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockStateHolder; - - import static com.google.common.base.Preconditions.checkNotNull; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockStateHolder; + /** - * @deprecated Just use BaseBlock directly + * A pattern that returns the same {@link BaseBlock} each time. */ @Deprecated public class BlockPattern implements Pattern { - private BlockStateHolder block; + private BaseBlock block; - public BlockPattern(BlockStateHolder block) { - this.block = block; - } - - @Override - public BlockStateHolder apply(Vector position) { - return block; + /** + * Create a new pattern with the given block. + * + * @param block the block + */ + public BlockPattern(BlockStateHolder block) { + setBlock(block); } /** @@ -32,7 +46,7 @@ public class BlockPattern implements Pattern { * * @return the block that is always returned */ - public BlockStateHolder getBlock() { + public BaseBlock getBlock() { return block; } @@ -41,8 +55,14 @@ public class BlockPattern implements Pattern { * * @param block the block */ - public void setBlock(BlockStateHolder block) { + public void setBlock(BlockStateHolder block) { checkNotNull(block); - this.block = block; + this.block = block.toBaseBlock(); } + + @Override + public BaseBlock apply(BlockVector3 position) { + return block; + } + } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/ClipboardPattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/ClipboardPattern.java index 632fe21c6..cbfa5dbf6 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/ClipboardPattern.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/ClipboardPattern.java @@ -1,11 +1,12 @@ package com.sk89q.worldedit.function.pattern; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.extent.clipboard.Clipboard; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; import static com.google.common.base.Preconditions.checkNotNull; @@ -17,8 +18,8 @@ public class ClipboardPattern extends AbstractPattern { private final Clipboard clipboard; private final int sx, sy, sz; - private final Vector min; - private MutableBlockVector mutable = new MutableBlockVector(); + private final BlockVector3 min; +// private final BlockVector3 size; /** * Create a new clipboard pattern. @@ -28,7 +29,7 @@ public class ClipboardPattern extends AbstractPattern { public ClipboardPattern(Clipboard clipboard) { checkNotNull(clipboard); this.clipboard = clipboard; - Vector size = clipboard.getMaximumPoint().subtract(clipboard.getMinimumPoint()).add(1, 1, 1); + BlockVector3 size = clipboard.getMaximumPoint().subtract(clipboard.getMinimumPoint()).add(1, 1, 1); this.sx = size.getBlockX(); this.sy = size.getBlockY(); this.sz = size.getBlockZ(); @@ -36,17 +37,14 @@ public class ClipboardPattern extends AbstractPattern { } @Override - public BlockStateHolder apply(Vector position) { + public BaseBlock apply(BlockVector3 position) { int xp = position.getBlockX() % sx; int yp = position.getBlockY() % sy; int zp = position.getBlockZ() % sz; if (xp < 0) xp += sx; if (yp < 0) yp += sy; if (zp < 0) zp += sz; - mutable.mutX((min.getX() + xp)); - mutable.mutY((min.getY() + yp)); - mutable.mutZ((min.getZ() + zp)); - return clipboard.getBlock(mutable); + return clipboard.getFullBlock(BlockVector3.at(min.getX() + xp, min.getY() + yp, min.getZ() + zp)); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/FawePattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/FawePattern.java index 9030c2bf0..8a797f5cd 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/FawePattern.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/FawePattern.java @@ -1,12 +1,13 @@ package com.sk89q.worldedit.function.pattern; import com.sk89q.minecraft.util.commands.Link; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.command.UtilityCommands; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.NullExtent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; /** @@ -17,7 +18,7 @@ import com.sk89q.worldedit.world.block.BlockState; public interface FawePattern extends Pattern { @Deprecated - default BlockStateHolder apply(Vector position) { + default BaseBlock apply(BlockVector3 position) { throw new UnsupportedOperationException("Please use apply(extent, get, set)"); } @@ -27,6 +28,5 @@ public interface FawePattern extends Pattern { * @return a block */ @Override - boolean apply(Extent extent, Vector get, Vector set) throws WorldEditException; -} - + boolean apply(Extent extent, BlockVector3 get, BlockVector3 set) throws WorldEditException; +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/Pattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/Pattern.java index 9d416ff56..a2419df27 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/Pattern.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/Pattern.java @@ -20,35 +20,33 @@ package com.sk89q.worldedit.function.pattern; import com.sk89q.minecraft.util.commands.Link; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.command.UtilityCommands; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.NullExtent; import com.sk89q.worldedit.internal.expression.runtime.Return; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockState; /** * Returns a {@link BlockStateHolder} for a given position. - * @deprecated Use FawePattern */ @Link(clazz = UtilityCommands.class, value = "patterns") -@Deprecated -public interface Pattern extends com.sk89q.worldedit.patterns.Pattern{ +public interface Pattern{ - @Override - default BaseBlock next(Vector position) { - return new BaseBlock(apply(position)); - } - - @Override - default BaseBlock next(int x, int y, int z) { - return new BaseBlock(apply(new Vector(x, y, z))); - } +// @Override +// default BaseBlock next(BlockVector3 position) { +// return new BaseBlock(apply(position)); +// } +// +// @Override +// default BaseBlock next(int x, int y, int z) { +// return new BaseBlock(apply(BlockVector3.at(x, y, z))); +// } /** * Return a {@link BlockStateHolder} for the given position. @@ -56,10 +54,9 @@ public interface Pattern extends com.sk89q.worldedit.patterns.Pattern{ * @param position the position * @return a block */ - @Deprecated - BlockStateHolder apply(Vector position); + BaseBlock apply(BlockVector3 position); - default boolean apply(Extent extent, Vector get, Vector set) throws WorldEditException { + default boolean apply(Extent extent, BlockVector3 get, BlockVector3 set) throws WorldEditException { return extent.setBlock(set, apply(get)); } -} \ No newline at end of file +} 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 edd624fa1..2acf60bf0 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 @@ -3,12 +3,14 @@ package com.sk89q.worldedit.function.pattern; import com.boydti.fawe.object.collection.RandomCollection; import com.boydti.fawe.object.random.SimpleRandom; import com.boydti.fawe.object.random.TrueRandom; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; import java.util.HashMap; import java.util.LinkedHashSet; @@ -63,12 +65,12 @@ public class RandomPattern extends AbstractPattern { } @Override - public BlockStateHolder apply(Vector get) { + public BaseBlock apply(BlockVector3 get) { return collection.next(get.getBlockX(), get.getBlockY(), get.getBlockZ()).apply(get); } @Override - public boolean apply(Extent extent, Vector set, Vector get) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 set, BlockVector3 get) throws WorldEditException { return collection.next(get.getBlockX(), get.getBlockY(), get.getBlockZ()).apply(extent, set, get); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RepeatingExtentPattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RepeatingExtentPattern.java index 70f3f81d4..d7b799840 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RepeatingExtentPattern.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RepeatingExtentPattern.java @@ -19,20 +19,19 @@ package com.sk89q.worldedit.function.pattern; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.extent.Extent; - import static com.google.common.base.Preconditions.checkNotNull; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; + /** * Returns the blocks from {@link Extent}, repeating when out of bounds. */ public class RepeatingExtentPattern extends AbstractPattern { private Extent extent; - private Vector offset; + private BlockVector3 offset; /** * Create a new instance. @@ -40,7 +39,7 @@ public class RepeatingExtentPattern extends AbstractPattern { * @param extent the extent * @param offset the offset */ - public RepeatingExtentPattern(Extent extent, Vector offset) { + public RepeatingExtentPattern(Extent extent, BlockVector3 offset) { setExtent(extent); setOffset(offset); } @@ -69,7 +68,7 @@ public class RepeatingExtentPattern extends AbstractPattern { * * @return the offset */ - public Vector getOffset() { + public BlockVector3 getOffset() { return offset; } @@ -78,18 +77,18 @@ public class RepeatingExtentPattern extends AbstractPattern { * * @param offset the offset */ - public void setOffset(Vector offset) { + public void setOffset(BlockVector3 offset) { checkNotNull(offset); this.offset = offset; } @Override - public BlockStateHolder apply(Vector position) { - Vector base = position.add(offset); - Vector size = extent.getMaximumPoint().subtract(extent.getMinimumPoint()).add(1, 1, 1); + public BaseBlock apply(BlockVector3 position) { + BlockVector3 base = position.add(offset); + BlockVector3 size = extent.getMaximumPoint().subtract(extent.getMinimumPoint()).add(1, 1, 1); int x = base.getBlockX() % size.getBlockX(); int y = base.getBlockY() % size.getBlockY(); int z = base.getBlockZ() % size.getBlockZ(); - return extent.getBlock(new Vector(x, y, z)); + return extent.getFullBlock(BlockVector3.at(x, y, z)); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/util/FlatRegionOffset.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/util/FlatRegionOffset.java index 6a21a50c3..b53b75619 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/util/FlatRegionOffset.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/util/FlatRegionOffset.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function.util; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.FlatRegionFunction; @@ -30,7 +30,7 @@ import com.sk89q.worldedit.function.FlatRegionFunction; */ public class FlatRegionOffset implements FlatRegionFunction { - private Vector2D offset; + private BlockVector2 offset; private final FlatRegionFunction function; /** @@ -39,7 +39,7 @@ public class FlatRegionOffset implements FlatRegionFunction { * @param offset the offset * @param function the function that is called with the offset position */ - public FlatRegionOffset(Vector2D offset, FlatRegionFunction function) { + public FlatRegionOffset(BlockVector2 offset, FlatRegionFunction function) { checkNotNull(function); setOffset(offset); this.function = function; @@ -50,7 +50,7 @@ public class FlatRegionOffset implements FlatRegionFunction { * * @return the offset */ - public Vector2D getOffset() { + public BlockVector2 getOffset() { return offset; } @@ -59,13 +59,13 @@ public class FlatRegionOffset implements FlatRegionFunction { * * @param offset the offset */ - public void setOffset(Vector2D offset) { + public void setOffset(BlockVector2 offset) { checkNotNull(offset); this.offset = offset; } @Override - public boolean apply(Vector2D position) throws WorldEditException { + public boolean apply(BlockVector2 position) throws WorldEditException { return function.apply(position.add(offset)); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/util/RegionOffset.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/util/RegionOffset.java index c1f395be6..a9e123fcf 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/util/RegionOffset.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/util/RegionOffset.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.function.util; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; @@ -30,7 +30,7 @@ import com.sk89q.worldedit.function.RegionFunction; */ public class RegionOffset implements RegionFunction { - private Vector offset; + private BlockVector3 offset; private final RegionFunction function; /** @@ -39,7 +39,7 @@ public class RegionOffset implements RegionFunction { * @param offset the offset * @param function the function that is called with the offset position */ - public RegionOffset(Vector offset, RegionFunction function) { + public RegionOffset(BlockVector3 offset, RegionFunction function) { checkNotNull(function); setOffset(offset); this.function = function; @@ -50,7 +50,7 @@ public class RegionOffset implements RegionFunction { * * @return the offset */ - public Vector getOffset() { + public BlockVector3 getOffset() { return offset; } @@ -59,13 +59,13 @@ public class RegionOffset implements RegionFunction { * * @param offset the offset */ - public void setOffset(Vector offset) { + public void setOffset(BlockVector3 offset) { checkNotNull(offset); this.offset = offset; } @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { return function.apply(position.add(offset)); } 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 e371e4ff5..b31ea0d85 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 @@ -7,37 +7,55 @@ import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.HasFaweQueue; import com.boydti.fawe.object.IntegerTrio; import com.boydti.fawe.object.collection.BlockVectorSet; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.RunContext; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; +import com.sk89q.worldedit.math.Vector3; + +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; +import java.util.Queue; +import java.util.Set; +/** + * Performs a breadth-first search starting from points added with + * {@link #visit(BlockVector3)}. The search continues + * to a certain adjacent point provided that the method + * {@link #isVisitable(BlockVector3, BlockVector3)} + * returns true for that point. + * + *

As an abstract implementation, this class can be used to implement + * functionality that starts at certain points and extends outward from + * those points.

+ */ public abstract class BreadthFirstSearch implements Operation { - public static final Vector[] DEFAULT_DIRECTIONS = new Vector[6]; - public static final Vector[] DIAGONAL_DIRECTIONS; + public static final BlockVector3[] DEFAULT_DIRECTIONS = new BlockVector3[6]; + public static final BlockVector3[] DIAGONAL_DIRECTIONS; static { - DEFAULT_DIRECTIONS[0] = (new MutableBlockVector(0, -1, 0)); - DEFAULT_DIRECTIONS[1] = (new MutableBlockVector(0, 1, 0)); - DEFAULT_DIRECTIONS[2] = (new MutableBlockVector(-1, 0, 0)); - DEFAULT_DIRECTIONS[3] = (new MutableBlockVector(1, 0, 0)); - DEFAULT_DIRECTIONS[4] = (new MutableBlockVector(0, 0, -1)); - DEFAULT_DIRECTIONS[5] = (new MutableBlockVector(0, 0, 1)); - List list = new ArrayList<>(); + DEFAULT_DIRECTIONS[0] = (BlockVector3.at(0, -1, 0)); + DEFAULT_DIRECTIONS[1] = (BlockVector3.at(0, 1, 0)); + DEFAULT_DIRECTIONS[2] = (BlockVector3.at(-1, 0, 0)); + DEFAULT_DIRECTIONS[3] = (BlockVector3.at(1, 0, 0)); + DEFAULT_DIRECTIONS[4] = (BlockVector3.at(0, 0, -1)); + DEFAULT_DIRECTIONS[5] = (BlockVector3.at(0, 0, 1)); + List list = new ArrayList<>(); for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { for (int z = -1; z <= 1; z++) { if (x != 0 || y != 0 || z != 0) { - MutableBlockVector pos = new MutableBlockVector(x, y, z); + BlockVector3 pos = BlockVector3.at(x, y, z); if (!list.contains(pos)) { list.add(pos); } @@ -45,17 +63,17 @@ public abstract class BreadthFirstSearch implements Operation { } } } - Collections.sort(list, new Comparator() { + Collections.sort(list, new Comparator() { @Override - public int compare(Vector o1, Vector o2) { + public int compare(BlockVector3 o1, BlockVector3 o2) { return (int) Math.signum(o1.lengthSq() - o2.lengthSq()); } }); - DIAGONAL_DIRECTIONS = list.toArray(new Vector[list.size()]); + DIAGONAL_DIRECTIONS = list.toArray(new BlockVector3[list.size()]); } private final RegionFunction function; - private List directions = new ArrayList<>(); + private List directions = new ArrayList<>(); private BlockVectorSet visited; private final MappedFaweQueue mFaweQueue; private BlockVectorSet queue; @@ -82,26 +100,58 @@ public abstract class BreadthFirstSearch implements Operation { this.maxDepth = maxDepth; } - public abstract boolean isVisitable(Vector from, Vector to); - - public Collection getDirections() { - return this.directions; - } - - public void setDirections(List directions) { + public void setDirections(List directions) { this.directions = directions; } private IntegerTrio[] getIntDirections() { IntegerTrio[] array = new IntegerTrio[directions.size()]; for (int i = 0; i < array.length; i++) { - Vector dir = directions.get(i); + BlockVector3 dir = directions.get(i); array[i] = new IntegerTrio(dir.getBlockX(), dir.getBlockY(), dir.getBlockZ()); } return array; } + + /** + * Get the list of directions will be visited. + * + *

Directions are {@link BlockVector3}s that determine + * what adjacent points area available. Vectors should not be + * unit vectors. An example of a valid direction is + * {@code BlockVector3.at(1, 0, 1)}.

+ * + *

The list of directions can be cleared.

+ * + * @return the list of directions + */ + protected Collection getDirections() { + return directions; + } - public void visit(final Vector pos) { + /** + * Add the directions along the axes as directions to visit. + */ + protected void addAxes() { + directions.add(BlockVector3.at(0, -1, 0)); + directions.add(BlockVector3.at(0, 1, 0)); + directions.add(BlockVector3.at(-1, 0, 0)); + directions.add(BlockVector3.at(1, 0, 0)); + directions.add(BlockVector3.at(0, 0, -1)); + directions.add(BlockVector3.at(0, 0, 1)); + } + + /** + * Add the diagonal directions as directions to visit. + */ + protected void addDiagonal() { + directions.add(BlockVector3.at(1, 0, 1)); + directions.add(BlockVector3.at(-1, 0, -1)); + directions.add(BlockVector3.at(1, 0, -1)); + directions.add(BlockVector3.at(-1, 0, 1)); + } + + public void visit(final BlockVector3 pos) { if (!isVisited(pos)) { isVisitable(pos, pos); // Ignore this, just to initialize mask on this point queue.add(pos); @@ -123,18 +173,52 @@ public abstract class BreadthFirstSearch implements Operation { return visited; } - public boolean isVisited(Vector pos) { + public boolean isVisited(BlockVector3 pos) { return visited.contains(pos); } public void setMaxBranch(int maxBranch) { this.maxBranch = maxBranch; } + /** + * Try to visit the given 'to' location. + * + * @param from the origin block + * @param to the block under question + */ + private void visit(BlockVector3 from, BlockVector3 to) { + BlockVector3 blockVector = to; + if (!visited.contains(blockVector)) { + visited.add(blockVector); + if (isVisitable(from, to)) { + queue.add(blockVector); + } + } + } + + /** + * Return whether the given 'to' block should be visited, starting from the + * 'from' block. + * + * @param from the origin block + * @param to the block under question + * @return true if the 'to' block should be visited + */ + protected abstract boolean isVisitable(BlockVector3 from, BlockVector3 to); + + /** + * Get the number of affected objects. + * + * @return the number of affected + */ + public int getAffected() { + return affected; + } @Override public Operation resume(RunContext run) throws WorldEditException { - MutableBlockVector mutable = new MutableBlockVector(); - MutableBlockVector mutable2 = new MutableBlockVector(); + MutableBlockVector3 mutable = new MutableBlockVector3(); +// MutableBlockVector3 mutable2 = new MutableBlockVector3(); boolean shouldTrim = false; IntegerTrio[] dirs = getIntDirections(); BlockVectorSet tempQueue = new BlockVectorSet(); @@ -143,7 +227,7 @@ public abstract class BreadthFirstSearch implements Operation { if (mFaweQueue != null && Settings.IMP.QUEUE.PRELOAD_CHUNKS > 1) { int cx = Integer.MIN_VALUE; int cz = Integer.MIN_VALUE; - for (Vector from : queue) { + for (BlockVector3 from : queue) { for (IntegerTrio direction : dirs) { int x = from.getBlockX() + direction.x; int z = from.getBlockZ() + direction.z; @@ -158,11 +242,11 @@ public abstract class BreadthFirstSearch implements Operation { } } } - for (Vector chunk : chunkLoadSet) { + for (BlockVector3 chunk : chunkLoadSet) { mFaweQueue.queueChunkLoad(chunk.getBlockX(), chunk.getBlockZ()); } } - for (Vector from : queue) { + for (BlockVector3 from : queue) { if (function.apply(from)) affected++; for (int i = 0, j = 0; i < dirs.length && j < maxBranch; i++) { IntegerTrio direction = dirs[i]; @@ -173,16 +257,24 @@ public abstract class BreadthFirstSearch implements Operation { int x = from.getBlockX() + direction.x; int z = from.getBlockZ() + direction.z; if (!visited.contains(x, y, z)) { - mutable2.mutX(x); - mutable2.mutY(y); - mutable2.mutZ(z); - if (isVisitable(from, mutable2)) { + if (isVisitable(from, BlockVector3.at(x, y, z))) { j++; visited.add(x, y, z); tempQueue.add(x, y, z); } } } +//======= +// BlockVector3 position; +// +// while ((position = queue.poll()) != null) { +// if (function.apply(position)) { +// affected++; +// } +// +// for (BlockVector3 dir : directions) { +// visit(position, position.add(dir)); +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner } if (currentDepth == maxDepth) { break; @@ -207,10 +299,6 @@ public abstract class BreadthFirstSearch implements Operation { messages.add(BBC.VISITOR_BLOCK.format(getAffected())); } - public int getAffected() { - return this.affected; - } - @Override public void cancel() { } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DirectionalVisitor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DirectionalVisitor.java index ecdcbb690..8a9542e32 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DirectionalVisitor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DirectionalVisitor.java @@ -20,10 +20,11 @@ package com.sk89q.worldedit.function.visitor; import com.boydti.fawe.object.HasFaweQueue; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; + import java.util.Collection; @@ -38,30 +39,30 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class DirectionalVisitor extends RecursiveVisitor { - private final Vector origin; - private final Vector dirVec; + private final BlockVector3 origin; + private final BlockVector3 dirVec; - public DirectionalVisitor(Mask mask, RegionFunction function, Vector origin, Vector direction) { + public DirectionalVisitor(Mask mask, RegionFunction function, BlockVector3 origin, BlockVector3 direction) { this(mask, function, origin, direction, Integer.MAX_VALUE, null); } - public DirectionalVisitor(Mask mask, RegionFunction function, Vector origin, Vector direction, int distance, HasFaweQueue hasFaweQueue) { + public DirectionalVisitor(Mask mask, RegionFunction function, BlockVector3 origin, BlockVector3 direction, int distance, HasFaweQueue hasFaweQueue) { super(mask, function, distance, hasFaweQueue); checkNotNull(mask); this.origin = origin; - this.dirVec = new MutableBlockVector(direction); - final Collection directions = this.getDirections(); + this.dirVec = direction; + final Collection directions = this.getDirections(); directions.clear(); - directions.add(new Vector(1, 0, 0)); - directions.add(new Vector(-1, 0, 0)); - directions.add(new Vector(0, 0, 1)); - directions.add(new Vector(0, 0, -1)); - directions.add(new Vector(0, -1, 0)); - directions.add(new Vector(0, 1, 0)); + directions.add(BlockVector3.at(1, 0, 0)); + directions.add(BlockVector3.at(-1, 0, 0)); + directions.add(BlockVector3.at(0, 0, 1)); + directions.add(BlockVector3.at(0, 0, -1)); + directions.add(BlockVector3.at(0, -1, 0)); + directions.add(BlockVector3.at(0, 1, 0)); } @Override - public boolean isVisitable(final Vector from, final Vector to) { + public boolean isVisitable(final BlockVector3 from, final BlockVector3 to) { int dx = to.getBlockX() - from.getBlockX(); int dz = to.getBlockZ() - from.getBlockZ(); int dy = to.getBlockY() - from.getBlockY(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DownwardVisitor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DownwardVisitor.java index 7d91069d7..a3a8dac66 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DownwardVisitor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/DownwardVisitor.java @@ -20,9 +20,14 @@ package com.sk89q.worldedit.function.visitor; import com.boydti.fawe.object.HasFaweQueue; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.mask.Mask; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; + import java.util.Collection; @@ -54,19 +59,20 @@ public class DownwardVisitor extends RecursiveVisitor { super(mask, function, depth, hasFaweQueue); checkNotNull(mask); this.baseY = baseY; - final Collection directions = this.getDirections(); + + Collection directions = getDirections(); directions.clear(); - directions.add(new Vector(1, 0, 0)); - directions.add(new Vector(-1, 0, 0)); - directions.add(new Vector(0, 0, 1)); - directions.add(new Vector(0, 0, -1)); - directions.add(new Vector(0, -1, 0)); + directions.add(BlockVector3.at(1, 0, 0)); + directions.add(BlockVector3.at(-1, 0, 0)); + directions.add(BlockVector3.at(0, 0, 1)); + directions.add(BlockVector3.at(0, 0, -1)); + directions.add(BlockVector3.at(0, -1, 0)); } @Override - public boolean isVisitable(final Vector from, final Vector to) { - final int fromY = from.getBlockY(); - return ((fromY == this.baseY) || (to.getBlockY() - from.getBlockY() < 0)) && super.isVisitable(from, to); + protected boolean isVisitable(BlockVector3 from, BlockVector3 to) { + int fromY = from.getBlockY(); + return (fromY == baseY || to.subtract(from).getBlockY() < 0) && super.isVisitable(from, to); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/FlatRegionVisitor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/FlatRegionVisitor.java index 6a36fcdac..5d86ad0c9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/FlatRegionVisitor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/FlatRegionVisitor.java @@ -24,12 +24,15 @@ import com.boydti.fawe.example.MappedFaweQueue; import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.HasFaweQueue; import com.boydti.fawe.object.visitor.Fast2DIterator; -import com.sk89q.worldedit.Vector2D; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.FlatRegionFunction; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.operation.RunContext; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.Vector2; import com.sk89q.worldedit.regions.FlatRegion; import java.util.List; @@ -44,7 +47,7 @@ public class FlatRegionVisitor implements Operation { private final FlatRegionFunction function; private MappedFaweQueue queue; private int affected = 0; - private final Iterable iterator; + private final Iterable iterator; /** * Create a new visitor. @@ -78,14 +81,21 @@ public class FlatRegionVisitor implements Operation { } @Override +//<<<<<<< HEAD public Operation resume(final RunContext run) throws WorldEditException { if (this.queue != null) { - for (final Vector2D pt : new Fast2DIterator(this.iterator, queue)) { + for (final BlockVector2 pt : new Fast2DIterator(this.iterator, queue)) { if (this.function.apply(pt)) affected++; } } else { - for (final Vector2D pt : this.iterator) { + for (final BlockVector2 pt : this.iterator) { if (this.function.apply(pt)) affected++; +//======= +// public Operation resume(RunContext run) throws WorldEditException { +// for (BlockVector2 pt : flatRegion.asFlatRegion()) { +// if (function.apply(pt)) { +// affected++; +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner } } return null; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/IntersectRegionFunction.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/IntersectRegionFunction.java index b08c4a223..8d0f5ea10 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/IntersectRegionFunction.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/IntersectRegionFunction.java @@ -1,8 +1,8 @@ package com.sk89q.worldedit.function.visitor; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.math.BlockVector3; public class IntersectRegionFunction implements RegionFunction { private final RegionFunction[] functions; @@ -13,7 +13,7 @@ public class IntersectRegionFunction implements RegionFunction { @Override - public boolean apply(Vector position) throws WorldEditException { + public boolean apply(BlockVector3 position) throws WorldEditException { boolean ret = false; for (RegionFunction function : functions) { if (!function.apply(position)) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/LayerVisitor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/LayerVisitor.java index ee0a1d67a..7293d2b26 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/LayerVisitor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/LayerVisitor.java @@ -19,8 +19,9 @@ package com.sk89q.worldedit.function.visitor; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.LayerFunction; import com.sk89q.worldedit.function.mask.Mask2D; @@ -28,6 +29,8 @@ import com.sk89q.worldedit.function.mask.Masks; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.operation.RunContext; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.FlatRegion; import java.util.List; @@ -50,7 +53,7 @@ public class LayerVisitor implements Operation { private Mask2D mask = Masks.alwaysTrue2D(); private final int minY; private final int maxY; - private final Iterable iterator; + private final Iterable iterator; /** * Create a new visitor. @@ -93,20 +96,20 @@ public class LayerVisitor implements Operation { @Override public Operation resume(final RunContext run) throws WorldEditException { - for (final Vector2D column : this.iterator) { + for (final BlockVector2 column : this.iterator) { if (!this.mask.test(column)) { continue; } // Abort if we are underground - if (this.function.isGround(column.toVector(this.maxY + 1))) { + if (function.isGround(column.toBlockVector3(maxY + 1))) { return null; } boolean found = false; int groundY = 0; - for (int y = this.maxY; y >= this.minY; --y) { - final Vector test = column.toVector(y); + for (int y = maxY; y >= minY; --y) { + BlockVector3 test = column.toBlockVector3(y); if (!found) { if (this.function.isGround(test)) { found = true; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/NonRisingVisitor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/NonRisingVisitor.java index 31eae2177..7e79e57a7 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/NonRisingVisitor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/NonRisingVisitor.java @@ -20,9 +20,12 @@ package com.sk89q.worldedit.function.visitor; import com.boydti.fawe.object.HasFaweQueue; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.function.RegionFunction; +import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; + import java.util.Collection; /** @@ -43,13 +46,13 @@ public class NonRisingVisitor extends RecursiveVisitor { public NonRisingVisitor(Mask mask, RegionFunction function, int depth, HasFaweQueue hasFaweQueue) { super(mask, function, depth, hasFaweQueue); - final Collection directions = this.getDirections(); + Collection directions = getDirections(); directions.clear(); - directions.add(new Vector(1, 0, 0)); - directions.add(new Vector(-1, 0, 0)); - directions.add(new Vector(0, 0, 1)); - directions.add(new Vector(0, 0, -1)); - directions.add(new Vector(0, -1, 0)); + directions.add(BlockVector3.at(1, 0, 0)); + directions.add(BlockVector3.at(-1, 0, 0)); + directions.add(BlockVector3.at(0, 0, 1)); + directions.add(BlockVector3.at(0, 0, -1)); + directions.add(BlockVector3.at(0, -1, 0)); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RecursiveVisitor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RecursiveVisitor.java index ba45fbf7c..be44fb32b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RecursiveVisitor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RecursiveVisitor.java @@ -20,9 +20,11 @@ package com.sk89q.worldedit.function.visitor; import com.boydti.fawe.object.HasFaweQueue; -import com.sk89q.worldedit.Vector; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector3; import static com.google.common.base.Preconditions.checkNotNull; @@ -56,8 +58,8 @@ public class RecursiveVisitor extends BreadthFirstSearch { } @Override - public boolean isVisitable(final Vector from, final Vector to) { - return this.mask.test(to); + protected boolean isVisitable(BlockVector3 from, BlockVector3 to) { + return mask.test(to); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RegionVisitor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RegionVisitor.java index 11895274f..9e62b58b5 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RegionVisitor.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/function/visitor/RegionVisitor.java @@ -25,14 +25,13 @@ import com.boydti.fawe.example.MappedFaweQueue; import com.boydti.fawe.object.FaweQueue; import com.boydti.fawe.object.HasFaweQueue; import com.boydti.fawe.object.exception.FaweException; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.function.operation.RunContext; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import java.util.Iterator; import java.util.List; @@ -43,7 +42,7 @@ import java.util.List; public class RegionVisitor implements Operation { public final Region region; - public final Iterable iterable; + public final Iterable iterable; public final RegionFunction function; private final MappedFaweQueue queue; private boolean useCuboidIterator = false; @@ -65,10 +64,10 @@ public class RegionVisitor implements Operation { } public RegionVisitor(Region region, RegionFunction function, FaweQueue queue) { - this((Iterable) region, function, queue); + this((Iterable) region, function, queue); } - public RegionVisitor(Iterable iterable, RegionFunction function, HasFaweQueue hasQueue) { + public RegionVisitor(Iterable iterable, RegionFunction function, HasFaweQueue hasQueue) { region = (iterable instanceof Region) ? (Region) iterable : null; this.iterable = iterable; this.function = function; @@ -87,15 +86,15 @@ public class RegionVisitor implements Operation { @Override public Operation resume(final RunContext run) throws WorldEditException { if (queue != null && Settings.IMP.QUEUE.PRELOAD_CHUNKS > 1) { - /* + /* * The following is done to reduce iteration cost * - Preload chunks just in time * - Only check every 16th block for potential chunk loads * - Stop iteration on exception instead of hasNext * - Do not calculate the stacktrace as it is expensive */ - Iterator trailIter = iterable.iterator(); - Iterator leadIter = iterable.iterator(); + Iterator trailIter = iterable.iterator(); + Iterator leadIter = iterable.iterator(); int lastTrailChunkX = Integer.MIN_VALUE; int lastTrailChunkZ = Integer.MIN_VALUE; int lastLeadChunkX = Integer.MIN_VALUE; @@ -103,7 +102,7 @@ public class RegionVisitor implements Operation { int loadingTarget = Settings.IMP.QUEUE.PRELOAD_CHUNKS; try { for (; ; ) { - Vector pt = trailIter.next(); + BlockVector3 pt = trailIter.next(); apply(pt); int cx = pt.getBlockX() >> 4; int cz = pt.getBlockZ() >> 4; @@ -119,7 +118,7 @@ public class RegionVisitor implements Operation { amount = 1; } for (int count = 0; count < amount; ) { - Vector v = leadIter.next(); + BlockVector3 v = leadIter.next(); int vcx = v.getBlockX() >> 4; int vcz = v.getBlockZ() >> 4; if (vcx != lastLeadChunkX || vcz != lastLeadChunkZ) { @@ -167,7 +166,7 @@ public class RegionVisitor implements Operation { } catch (Throwable ignore) { } try { - for (; ; ) { + while (true) { apply(trailIter.next()); apply(trailIter.next()); } @@ -176,14 +175,14 @@ public class RegionVisitor implements Operation { } catch (Throwable ignore) { } } else { - for (Vector pt : iterable) { + for (BlockVector3 pt : iterable) { apply(pt); } } return null; } - private void apply(Vector pt) throws WorldEditException { + private void apply(BlockVector3 pt) throws WorldEditException { if (function.apply(pt)) { affected++; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/history/change/BiomeChange.java b/worldedit-core/src/main/java/com/sk89q/worldedit/history/change/BiomeChange.java new file mode 100644 index 000000000..133f38f7f --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/history/change/BiomeChange.java @@ -0,0 +1,96 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.history.change; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.history.UndoContext; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.world.biome.BaseBiome; + +/** + * Represents a biome change that may be undone or replayed. + * + *

This biome change does not have an {@link Extent} assigned to it because + * one will be taken from the passed {@link UndoContext}. If the context + * does not have an extent (it is null), cryptic errors may occur.

+ */ +public class BiomeChange implements Change { + + private final BlockVector2 position; + private final BaseBiome previous; + private final BaseBiome current; + + /** + * Create a new biome change. + * + * @param position the position + * @param previous the previous biome + * @param current the current biome + */ + public BiomeChange(BlockVector2 position, BaseBiome previous, BaseBiome current) { + checkNotNull(position); + checkNotNull(previous); + checkNotNull(current); + this.position = position; + this.previous = previous; + this.current = current; + } + + /** + * Get the position. + * + * @return the position + */ + public BlockVector2 getPosition() { + return position; + } + + /** + * Get the previous biome. + * + * @return the previous biome + */ + public BaseBiome getPrevious() { + return previous; + } + + /** + * Get the current biome. + * + * @return the current biome + */ + public BaseBiome getCurrent() { + return current; + } + + @Override + public void undo(UndoContext context) throws WorldEditException { + checkNotNull(context.getExtent()).setBiome(position, previous); + } + + @Override + public void redo(UndoContext context) throws WorldEditException { + checkNotNull(context.getExtent()).setBiome(position, current); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/history/change/BlockChange.java b/worldedit-core/src/main/java/com/sk89q/worldedit/history/change/BlockChange.java index 4bb94aa09..d4613b277 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/history/change/BlockChange.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/history/change/BlockChange.java @@ -21,10 +21,11 @@ package com.sk89q.worldedit.history.change; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.BlockVector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.history.UndoContext; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockStateHolder; /** @@ -36,9 +37,9 @@ import com.sk89q.worldedit.world.block.BlockStateHolder; */ public class BlockChange implements Change { - private final BlockVector position; - private final BlockStateHolder previous; - private final BlockStateHolder current; + private final BlockVector3 position; + private final BaseBlock previous; + private final BaseBlock current; /** * Create a new block change. @@ -47,13 +48,13 @@ public class BlockChange implements Change { * @param previous the previous block * @param current the current block */ - public BlockChange(BlockVector position, BlockStateHolder previous, BlockStateHolder current) { + public , BC extends BlockStateHolder> BlockChange(BlockVector3 position, BP previous, BC current) { checkNotNull(position); checkNotNull(previous); checkNotNull(current); this.position = position; - this.previous = previous; - this.current = current; + this.previous = previous.toBaseBlock(); + this.current = current.toBaseBlock(); } /** @@ -61,7 +62,7 @@ public class BlockChange implements Change { * * @return the position */ - public BlockVector getPosition() { + public BlockVector3 getPosition() { return position; } @@ -70,7 +71,7 @@ public class BlockChange implements Change { * * @return the previous block */ - public BlockStateHolder getPrevious() { + public BaseBlock getPrevious() { return previous; } @@ -79,7 +80,7 @@ public class BlockChange implements Change { * * @return the current block */ - public BlockStateHolder getCurrent() { + public BaseBlock getCurrent() { return current; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/history/changeset/ArrayListHistory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/history/changeset/ArrayListHistory.java new file mode 100644 index 000000000..ec06c27b5 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/history/changeset/ArrayListHistory.java @@ -0,0 +1,73 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.history.changeset; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.collect.Lists; +import com.sk89q.worldedit.history.change.Change; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Stores all {@link Change}s in an {@link ArrayList}. + */ +public class ArrayListHistory implements ChangeSet { + + private final List changes = new ArrayList<>(); + + private boolean recordChanges = true; + + @Override + public void add(Change change) { + checkNotNull(change); + if (recordChanges) { + changes.add(change); + } + } + + @Override + public boolean isRecordingChanges() { + return recordChanges; + } + + @Override + public void setRecordChanges(boolean recordChanges) { + this.recordChanges = recordChanges; + } + + @Override + public Iterator backwardIterator() { + return Lists.reverse(changes).iterator(); + } + + @Override + public Iterator forwardIterator() { + return changes.iterator(); + } + + @Override + public int size() { + return changes.size(); + } + +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/history/changeset/BlockOptimizedHistory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/history/changeset/BlockOptimizedHistory.java new file mode 100644 index 000000000..9c9ad2a85 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/history/changeset/BlockOptimizedHistory.java @@ -0,0 +1,83 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.history.changeset; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.collect.Iterators; +import com.sk89q.worldedit.history.change.BlockChange; +import com.sk89q.worldedit.history.change.Change; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.util.LocatedBlock; +import com.sk89q.worldedit.util.collection.LocatedBlockList; + +import java.util.ArrayList; +import java.util.Iterator; + +/** + * An extension of {@link ArrayListHistory} that stores {@link BlockChange}s + * separately in two {@link ArrayList}s. + * + *

Whether this is a good idea or not is highly questionable, but this class + * exists because this is how history was implemented in WorldEdit for + * many years.

+ */ +public class BlockOptimizedHistory extends ArrayListHistory { + + private static Change createChange(LocatedBlock block) { + return new BlockChange(block.getLocation(), block.getBlock(), block.getBlock()); + } + + private final LocatedBlockList previous = new LocatedBlockList(); + private final LocatedBlockList current = new LocatedBlockList(); + + @Override + public void add(Change change) { + checkNotNull(change); + + if (change instanceof BlockChange) { + BlockChange blockChange = (BlockChange) change; + BlockVector3 position = blockChange.getPosition(); + previous.add(position, blockChange.getPrevious()); + current.add(position, blockChange.getCurrent()); + } else { + super.add(change); + } + } + + @Override + public Iterator forwardIterator() { + return Iterators.concat( + super.forwardIterator(), + Iterators.transform(current.iterator(), BlockOptimizedHistory::createChange)); + } + + @Override + public Iterator backwardIterator() { + return Iterators.concat( + super.backwardIterator(), + Iterators.transform(previous.reverseIterator(), BlockOptimizedHistory::createChange)); + } + + @Override + public int size() { + return super.size() + previous.size(); + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/history/changeset/ChangeSet.java b/worldedit-core/src/main/java/com/sk89q/worldedit/history/changeset/ChangeSet.java index 0b018bcb9..24c4c3fe0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/history/changeset/ChangeSet.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/history/changeset/ChangeSet.java @@ -36,6 +36,20 @@ public interface ChangeSet { */ void add(Change change); + /** + * Whether or not the ChangeSet is recording changes. + * + * @return whether or not the ChangeSet is set to record changes + */ + boolean isRecordingChanges(); + + /** + * Tell the change set whether to record changes or not. + * + * @param recordChanges whether to record changes or not + */ + void setRecordChanges(boolean recordChanges); + /** * Get a backward directed iterator that can be used for undo. * @@ -63,4 +77,4 @@ public interface ChangeSet { */ int size(); -} +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/annotation/Direction.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/annotation/Direction.java index eac88237c..dbc7d3b29 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/annotation/Direction.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/annotation/Direction.java @@ -19,7 +19,7 @@ package com.sk89q.worldedit.internal.annotation; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -27,7 +27,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Annotates a {@link Vector} parameter to inject a direction. + * Annotates a {@link Vector3} parameter to inject a direction. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) @@ -35,4 +35,5 @@ public @interface Direction { String AIM = "me"; + boolean includeDiagonals() default false; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandLoggingHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandLoggingHandler.java index a6371961f..256f891ec 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandLoggingHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandLoggingHandler.java @@ -26,7 +26,7 @@ import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.Logging; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.platform.Actor; @@ -102,13 +102,13 @@ public class CommandLoggingHandler extends AbstractInvokeListener implements Inv } if (logMode != null && sender.isPlayer()) { - Vector position = player.getLocation().toVector(); + Vector3 position = player.getLocation(); LocalSession session = worldEdit.getSessionManager().get(player); switch (logMode) { case PLACEMENT: try { - position = session.getPlacementPosition(player); + position = session.getPlacementPosition(player).toVector3(); } catch (IncompleteRegionException e) { break; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/WorldEditBinding.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/WorldEditBinding.java index 89c850826..ead5cd02b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/WorldEditBinding.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/WorldEditBinding.java @@ -24,13 +24,12 @@ import com.boydti.fawe.util.MathMan; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.PlayerDirection; import com.sk89q.worldedit.UnknownDirectionException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.extension.input.NoMatchException; @@ -42,6 +41,7 @@ import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.internal.annotation.Direction; import com.sk89q.worldedit.internal.annotation.Selection; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator.TreeType; @@ -64,7 +64,7 @@ import java.util.List; /** * Binds standard WorldEdit classes such as {@link Player} and {@link LocalSession}. */ -public class WorldEditBinding extends BindingHelper { +public class WorldEditBinding { private final WorldEdit worldEdit; @@ -202,10 +202,10 @@ public class WorldEditBinding extends BindingHelper { return result instanceof BlockState ? (BlockState) result : result.toImmutableState(); } - @BindingMatch(type = BaseBlock.class, + @BindingMatch(type = {BaseBlock.class, BlockState.class, BlockStateHolder.class}, behavior = BindingBehavior.CONSUMES, consumedCount = 1) - public BaseBlock getBaseBlock(ArgumentStack context) throws ParameterException, WorldEditException { +public BaseBlock getBaseBlock(ArgumentStack context) throws ParameterException, WorldEditException { return new BaseBlock(getBlockState(context)); } @@ -306,13 +306,17 @@ public class WorldEditBinding extends BindingHelper { * @throws UnknownDirectionException on an unknown direction */ @BindingMatch(classifier = Direction.class, - type = Vector.class, - behavior = BindingBehavior.CONSUMES, - consumedCount = 1) - public Vector getDirection(ArgumentStack context, Direction direction) + type = BlockVector3.class, + behavior = BindingBehavior.CONSUMES, + consumedCount = 1) + public BlockVector3 getDirection(ArgumentStack context, Direction direction) throws ParameterException, UnknownDirectionException { Player sender = getPlayer(context); - return worldEdit.getDirection(sender, context.next()); + if (direction.includeDiagonals()) { + return worldEdit.getDiagonalDirection(sender, context.next()); + } else { + return worldEdit.getDirection(sender, context.next()); + } } /** @@ -356,7 +360,6 @@ public class WorldEditBinding extends BindingHelper { String input = context.next(); if (input != null) { if (MathMan.isInteger(input)) return new BaseBiome(Integer.parseInt(input)); - BiomeRegistry biomeRegistry = WorldEdit.getInstance().getPlatformManager() .queryCapability(Capability.GAME_HOOKS).getRegistries().getBiomeRegistry(); List knownBiomes = biomeRegistry.getBiomes(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionCylinderEvent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionCylinderEvent.java index d23fd9a74..d10f5fb68 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionCylinderEvent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionCylinderEvent.java @@ -21,15 +21,15 @@ package com.sk89q.worldedit.internal.cui; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector2; public class SelectionCylinderEvent implements CUIEvent { - protected final Vector pos; - protected final Vector2D radius; + protected final BlockVector3 pos; + protected final Vector2 radius; - public SelectionCylinderEvent(Vector pos, Vector2D radius) { + public SelectionCylinderEvent(BlockVector3 pos, Vector2 radius) { this.pos = pos; this.radius = radius; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionEllipsoidPointEvent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionEllipsoidPointEvent.java index 3e371b105..e8c051040 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionEllipsoidPointEvent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionEllipsoidPointEvent.java @@ -19,14 +19,14 @@ package com.sk89q.worldedit.internal.cui; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; public class SelectionEllipsoidPointEvent implements CUIEvent { protected final int id; - protected final Vector pos; + protected final BlockVector3 pos; - public SelectionEllipsoidPointEvent(int id, Vector pos) { + public SelectionEllipsoidPointEvent(int id, BlockVector3 pos) { this.id = id; this.pos = pos; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionPoint2DEvent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionPoint2DEvent.java index dc4d0adaa..1586dced9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionPoint2DEvent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionPoint2DEvent.java @@ -19,27 +19,27 @@ package com.sk89q.worldedit.internal.cui; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; public class SelectionPoint2DEvent implements CUIEvent { protected final int id; - protected final int blockx; - protected final int blockz; + protected final int blockX; + protected final int blockZ; protected final int area; - public SelectionPoint2DEvent(int id, Vector2D pos, int area) { + public SelectionPoint2DEvent(int id, BlockVector2 pos, int area) { this.id = id; - this.blockx = pos.getBlockX(); - this.blockz = pos.getBlockZ(); + this.blockX = pos.getX(); + this.blockZ = pos.getZ(); this.area = area; } - public SelectionPoint2DEvent(int id, Vector pos, int area) { + public SelectionPoint2DEvent(int id, BlockVector3 pos, int area) { this.id = id; - this.blockx = pos.getBlockX(); - this.blockz = pos.getBlockZ(); + this.blockX = pos.getX(); + this.blockZ = pos.getZ(); this.area = area; } @@ -52,8 +52,8 @@ public class SelectionPoint2DEvent implements CUIEvent { public String[] getParameters() { return new String[] { String.valueOf(id), - String.valueOf(blockx), - String.valueOf(blockz), + String.valueOf(blockX), + String.valueOf(blockZ), String.valueOf(area) }; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionPointEvent.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionPointEvent.java index e719b1855..baac3ab1f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionPointEvent.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/SelectionPointEvent.java @@ -19,15 +19,15 @@ package com.sk89q.worldedit.internal.cui; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; public class SelectionPointEvent implements CUIEvent { protected final int id; - protected final Vector pos; + protected final BlockVector3 pos; protected final int area; - public SelectionPointEvent(int id, Vector pos, int area) { + public SelectionPointEvent(int id, BlockVector3 pos, int area) { this.id = id; this.pos = pos; this.area = area; 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 new file mode 100644 index 000000000..596f0b63c --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/cui/ServerCUIHandler.java @@ -0,0 +1,158 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.internal.cui; + +import com.sk89q.jnbt.ByteTag; +import com.sk89q.jnbt.CompoundTag; +import com.sk89q.jnbt.IntTag; +import com.sk89q.jnbt.StringTag; +import com.sk89q.jnbt.Tag; +import com.sk89q.worldedit.IncompleteRegionException; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.WorldEdit; + +import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.regions.RegionSelector; +import com.sk89q.worldedit.regions.selector.CuboidRegionSelector; +import com.sk89q.worldedit.world.block.BaseBlock; +import com.sk89q.worldedit.world.block.BlockTypes; + +import java.util.HashMap; +import java.util.Map; + +import javax.annotation.Nullable; + +/** + * Handles creation of server-side CUI systems. + */ +public class ServerCUIHandler { + + private ServerCUIHandler() { + } + + /** + * Creates a structure block that shows the region. + * + *

+ * Null symbolises removal of the CUI. + *

+ * + * @param player The player to create the structure block for. + * @return The structure block, or null + */ + @Nullable + public static BaseBlock createStructureBlock(Player player) { + LocalSession session = WorldEdit.getInstance().getSessionManager().get(player); + RegionSelector regionSelector = session.getRegionSelector(player.getWorld()); + + int posX, posY, posZ; + int width, height, length; + + if (regionSelector instanceof CuboidRegionSelector) { + if (regionSelector.isDefined()) { + try { + CuboidRegion region = ((CuboidRegionSelector) regionSelector).getRegion(); + + posX = region.getMinimumPoint().getBlockX(); + posY = region.getMinimumPoint().getBlockY(); + posZ = region.getMinimumPoint().getBlockZ(); + + width = region.getWidth(); + height = region.getHeight(); + length = region.getLength(); + } catch (IncompleteRegionException e) { + // This will never happen. + e.printStackTrace(); + return null; + } + } else { + CuboidRegion region = ((CuboidRegionSelector) regionSelector).getIncompleteRegion(); + BlockVector3 point; + if (region.getPos1() != null) { + point = region.getPos1(); + } else if (region.getPos2() != null) { + point = region.getPos2(); + } else { + // No more selection + return null; + } + + // Just select the point. + posX = point.getBlockX(); + posY = point.getBlockY(); + posZ = point.getBlockZ(); + width = 1; + height = 1; + length = 1; + } + } else { + // We only support cuboid regions right now. + return null; + } + + if (width > 32 || length > 32 || height > 32) { + // Structure blocks have a limit of 32x32x32 + return null; + } + + // Borrowed this math from FAWE + double rotX = player.getLocation().getYaw(); + double rotY = player.getLocation().getPitch(); + double xz = Math.cos(Math.toRadians(rotY)); + int x = (int) (player.getLocation().getX() - (-xz * Math.sin(Math.toRadians(rotX))) * 12); + int z = (int) (player.getLocation().getZ() - (xz * Math.cos(Math.toRadians(rotX))) * 12); + int y = Math.max(0, Math.min(Math.min(255, posY + 32), posY + 3)); + + Map structureTag = new HashMap<>(); + + posX -= x; + posY -= y; + posZ -= z; + + if (Math.abs(posX) > 32 || Math.abs(posY) > 32 || Math.abs(posZ) > 32) { + // Structure blocks have a limit + return null; + } + + structureTag.put("name", new StringTag("worldedit:" + player.getName())); + structureTag.put("author", new StringTag(player.getName())); + structureTag.put("metadata", new StringTag("")); + structureTag.put("x", new IntTag(x)); + structureTag.put("y", new IntTag(y)); + structureTag.put("z", new IntTag(z)); + structureTag.put("posX", new IntTag(posX)); + structureTag.put("posY", new IntTag(posY)); + structureTag.put("posZ", new IntTag(posZ)); + structureTag.put("sizeX", new IntTag(width)); + structureTag.put("sizeY", new IntTag(height)); + structureTag.put("sizeZ", new IntTag(length)); + structureTag.put("rotation", new StringTag("NONE")); + structureTag.put("mirror", new StringTag("NONE")); + structureTag.put("mode", new StringTag("SAVE")); + structureTag.put("ignoreEntities", new ByteTag((byte) 1)); + structureTag.put("showboundingbox", new ByteTag((byte) 1)); + structureTag.put("id", new StringTag(BlockTypes.STRUCTURE_BLOCK.getId())); + +// return BlockTypes.STRUCTURE_BLOCK.getDefaultState().toBaseBlock(new CompoundTag(structureTag)); + return new BaseBlock(BlockTypes.STRUCTURE_BLOCK.getDefaultState(), new CompoundTag(structureTag)); + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/Expression.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/Expression.java index 41cb27134..17460fc1f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/Expression.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/Expression.java @@ -69,7 +69,7 @@ public class Expression { private static final ThreadLocal> instance = ThreadLocal.withInitial(ArrayDeque::new); - private final Map variables = new HashMap(); + private final Map variables = new HashMap<>(); private final String[] variableNames; private Variable[] variableArray; private RValue root; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/runtime/Functions.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/runtime/Functions.java index 612709ff7..088cef4c2 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/runtime/Functions.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/expression/runtime/Functions.java @@ -19,11 +19,11 @@ package com.sk89q.worldedit.internal.expression.runtime; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; + import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.runtime.Function.Dynamic; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.noise.PerlinNoise; import com.sk89q.worldedit.math.noise.RidgedMultiFractalNoise; import com.sk89q.worldedit.math.noise.VoronoiNoise; @@ -124,7 +124,7 @@ public final class Functions { throw new NoSuchMethodException(); // TODO: return null (check for side-effects first) } - private static final Map> functions = new HashMap>(); + private static final Map> functions = new HashMap<>(); static { for (Method method : Functions.class.getMethods()) { @@ -143,7 +143,7 @@ public final class Functions { List overloads = functions.get(methodName); if (overloads == null) { - functions.put(methodName, overloads = new ArrayList()); + functions.put(methodName, overloads = new ArrayList<>()); } overloads.add(overload); @@ -281,8 +281,8 @@ public final class Functions { } - private static final Map gmegabuf = new HashMap(); - private final Map megabuf = new HashMap(); + private static final Map gmegabuf = new HashMap<>(); + private final Map megabuf = new HashMap<>(); public Map getMegabuf() { return megabuf; @@ -397,7 +397,7 @@ public final class Functions { } catch (IllegalArgumentException e) { throw new EvaluationException(0, "Perlin noise error: " + e.getMessage()); } - return perlin.noise(new Vector(x.getValue(), y.getValue(), z.getValue())); + return perlin.noise(Vector3.at(x.getValue(), y.getValue(), z.getValue())); } private static final ThreadLocal localVoronoi = ThreadLocal.withInitial(VoronoiNoise::new); @@ -410,7 +410,7 @@ public final class Functions { } catch (IllegalArgumentException e) { throw new EvaluationException(0, "Voronoi error: " + e.getMessage()); } - return voronoi.noise(new Vector(x.getValue(), y.getValue(), z.getValue())); + return voronoi.noise(Vector3.at(x.getValue(), y.getValue(), z.getValue())); } private static final ThreadLocal localRidgedMulti = ThreadLocal.withInitial(RidgedMultiFractalNoise::new); @@ -424,7 +424,7 @@ public final class Functions { } catch (IllegalArgumentException e) { throw new EvaluationException(0, "Ridged multi error: " + e.getMessage()); } - return ridgedMulti.noise(new Vector(x.getValue(), y.getValue(), z.getValue())); + return ridgedMulti.noise(Vector3.at(x.getValue(), y.getValue(), z.getValue())); } private static double queryInternal(RValue type, RValue data, double typeId, double dataValue) throws EvaluationException { 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 506663a81..fcee6abcc 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 @@ -27,6 +27,7 @@ import com.sk89q.worldedit.extension.input.NoMatchException; import com.sk89q.worldedit.extension.input.ParserContext; import java.util.ArrayList; +import java.util.Collections; import java.util.List; /** @@ -38,7 +39,7 @@ import java.util.List; public abstract class AbstractFactory { protected final WorldEdit worldEdit; - protected final List> parsers = new ArrayList<>(); + private final List> parsers = new ArrayList<>(); /** * Create a new factory. @@ -50,6 +51,17 @@ public abstract class AbstractFactory { this.worldEdit = worldEdit; } + /** + * Gets an immutable list of parsers. + * + * To add parsers, use the register method. + * + * @return the parsers + */ + public List> getParsers() { + return Collections.unmodifiableList(parsers); + } + public E parseFromInput(String input, ParserContext context) throws InputParseException { E match; @@ -64,4 +76,14 @@ public abstract class AbstractFactory { throw new NoMatchException("No match for '" + input + "'"); } + /** + * Registers an InputParser to this factory + * + * @param inputParser The input parser + */ + public void register(InputParser inputParser) { + checkNotNull(inputParser); + + parsers.add(inputParser); + } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/InputParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/InputParser.java index 77c05c2e3..ee40fa3b9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/InputParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/InputParser.java @@ -19,10 +19,13 @@ package com.sk89q.worldedit.internal.registry; +import com.google.common.collect.Lists; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.ParserContext; +import java.util.List; + /** * Input parser interface for {@link AbstractFactory}. * @@ -33,10 +36,18 @@ public abstract class InputParser { protected final WorldEdit worldEdit; - protected InputParser(WorldEdit worldEdit) { + public InputParser(WorldEdit worldEdit) { this.worldEdit = worldEdit; } public abstract E parseFromInput(String input, ParserContext context) throws InputParseException; + /** + * Gets a list of suggestions of input to this parser. + * + * @return a list of suggestions + */ + public List getSuggestions() { + return Lists.newArrayList(); + } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/SimpleInputParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/SimpleInputParser.java new file mode 100644 index 000000000..d0647f9cc --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/registry/SimpleInputParser.java @@ -0,0 +1,71 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.internal.registry; + +import com.google.common.collect.Lists; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.input.InputParseException; +import com.sk89q.worldedit.extension.input.ParserContext; + +import java.util.List; + +/** + * An input parser that only performs a single function from aliases. + * + * @param the element + */ +public abstract class SimpleInputParser extends InputParser { + + public SimpleInputParser(WorldEdit worldEdit) { + super(worldEdit); + } + + /** + * The strings this parser matches + * + * @return the matching aliases + */ + public abstract List getMatchedAliases(); + + @Override + public E parseFromInput(String input, ParserContext context) throws InputParseException { + if (!getMatchedAliases().contains(input)) { + return null; + } + + return parseFromSimpleInput(input, context); + } + + public abstract E parseFromSimpleInput(String input, ParserContext context) throws InputParseException; + + /** + * Gets the primary name of this matcher + * + * @return the primary match + */ + public String getPrimaryMatcher() { + return getMatchedAliases().get(0); + } + + @Override + public List getSuggestions() { + return Lists.newArrayList(getPrimaryMatcher()); + } +} 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 new file mode 100644 index 000000000..c2e6cf904 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector2.java @@ -0,0 +1,578 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.math; + +import com.google.common.collect.ComparisonChain; +import com.sk89q.worldedit.math.transform.AffineTransform; + +import java.util.Comparator; + +/** + * An immutable 2-dimensional vector. + */ +public class BlockVector2 { + + public static final BlockVector2 ZERO = new BlockVector2(0, 0); + public static final BlockVector2 UNIT_X = new BlockVector2(1, 0); + public static final BlockVector2 UNIT_Z = new BlockVector2(0, 1); + public static final BlockVector2 ONE = new BlockVector2(1, 1); + + /** + * A comparator for BlockVector2ds that orders the vectors by rows, with x as the + * column and z as the row. + * + * For example, if x is the horizontal axis and z is the vertical axis, it + * sorts like so: + * + *
+     * 0123
+     * 4567
+     * 90ab
+     * cdef
+     * 
+ */ + public static final Comparator COMPARING_GRID_ARRANGEMENT = (a, b) -> { + return ComparisonChain.start() + .compare(a.getBlockZ(), b.getBlockZ()) + .compare(a.getBlockX(), b.getBlockX()) + .result(); + }; + + public static BlockVector2 at(double x, double z) { + return at((int) Math.floor(x), (int) Math.floor(z)); + } + + public static BlockVector2 at(int x, int z) { + return new BlockVector2(x, z); + } + + protected int x, z; + + protected BlockVector2(){} + + /** + * Construct an instance. + * + * @param x the X coordinate + * @param z the Z coordinate + */ + protected BlockVector2(int x, int z) { + this.x = x; + this.z = z; + } + + public MutableBlockVector2 setComponents(int x, int z) { + return new MutableBlockVector2(x, z); + } + + public MutableBlockVector2 mutX(double x) { + return new MutableBlockVector2((int) x, z); + } + + public MutableBlockVector2 mutZ(double z) { + return new MutableBlockVector2(x, (int) z); + } + + public MutableBlockVector2 mutX(int x) { + return new MutableBlockVector2(x, z); + } + + public MutableBlockVector2 mutZ(int z) { + return new MutableBlockVector2(x, z); + } + + /** + * Get the X coordinate. + * + * @return the x coordinate + */ + public int getX() { + return x; + } + + /** + * Get the X coordinate. + * + * @return the x coordinate + */ + public int getBlockX() { + return x; + } + + /** + * Set the X coordinate. + * + * @param x the new X + * @return a new vector + */ + public BlockVector2 withX(int x) { + return BlockVector2.at(x, z); + } + + /** + * Get the Z coordinate. + * + * @return the z coordinate + */ + public int getZ() { + return z; + } + + /** + * Get the Z coordinate. + * + * @return the z coordinate + */ + public int getBlockZ() { + return z; + } + + /** + * Set the Z coordinate. + * + * @param z the new Z + * @return a new vector + */ + public BlockVector2 withZ(int z) { + return BlockVector2.at(x, z); + } + + public MutableBlockVector2 nextPosition() { + int absX = Math.abs(x); + int absY = Math.abs(z); + if (absX > absY) { + if (x > 0) { + return setComponents(x, z + 1); + } else { + return setComponents(x, z - 1); + } + } else if (absY > absX) { + if (z > 0) { + return setComponents(x - 1, z); + } else { + return setComponents(x + 1, z); + } + } else { + if (x == z && x > 0) { + return setComponents(x, z + 1); + } + if (x == absX) { + return setComponents(x, z + 1); + } + if (z == absY) { + return setComponents(x, z - 1); + } + return setComponents(x + 1, z); + } + } + + /** + * Add another vector to this vector and return the result as a new vector. + * + * @param other the other vector + * @return a new vector + */ + public BlockVector2 add(BlockVector2 other) { + return add(other.x, other.z); + } + + /** + * Add another vector to this vector and return the result as a new vector. + * + * @param x the value to add + * @param z the value to add + * @return a new vector + */ + public BlockVector2 add(int x, int z) { + return BlockVector2.at(this.x + x, this.z + z); + } + + /** + * Add a list of vectors to this vector and return the + * result as a new vector. + * + * @param others an array of vectors + * @return a new vector + */ + public BlockVector2 add(BlockVector2... others) { + int newX = x, newZ = z; + + for (BlockVector2 other : others) { + newX += other.x; + newZ += other.z; + } + + return BlockVector2.at(newX, newZ); + } + + /** + * Subtract another vector from this vector and return the result + * as a new vector. + * + * @param other the other vector + * @return a new vector + */ + public BlockVector2 subtract(BlockVector2 other) { + return subtract(other.x, other.z); + } + + /** + * Subtract another vector from this vector and return the result + * as a new vector. + * + * @param x the value to subtract + * @param z the value to subtract + * @return a new vector + */ + public BlockVector2 subtract(int x, int z) { + return BlockVector2.at(this.x - x, this.z - z); + } + + /** + * Subtract a list of vectors from this vector and return the result + * as a new vector. + * + * @param others an array of vectors + * @return a new vector + */ + public BlockVector2 subtract(BlockVector2... others) { + int newX = x, newZ = z; + + for (BlockVector2 other : others) { + newX -= other.x; + newZ -= other.z; + } + + return BlockVector2.at(newX, newZ); + } + + /** + * Multiply this vector by another vector on each component. + * + * @param other the other vector + * @return a new vector + */ + public BlockVector2 multiply(BlockVector2 other) { + return multiply(other.x, other.z); + } + + /** + * Multiply this vector by another vector on each component. + * + * @param x the value to multiply + * @param z the value to multiply + * @return a new vector + */ + public BlockVector2 multiply(int x, int z) { + return BlockVector2.at(this.x * x, this.z * z); + } + + /** + * Multiply this vector by zero or more vectors on each component. + * + * @param others an array of vectors + * @return a new vector + */ + public BlockVector2 multiply(BlockVector2... others) { + int newX = x, newZ = z; + + for (BlockVector2 other : others) { + newX *= other.x; + newZ *= other.z; + } + + return BlockVector2.at(newX, newZ); + } + + /** + * Perform scalar multiplication and return a new vector. + * + * @param n the value to multiply + * @return a new vector + */ + public BlockVector2 multiply(int n) { + return multiply(n, n); + } + + /** + * Divide this vector by another vector on each component. + * + * @param other the other vector + * @return a new vector + */ + public BlockVector2 divide(BlockVector2 other) { + return divide(other.x, other.z); + } + + /** + * Divide this vector by another vector on each component. + * + * @param x the value to divide by + * @param z the value to divide by + * @return a new vector + */ + public BlockVector2 divide(int x, int z) { + return BlockVector2.at(this.x / x, this.z / z); + } + + /** + * Perform scalar division and return a new vector. + * + * @param n the value to divide by + * @return a new vector + */ + public BlockVector2 divide(int n) { + return divide(n, n); + } + + /** + * Get the length of the vector. + * + * @return length + */ + public double length() { + return Math.sqrt(lengthSq()); + } + + /** + * Get the length, squared, of the vector. + * + * @return length, squared + */ + public int lengthSq() { + return x * x + z * z; + } + + /** + * Get the distance between this vector and another vector. + * + * @param other the other vector + * @return distance + */ + public double distance(BlockVector2 other) { + return Math.sqrt(distanceSq(other)); + } + + /** + * Get the distance between this vector and another vector, squared. + * + * @param other the other vector + * @return distance + */ + public int distanceSq(BlockVector2 other) { + int dx = other.x - x; + int dz = other.z - z; + return dx * dx + dz * dz; + } + + /** + * Get the normalized vector, which is the vector divided by its + * length, as a new vector. + * + * @return a new vector + */ + public BlockVector2 normalize() { + double len = length(); + double x = this.x / len; + double z = this.z / len; + return BlockVector2.at(x, z); + } + + /** + * Gets the dot product of this and another vector. + * + * @param other the other vector + * @return the dot product of this and the other vector + */ + public int dot(BlockVector2 other) { + return x * other.x + z * other.z; + } + + /** + * Checks to see if a vector is contained with another. + * + * @param min the minimum point (X, Y, and Z are the lowest) + * @param max the maximum point (X, Y, and Z are the lowest) + * @return true if the vector is contained + */ + public boolean containedWithin(BlockVector2 min, BlockVector2 max) { + return x >= min.x && x <= max.x + && z >= min.z && z <= max.z; + } + + /** + * Floors the values of all components. + * + * @return a new vector + */ + public BlockVector2 floor() { + // already floored, kept for feature parity with Vector2 + return this; + } + + /** + * Rounds all components up. + * + * @return a new vector + */ + public BlockVector2 ceil() { + // already raised, kept for feature parity with Vector2 + return this; + } + + /** + * Rounds all components to the closest integer. + * + *

Components < 0.5 are rounded down, otherwise up.

+ * + * @return a new vector + */ + public BlockVector2 round() { + // already rounded, kept for feature parity with Vector2 + return this; + } + + /** + * Returns a vector with the absolute values of the components of + * this vector. + * + * @return a new vector + */ + public BlockVector2 abs() { + return BlockVector2.at(Math.abs(x), Math.abs(z)); + } + + /** + * Perform a 2D transformation on this vector and return a new one. + * + * @param angle in degrees + * @param aboutX about which x coordinate to rotate + * @param aboutZ about which z coordinate to rotate + * @param translateX what to add after rotation + * @param translateZ what to add after rotation + * @return a new vector + * @see AffineTransform another method to transform vectors + */ + public BlockVector2 transform2D(double angle, double aboutX, double aboutZ, double translateX, double translateZ) { + angle = Math.toRadians(angle); + double x = this.x - aboutX; + double z = this.z - aboutZ; + double cos = Math.cos(angle); + double sin = Math.sin(angle); + double x2 = x * cos - z * sin; + double z2 = x * sin + z * cos; + return BlockVector2.at( + x2 + aboutX + translateX, + z2 + aboutZ + translateZ); + } + + /** + * Gets the minimum components of two vectors. + * + * @param v2 the second vector + * @return minimum + */ + public BlockVector2 getMinimum(BlockVector2 v2) { + return new BlockVector2( + Math.min(x, v2.x), + Math.min(z, v2.z) + ); + } + + /** + * Gets the maximum components of two vectors. + * + * @param v2 the second vector + * @return maximum + */ + public BlockVector2 getMaximum(BlockVector2 v2) { + return new BlockVector2( + Math.max(x, v2.x), + Math.max(z, v2.z) + ); + } + + public Vector2 toVector2() { + return Vector2.at(x, z); + } + + /** + * Creates a 3D vector by adding a zero Y component to this vector. + * + * @return a new vector + */ + public Vector3 toVector3() { + return toVector3(0); + } + + /** + * Creates a 3D vector by adding the specified Y component to this vector. + * + * @param y the Y component + * @return a new vector + */ + public Vector3 toVector3(double y) { + return Vector3.at(x, y, z); + } + + /** + * Creates a 3D vector by adding a zero Y component to this vector. + * + * @return a new vector + */ + public BlockVector3 toBlockVector3() { + return toBlockVector3(0); + } + + /** + * Creates a 3D vector by adding the specified Y component to this vector. + * + * @param y the Y component + * @return a new vector + */ + public BlockVector3 toBlockVector3(int y) { + return BlockVector3.at(x, y, z); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof BlockVector2)) { + return false; + } + + BlockVector2 other = (BlockVector2) obj; + return other.x == this.x && other.z == this.z; + + } + + @Override + public int hashCode() { + int hash = 17; + hash = 31 * hash + Integer.hashCode(x); + hash = 31 * hash + Integer.hashCode(z); + return hash; + } + + @Override + public String toString() { + return "(" + x + ", " + z + ")"; + } + +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector3.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector3.java new file mode 100644 index 000000000..367efdb69 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/BlockVector3.java @@ -0,0 +1,644 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.math; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.common.collect.ComparisonChain; +import com.sk89q.worldedit.math.transform.AffineTransform; + +import java.util.Comparator; + +/** + * An immutable 3-dimensional vector. + */ +public class BlockVector3 { + + public static final BlockVector3 ZERO = new BlockVector3(0, 0, 0); + public static final BlockVector3 UNIT_X = new BlockVector3(1, 0, 0); + public static final BlockVector3 UNIT_Y = new BlockVector3(0, 1, 0); + public static final BlockVector3 UNIT_Z = new BlockVector3(0, 0, 1); + public static final BlockVector3 ONE = new BlockVector3(1, 1, 1); + + public static BlockVector3 at(double x, double y, double z) { + return at((int) Math.floor(x), (int) Math.floor(y), (int) Math.floor(z)); + } + + public static BlockVector3 at(int x, int y, int z) { + return new BlockVector3(x, y, z); + } + + // thread-safe initialization idiom + private static final class YzxOrderComparator { + private static final Comparator YZX_ORDER = (a, b) -> { + return ComparisonChain.start() + .compare(a.y, b.y) + .compare(a.z, b.z) + .compare(a.x, b.x) + .result(); + }; + } + + /** + * Returns a comparator that sorts vectors first by Y, then Z, then X. + * + *

+ * Useful for sorting by chunk block storage order. + */ + public static Comparator sortByCoordsYzx() { + return YzxOrderComparator.YZX_ORDER; + } + + protected int x, y, z; + + protected BlockVector3(){} + + /** + * Construct an instance. + * + * @param x the X coordinate + * @param y the Y coordinate + * @param z the Z coordinate + */ + protected BlockVector3(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + public MutableBlockVector3 setComponents(double x, double y, double z) { + return new MutableBlockVector3((int) x, (int) y, (int) z); + } + + public MutableBlockVector3 setComponents(int x, int y, int z) { + return new MutableBlockVector3(x, y, z); + } + + public MutableBlockVector3 mutX(double x) { + return new MutableBlockVector3((int) x, y, z); + } + + public MutableBlockVector3 mutY(double y) { + return new MutableBlockVector3(x, (int) y, z); + } + + public MutableBlockVector3 mutZ(double z) { + return new MutableBlockVector3(x, y, (int) z); + } + + public MutableBlockVector3 mutX(int x) { + return new MutableBlockVector3(x, y, z); + } + + public MutableBlockVector3 mutY(int y) { + return new MutableBlockVector3(x, y, z); + } + + public MutableBlockVector3 mutZ(int z) { + return new MutableBlockVector3(x, y, z); + } + + /** + * Get the X coordinate. + * + * @return the x coordinate + */ + public int getX() { + return x; + } + + /** + * Get the X coordinate. + * + * @return the x coordinate + */ + public int getBlockX() { + return x; + } + + /** + * Set the X coordinate. + * + * @param x the new X + * @return a new vector + */ + public BlockVector3 withX(int x) { + return BlockVector3.at(x, y, z); + } + + /** + * Get the Y coordinate. + * + * @return the y coordinate + */ + public int getY() { + return y; + } + + /** + * Get the Y coordinate. + * + * @return the y coordinate + */ + public int getBlockY() { + return y; + } + + /** + * Set the Y coordinate. + * + * @param y the new Y + * @return a new vector + */ + public BlockVector3 withY(int y) { + return BlockVector3.at(x, y, z); + } + + /** + * Get the Z coordinate. + * + * @return the z coordinate + */ + public int getZ() { + return z; + } + + /** + * Get the Z coordinate. + * + * @return the z coordinate + */ + public int getBlockZ() { + return z; + } + + /** + * Set the Z coordinate. + * + * @param z the new Z + * @return a new vector + */ + public BlockVector3 withZ(int z) { + return BlockVector3.at(x, y, z); + } + + /** + * Add another vector to this vector and return the result as a new vector. + * + * @param other the other vector + * @return a new vector + */ + public BlockVector3 add(BlockVector3 other) { + return add(other.x, other.y, other.z); + } + + /** + * Add another vector to this vector and return the result as a new vector. + * + * @param x the value to add + * @param y the value to add + * @param z the value to add + * @return a new vector + */ + public BlockVector3 add(int x, int y, int z) { + return BlockVector3.at(this.x + x, this.y + y, this.z + z); + } + + /** + * Add a list of vectors to this vector and return the + * result as a new vector. + * + * @param others an array of vectors + * @return a new vector + */ + public BlockVector3 add(BlockVector3... others) { + int newX = x, newY = y, newZ = z; + + for (BlockVector3 other : others) { + newX += other.x; + newY += other.y; + newZ += other.z; + } + + return BlockVector3.at(newX, newY, newZ); + } + + /** + * Subtract another vector from this vector and return the result + * as a new vector. + * + * @param other the other vector + * @return a new vector + */ + public BlockVector3 subtract(BlockVector3 other) { + return subtract(other.x, other.y, other.z); + } + + /** + * Subtract another vector from this vector and return the result + * as a new vector. + * + * @param x the value to subtract + * @param y the value to subtract + * @param z the value to subtract + * @return a new vector + */ + public BlockVector3 subtract(int x, int y, int z) { + return BlockVector3.at(this.x - x, this.y - y, this.z - z); + } + + /** + * Subtract a list of vectors from this vector and return the result + * as a new vector. + * + * @param others an array of vectors + * @return a new vector + */ + public BlockVector3 subtract(BlockVector3... others) { + int newX = x, newY = y, newZ = z; + + for (BlockVector3 other : others) { + newX -= other.x; + newY -= other.y; + newZ -= other.z; + } + + return BlockVector3.at(newX, newY, newZ); + } + + /** + * Multiply this vector by another vector on each component. + * + * @param other the other vector + * @return a new vector + */ + public BlockVector3 multiply(BlockVector3 other) { + return multiply(other.x, other.y, other.z); + } + + /** + * Multiply this vector by another vector on each component. + * + * @param x the value to multiply + * @param y the value to multiply + * @param z the value to multiply + * @return a new vector + */ + public BlockVector3 multiply(int x, int y, int z) { + return BlockVector3.at(this.x * x, this.y * y, this.z * z); + } + + /** + * Multiply this vector by zero or more vectors on each component. + * + * @param others an array of vectors + * @return a new vector + */ + public BlockVector3 multiply(BlockVector3... others) { + int newX = x, newY = y, newZ = z; + + for (BlockVector3 other : others) { + newX *= other.x; + newY *= other.y; + newZ *= other.z; + } + + return BlockVector3.at(newX, newY, newZ); + } + + /** + * Perform scalar multiplication and return a new vector. + * + * @param n the value to multiply + * @return a new vector + */ + public BlockVector3 multiply(int n) { + return multiply(n, n, n); + } + + /** + * Divide this vector by another vector on each component. + * + * @param other the other vector + * @return a new vector + */ + public BlockVector3 divide(BlockVector3 other) { + return divide(other.x, other.y, other.z); + } + + /** + * Divide this vector by another vector on each component. + * + * @param x the value to divide by + * @param y the value to divide by + * @param z the value to divide by + * @return a new vector + */ + public BlockVector3 divide(int x, int y, int z) { + return BlockVector3.at(this.x / x, this.y / y, this.z / z); + } + + /** + * Perform scalar division and return a new vector. + * + * @param n the value to divide by + * @return a new vector + */ + public BlockVector3 divide(int n) { + return divide(n, n, n); + } + + /** + * Get the length of the vector. + * + * @return length + */ + public double length() { + return Math.sqrt(lengthSq()); + } + + /** + * Get the length, squared, of the vector. + * + * @return length, squared + */ + public int lengthSq() { + return x * x + y * y + z * z; + } + + /** + * Get the distance between this vector and another vector. + * + * @param other the other vector + * @return distance + */ + public double distance(BlockVector3 other) { + return Math.sqrt(distanceSq(other)); + } + + /** + * Get the distance between this vector and another vector, squared. + * + * @param other the other vector + * @return distance + */ + public int distanceSq(BlockVector3 other) { + int dx = other.x - x; + int dy = other.y - y; + int dz = other.z - z; + return dx * dx + dy * dy + dz * dz; + } + + /** + * Get the normalized vector, which is the vector divided by its + * length, as a new vector. + * + * @return a new vector + */ + public BlockVector3 normalize() { + double len = length(); + double x = this.x / len; + double y = this.y / len; + double z = this.z / len; + return BlockVector3.at(x, y, z); + } + + /** + * Gets the dot product of this and another vector. + * + * @param other the other vector + * @return the dot product of this and the other vector + */ + public double dot(BlockVector3 other) { + return x * other.x + y * other.y + z * other.z; + } + + /** + * Gets the cross product of this and another vector. + * + * @param other the other vector + * @return the cross product of this and the other vector + */ + public BlockVector3 cross(BlockVector3 other) { + return new BlockVector3( + y * other.z - z * other.y, + z * other.x - x * other.z, + x * other.y - y * other.x + ); + } + + /** + * Checks to see if a vector is contained with another. + * + * @param min the minimum point (X, Y, and Z are the lowest) + * @param max the maximum point (X, Y, and Z are the lowest) + * @return true if the vector is contained + */ + public boolean containedWithin(BlockVector3 min, BlockVector3 max) { + return x >= min.x && x <= max.x && y >= min.y && y <= max.y && z >= min.z && z <= max.z; + } + + /** + * Clamp the Y component. + * + * @param min the minimum value + * @param max the maximum value + * @return a new vector + */ + public BlockVector3 clampY(int min, int max) { + checkArgument(min <= max, "minimum cannot be greater than maximum"); + if (y < min) { + return BlockVector3.at(x, min, z); + } + if (y > max) { + return BlockVector3.at(x, max, z); + } + return this; + } + + /** + * Floors the values of all components. + * + * @return a new vector + */ + public BlockVector3 floor() { + // already floored, kept for feature parity with Vector3 + return this; + } + + /** + * Rounds all components up. + * + * @return a new vector + */ + public BlockVector3 ceil() { + // already raised, kept for feature parity with Vector3 + return this; + } + + /** + * Rounds all components to the closest integer. + * + *

Components < 0.5 are rounded down, otherwise up.

+ * + * @return a new vector + */ + public BlockVector3 round() { + // already rounded, kept for feature parity with Vector3 + return this; + } + + /** + * Returns a vector with the absolute values of the components of + * this vector. + * + * @return a new vector + */ + public BlockVector3 abs() { + return BlockVector3.at(Math.abs(x), Math.abs(y), Math.abs(z)); + } + + /** + * Perform a 2D transformation on this vector and return a new one. + * + * @param angle in degrees + * @param aboutX about which x coordinate to rotate + * @param aboutZ about which z coordinate to rotate + * @param translateX what to add after rotation + * @param translateZ what to add after rotation + * @return a new vector + * @see AffineTransform another method to transform vectors + */ + public BlockVector3 transform2D(double angle, double aboutX, double aboutZ, double translateX, double translateZ) { + angle = Math.toRadians(angle); + double x = this.x - aboutX; + double z = this.z - aboutZ; + double cos = Math.cos(angle); + double sin = Math.sin(angle); + double x2 = x * cos - z * sin; + double z2 = x * sin + z * cos; + + return BlockVector3.at( + x2 + aboutX + translateX, + y, + z2 + aboutZ + translateZ + ); + } + + /** + * Get this vector's pitch as used within the game. + * + * @return pitch in radians + */ + public double toPitch() { + double x = getX(); + double z = getZ(); + + if (x == 0 && z == 0) { + return getY() > 0 ? -90 : 90; + } else { + double x2 = x * x; + double z2 = z * z; + double xz = Math.sqrt(x2 + z2); + return Math.toDegrees(Math.atan(-getY() / xz)); + } + } + + /** + * Get this vector's yaw as used within the game. + * + * @return yaw in radians + */ + public double toYaw() { + double x = getX(); + double z = getZ(); + + double t = Math.atan2(-x, z); + double tau = 2 * Math.PI; + + return Math.toDegrees(((t + tau) % tau)); + } + + /** + * Gets the minimum components of two vectors. + * + * @param v2 the second vector + * @return minimum + */ + public BlockVector3 getMinimum(BlockVector3 v2) { + return new BlockVector3( + Math.min(x, v2.x), + Math.min(y, v2.y), + Math.min(z, v2.z) + ); + } + + /** + * Gets the maximum components of two vectors. + * + * @param v2 the second vector + * @return maximum + */ + public BlockVector3 getMaximum(BlockVector3 v2) { + return new BlockVector3( + Math.max(x, v2.x), + Math.max(y, v2.y), + Math.max(z, v2.z) + ); + } + + /** + * Creates a 2D vector by dropping the Y component from this vector. + * + * @return a new {@link BlockVector2} + */ + public BlockVector2 toBlockVector2() { + return BlockVector2.at(x, z); + } + + public Vector3 toVector3() { + return Vector3.at(x, y, z); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof BlockVector3)) { + return false; + } + + BlockVector3 other = (BlockVector3) obj; + return other.x == this.x && other.y == this.y && other.z == this.z; + } + + @Override + public int hashCode() { + int hash = 17; + hash = 31 * hash + Integer.hashCode(x); + hash = 31 * hash + Integer.hashCode(y); + hash = 31 * hash + Integer.hashCode(z); + return hash; + } + + @Override + public String toString() { + return "(" + x + ", " + y + ", " + z + ")"; + } + +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/MathUtils.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/MathUtils.java index 3bc9d6f5b..f0f7b67fb 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/MathUtils.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/MathUtils.java @@ -117,4 +117,34 @@ public final class MathUtils { public static double roundHalfUp(double value) { return Math.signum(value) * Math.round(Math.abs(value)); } + + /** + * Returns the midpoint Vector3 of the two given Vector3's. + * + * @param first Vector3 + * @param second Vector3 + * @return midpoint Vector3 + */ + public static Vector3 midpoint(Vector3 v1, Vector3 v2) { + return Vector3.at( + (v1.getX() + v2.getX()) / 2, + (v1.getY() + v2.getY()) / 2, + (v1.getZ() + v2.getZ()) / 2 + ); + } + + /** + * Returns the midpoint BlockVector3 of the two given BlockVector3's. + * + * @param first BlockVector3 + * @param second BlockVector3 + * @return midpoint BlockVector3 + */ + public static BlockVector3 midpoint(BlockVector3 v1, BlockVector3 v2) { + return BlockVector3.at( + (v1.getBlockX() + v2.getBlockX()) / 2, + (v1.getBlockY() + v2.getBlockY()) / 2, + (v1.getBlockZ() + v2.getBlockZ()) / 2 + ); + } } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableBlockVector2.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableBlockVector2.java new file mode 100644 index 000000000..13bcb5cd4 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableBlockVector2.java @@ -0,0 +1,52 @@ +package com.sk89q.worldedit.math; + +public class MutableBlockVector2 extends BlockVector2 { + + private static ThreadLocal MUTABLE_CACHE = new ThreadLocal() { + @Override + protected MutableBlockVector2 initialValue() { + return new MutableBlockVector2(); + } + }; + + public static MutableBlockVector2 get(int x, int z) { + return MUTABLE_CACHE.get().setComponents(x, z); + } + + public MutableBlockVector2() {} + + public MutableBlockVector2(int x, int z) { + super(x, z); + } + + @Override + public MutableBlockVector2 setComponents(int x, int z) { + this.x = x; + this.z = z; + return this; + } + + @Override + public MutableBlockVector2 mutX(double x) { + this.x = (int) x; + return this; + } + + @Override + public MutableBlockVector2 mutZ(double z) { + this.z = (int) z; + return this; + } + + @Override + public MutableBlockVector2 mutX(int x) { + this.x = x; + return this; + } + + @Override + public MutableBlockVector2 mutZ(int z) { + this.z = z; + return this; + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableBlockVector3.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableBlockVector3.java new file mode 100644 index 000000000..89ee154f5 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableBlockVector3.java @@ -0,0 +1,73 @@ +package com.sk89q.worldedit.math; + +public class MutableBlockVector3 extends BlockVector3 { + + private static ThreadLocal MUTABLE_CACHE = new ThreadLocal() { + @Override + protected MutableBlockVector3 initialValue() { + return new MutableBlockVector3(); + } + }; + + public static MutableBlockVector3 get(int x, int y, int z) { + return MUTABLE_CACHE.get().setComponents(x, y, z); + } + + public MutableBlockVector3() {} + + public MutableBlockVector3(BlockVector3 other) { + super(other.getX(), other.getY(), other.getZ()); + } + + public MutableBlockVector3 setComponents(BlockVector3 other) { + return setComponents(other.getBlockX(), other.getBlockY(), other.getBlockZ()); + } + + public MutableBlockVector3(int x, int y, int z) { + super(x, y, z); + } + + @Override + public MutableBlockVector3 setComponents(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + return this; + } + + @Override + public MutableBlockVector3 mutX(double x) { + this.x = (int) x; + return this; + } + + @Override + public MutableBlockVector3 mutY(double y) { + this.y = (int) y; + return this; + } + + @Override + public MutableBlockVector3 mutZ(double z) { + this.z = (int) z; + return this; + } + + @Override + public final MutableBlockVector3 mutX(int x) { + this.x = x; + return this; + } + + @Override + public final MutableBlockVector3 mutY(int y) { + this.y = y; + return this; + } + + @Override + public final MutableBlockVector3 mutZ(int z) { + this.z = z; + return this; + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableVector2.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableVector2.java new file mode 100644 index 000000000..4b4133d5c --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableVector2.java @@ -0,0 +1,70 @@ +package com.sk89q.worldedit.math; + +import java.io.Serializable; + +public class MutableVector2 extends Vector2 { + public MutableVector2() {} + + /** + * Construct an instance. + * + * @param x the X coordinate + * @param z the Z coordinate + */ + public MutableVector2(double x, double z) { + super(x, z); + } + + /** + * Construct an instance. + * + * @param x the X coordinate + * @param z the Z coordinate + */ + public MutableVector2(float x, float z) { + super(x, z); + } + + /** + * Copy another vector. + * + * @param other the other vector + */ + public MutableVector2(Vector2 other) { + super(other); + } + + @Override + public MutableVector2 setComponents(int x, int z) { + this.x = x; + this.z = z; + return this; + } + + @Override + public MutableVector2 setComponents(double x, double z) { + this.x = x; + this.z = z; + return this; + } + @Override + public MutableVector2 mutX(int x) { + this.x = x; + return this; + } + @Override + public MutableVector2 mutZ(int z) { + this.z = z; + return this; + } + @Override + public MutableVector2 mutX(double x) { + this.x = x; + return this; + } + @Override + public MutableVector2 mutZ(double z) { + this.z = z; + return this; + } +} 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 new file mode 100644 index 000000000..e1810a4b6 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/MutableVector3.java @@ -0,0 +1,82 @@ +package com.sk89q.worldedit.math; + +import javax.annotation.Nullable; + +public class MutableVector3 extends Vector3 { + + public MutableVector3() {} + + public MutableVector3(double x, double y, double z) { + super(x, y, z); + } + + public MutableVector3(float x, float y, float z) { + super(x, y, z); + } + + public MutableVector3(Vector3 other) { + super(other); + } + + @Override + public MutableVector3 setComponents(Vector3 other) { + this.x = other.x; + this.y = other.y; + this.z = other.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 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; + } + + public double getY() { + return y; + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/Vector2.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/Vector2.java new file mode 100644 index 000000000..1950ff9e2 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/Vector2.java @@ -0,0 +1,502 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.math; + +import com.boydti.fawe.util.MathMan; +import com.sk89q.worldedit.math.transform.AffineTransform; + +/** + * An immutable 2-dimensional vector. + */ +public class Vector2 { + + public static final Vector2 ZERO = new Vector2(0, 0); + public static final Vector2 UNIT_X = new Vector2(1, 0); + public static final Vector2 UNIT_Z = new Vector2(0, 1); + public static final Vector2 ONE = new Vector2(1, 1); + + public static Vector2 at(double x, double z) { + return new Vector2(x, z); + } + + protected double x, z; + + protected Vector2(){} + + /** + * Construct an instance. + * + * @param x the X coordinate + * @param z the Z coordinate + */ + protected Vector2(double x, double z) { + this.x = x; + this.z = z; + } + + protected Vector2(Vector2 other) { + this.x = other.x; + this.z = other.z; + } + + public int getBlockX() { + return MathMan.roundInt(getX()); + } + + public int getBlockZ() { + return MathMan.roundInt(getZ()); + } + + public MutableVector2 setComponents(int x, int z) { + return new MutableVector2(x, z); + } + + public MutableVector2 setComponents(double x, double z) { + return new MutableVector2(x, z); + } + + public MutableVector2 mutX(int x) { + return new MutableVector2(x, z); + } + + public MutableVector2 mutZ(int z) { + return new MutableVector2(x, z); + } + + public MutableVector2 mutX(double x) { + return new MutableVector2(x, z); + } + + public MutableVector2 mutZ(double z) { + return new MutableVector2(x, z); + } + + /** + * Get the X coordinate. + * + * @return the x coordinate + */ + public double getX() { + return x; + } + + /** + * Set the X coordinate. + * + * @param x the new X + * @return a new vector + */ + public Vector2 withX(double x) { + return Vector2.at(x, z); + } + + /** + * Get the Z coordinate. + * + * @return the z coordinate + */ + public double getZ() { + return z; + } + + /** + * Set the Z coordinate. + * + * @param z the new Z + * @return a new vector + */ + public Vector2 withZ(double z) { + return Vector2.at(x, z); + } + + /** + * Add another vector to this vector and return the result as a new vector. + * + * @param other the other vector + * @return a new vector + */ + public Vector2 add(Vector2 other) { + return add(other.x, other.z); + } + + /** + * Add another vector to this vector and return the result as a new vector. + * + * @param x the value to add + * @param z the value to add + * @return a new vector + */ + public Vector2 add(double x, double z) { + return Vector2.at(this.x + x, this.z + z); + } + + /** + * Add a list of vectors to this vector and return the + * result as a new vector. + * + * @param others an array of vectors + * @return a new vector + */ + public Vector2 add(Vector2... others) { + double newX = x, newZ = z; + + for (Vector2 other : others) { + newX += other.x; + newZ += other.z; + } + + return Vector2.at(newX, newZ); + } + + /** + * Subtract another vector from this vector and return the result + * as a new vector. + * + * @param other the other vector + * @return a new vector + */ + public Vector2 subtract(Vector2 other) { + return subtract(other.x, other.z); + } + + /** + * Subtract another vector from this vector and return the result + * as a new vector. + * + * @param x the value to subtract + * @param z the value to subtract + * @return a new vector + */ + public Vector2 subtract(double x, double z) { + return Vector2.at(this.x - x, this.z - z); + } + + /** + * Subtract a list of vectors from this vector and return the result + * as a new vector. + * + * @param others an array of vectors + * @return a new vector + */ + public Vector2 subtract(Vector2... others) { + double newX = x, newZ = z; + + for (Vector2 other : others) { + newX -= other.x; + newZ -= other.z; + } + + return Vector2.at(newX, newZ); + } + + /** + * Multiply this vector by another vector on each component. + * + * @param other the other vector + * @return a new vector + */ + public Vector2 multiply(Vector2 other) { + return multiply(other.x, other.z); + } + + /** + * Multiply this vector by another vector on each component. + * + * @param x the value to multiply + * @param z the value to multiply + * @return a new vector + */ + public Vector2 multiply(double x, double z) { + return Vector2.at(this.x * x, this.z * z); + } + + /** + * Multiply this vector by zero or more vectors on each component. + * + * @param others an array of vectors + * @return a new vector + */ + public Vector2 multiply(Vector2... others) { + double newX = x, newZ = z; + + for (Vector2 other : others) { + newX *= other.x; + newZ *= other.z; + } + + return Vector2.at(newX, newZ); + } + + /** + * Perform scalar multiplication and return a new vector. + * + * @param n the value to multiply + * @return a new vector + */ + public Vector2 multiply(double n) { + return multiply(n, n); + } + + /** + * Divide this vector by another vector on each component. + * + * @param other the other vector + * @return a new vector + */ + public Vector2 divide(Vector2 other) { + return divide(other.x, other.z); + } + + /** + * Divide this vector by another vector on each component. + * + * @param x the value to divide by + * @param z the value to divide by + * @return a new vector + */ + public Vector2 divide(double x, double z) { + return Vector2.at(this.x / x, this.z / z); + } + + /** + * Perform scalar division and return a new vector. + * + * @param n the value to divide by + * @return a new vector + */ + public Vector2 divide(double n) { + return divide(n, n); + } + + /** + * Get the length of the vector. + * + * @return length + */ + public double length() { + return Math.sqrt(lengthSq()); + } + + /** + * Get the length, squared, of the vector. + * + * @return length, squared + */ + public double lengthSq() { + return x * x + z * z; + } + + /** + * Get the distance between this vector and another vector. + * + * @param other the other vector + * @return distance + */ + public double distance(Vector2 other) { + return Math.sqrt(distanceSq(other)); + } + + /** + * Get the distance between this vector and another vector, squared. + * + * @param other the other vector + * @return distance + */ + public double distanceSq(Vector2 other) { + double dx = other.x - x; + double dz = other.z - z; + return dx * dx + dz * dz; + } + + /** + * Get the normalized vector, which is the vector divided by its + * length, as a new vector. + * + * @return a new vector + */ + public Vector2 normalize() { + return divide(length()); + } + + /** + * Gets the dot product of this and another vector. + * + * @param other the other vector + * @return the dot product of this and the other vector + */ + public double dot(Vector2 other) { + return x * other.x + z * other.z; + } + + /** + * Checks to see if a vector is contained with another. + * + * @param min the minimum point (X, Y, and Z are the lowest) + * @param max the maximum point (X, Y, and Z are the lowest) + * @return true if the vector is contained + */ + public boolean containedWithin(Vector2 min, Vector2 max) { + return x >= min.x && x <= max.x + && z >= min.z && z <= max.z; + } + + /** + * Floors the values of all components. + * + * @return a new vector + */ + public Vector2 floor() { + return Vector2.at(Math.floor(x), Math.floor(z)); + } + + /** + * Rounds all components up. + * + * @return a new vector + */ + public Vector2 ceil() { + return Vector2.at(Math.ceil(x), Math.ceil(z)); + } + + /** + * Rounds all components to the closest integer. + * + *

Components < 0.5 are rounded down, otherwise up.

+ * + * @return a new vector + */ + public Vector2 round() { + return Vector2.at(Math.floor(x + 0.5), Math.floor(z + 0.5)); + } + + /** + * Returns a vector with the absolute values of the components of + * this vector. + * + * @return a new vector + */ + public Vector2 abs() { + return Vector2.at(Math.abs(x), Math.abs(z)); + } + + /** + * Perform a 2D transformation on this vector and return a new one. + * + * @param angle in degrees + * @param aboutX about which x coordinate to rotate + * @param aboutZ about which z coordinate to rotate + * @param translateX what to add after rotation + * @param translateZ what to add after rotation + * @return a new vector + * @see AffineTransform another method to transform vectors + */ + public Vector2 transform2D(double angle, double aboutX, double aboutZ, double translateX, double translateZ) { + angle = Math.toRadians(angle); + double x = this.x - aboutX; + double z = this.z - aboutZ; + double cos = Math.cos(angle); + double sin = Math.sin(angle); + double x2 = x * cos - z * sin; + double z2 = x * sin + z * cos; + return new Vector2( + x2 + aboutX + translateX, + z2 + aboutZ + translateZ); + } + + /** + * Gets the minimum components of two vectors. + * + * @param v2 the second vector + * @return minimum + */ + public Vector2 getMinimum(Vector2 v2) { + return new Vector2( + Math.min(x, v2.x), + Math.min(z, v2.z) + ); + } + + /** + * Gets the maximum components of two vectors. + * + * @param v2 the second vector + * @return maximum + */ + public Vector2 getMaximum(Vector2 v2) { + return new Vector2( + Math.max(x, v2.x), + Math.max(z, v2.z) + ); + } + + public static BlockVector2 toBlockPoint(double x, double z) { + return BlockVector2.at(x, z); + } + + /** + * Create a new {@link BlockVector2} from this vector. + * + * @return a new {@link BlockVector2} + */ + public BlockVector2 toBlockPoint() { + return toBlockPoint(x, z); + } + + /** + * Creates a 3D vector by adding a zero Y component to this vector. + * + * @return a new vector + */ + public Vector3 toVector3() { + return toVector3(0); + } + + /** + * Creates a 3D vector by adding the specified Y component to this vector. + * + * @param y the Y component + * @return a new vector + */ + public Vector3 toVector3(double y) { + return Vector3.at(x, y, z); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Vector2)) { + return false; + } + + Vector2 other = (Vector2) obj; + return other.getX() == this.getX() && other.getZ() == this.getZ(); + + } + + @Override + public int hashCode() { + return ((int) getX() ^ ((int) getZ() << 16)); + } + + @Override + public String toString() { + return "(" + getX() + ", " + getZ() + ")"; + } + +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/Vector3.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/Vector3.java new file mode 100644 index 000000000..172a75687 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/Vector3.java @@ -0,0 +1,647 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.math; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.boydti.fawe.util.MathMan; +import com.google.common.collect.ComparisonChain; +import com.sk89q.worldedit.math.transform.AffineTransform; + +import javax.annotation.Nullable; +import java.util.Comparator; + +/** + * An immutable 3-dimensional vector. + */ +public class Vector3 { + + public static final Vector3 ZERO = new Vector3(0, 0, 0); + public static final Vector3 UNIT_X = new Vector3(1, 0, 0); + public static final Vector3 UNIT_Y = new Vector3(0, 1, 0); + public static final Vector3 UNIT_Z = new Vector3(0, 0, 1); + public static final Vector3 ONE = new Vector3(1, 1, 1); + + public static Vector3 at(double x, double y, double z) { + return new Vector3(x, y, z); + } + + // thread-safe initialization idiom + private static final class YzxOrderComparator { + private static final Comparator YZX_ORDER = (a, b) -> { + return ComparisonChain.start() + .compare(a.y, b.y) + .compare(a.z, b.z) + .compare(a.x, b.x) + .result(); + }; + } + + /** + * Returns a comparator that sorts vectors first by Y, then Z, then X. + * + *

+ * Useful for sorting by chunk block storage order. + */ + public static Comparator sortByCoordsYzx() { + return YzxOrderComparator.YZX_ORDER; + } + + protected double x, y, z; + + /** + * Construct an instance. + * + * @param x the X coordinate + * @param y the Y coordinate + * @param z the Z coordinate + */ + protected Vector3(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + protected Vector3() {} + + protected Vector3(Vector3 other) { + this.x = other.x; + this.y = other.y; + this.z = other.z; + } + + public int getBlockX() { + return MathMan.roundInt(getX()); + } + + public int getBlockY() { + return MathMan.roundInt(getY()); + } + + public int getBlockZ() { + return MathMan.roundInt(getZ()); + } + + public MutableVector3 setComponents(Vector3 other) { + return new MutableVector3(other); + } + + public MutableVector3 setComponents(int x, int y, int z) { + return new MutableVector3(x, y, z); + } + + public MutableVector3 setComponents(double x, double y, double z) { + return new MutableVector3(x, y, z); + } + + public MutableVector3 mutX(int x) { + return new MutableVector3(x, y, getZ()); + } + + public MutableVector3 mutX(double x) { + return new MutableVector3(x, y, getZ()); + } + + public MutableVector3 mutY(int y) { + return new MutableVector3(getX(), y, getZ()); + } + + public MutableVector3 mutY(double y) { + return new MutableVector3(getX(), y, getZ()); + } + + public MutableVector3 mutZ(int z) { + return new MutableVector3(getX(), y, z); + } + + public MutableVector3 mutZ(double z) { + return new MutableVector3(getX(), y, z); + } + + /** + * Get the X coordinate. + * + * @return the x coordinate + */ + public double getX() { + return x; + } + + /** + * Set the X coordinate. + * + * @param x the new X + * @return a new vector + */ + public Vector3 withX(double x) { + return Vector3.at(x, y, z); + } + + /** + * Get the Y coordinate. + * + * @return the y coordinate + */ + public double getY() { + return y; + } + + /** + * Set the Y coordinate. + * + * @param y the new Y + * @return a new vector + */ + public Vector3 withY(double y) { + return Vector3.at(x, y, z); + } + + /** + * Get the Z coordinate. + * + * @return the z coordinate + */ + public double getZ() { + return z; + } + + /** + * Set the Z coordinate. + * + * @param z the new Z + * @return a new vector + */ + public Vector3 withZ(double z) { + return Vector3.at(x, y, z); + } + + /** + * Add another vector to this vector and return the result as a new vector. + * + * @param other the other vector + * @return a new vector + */ + public Vector3 add(Vector3 other) { + return add(other.x, other.y, other.z); + } + + /** + * Add another vector to this vector and return the result as a new vector. + * + * @param x the value to add + * @param y the value to add + * @param z the value to add + * @return a new vector + */ + public Vector3 add(double x, double y, double z) { + return Vector3.at(this.x + x, this.y + y, this.z + z); + } + + /** + * Add a list of vectors to this vector and return the + * result as a new vector. + * + * @param others an array of vectors + * @return a new vector + */ + public Vector3 add(Vector3... others) { + double newX = x, newY = y, newZ = z; + + for (Vector3 other : others) { + newX += other.x; + newY += other.y; + newZ += other.z; + } + + return Vector3.at(newX, newY, newZ); + } + + /** + * Subtract another vector from this vector and return the result + * as a new vector. + * + * @param other the other vector + * @return a new vector + */ + public Vector3 subtract(Vector3 other) { + return subtract(other.x, other.y, other.z); + } + + /** + * Subtract another vector from this vector and return the result + * as a new vector. + * + * @param x the value to subtract + * @param y the value to subtract + * @param z the value to subtract + * @return a new vector + */ + public Vector3 subtract(double x, double y, double z) { + return Vector3.at(this.x - x, this.y - y, this.z - z); + } + + /** + * Subtract a list of vectors from this vector and return the result + * as a new vector. + * + * @param others an array of vectors + * @return a new vector + */ + public Vector3 subtract(Vector3... others) { + double newX = x, newY = y, newZ = z; + + for (Vector3 other : others) { + newX -= other.x; + newY -= other.y; + newZ -= other.z; + } + + return Vector3.at(newX, newY, newZ); + } + + /** + * Multiply this vector by another vector on each component. + * + * @param other the other vector + * @return a new vector + */ + public Vector3 multiply(Vector3 other) { + return multiply(other.x, other.y, other.z); + } + + /** + * Multiply this vector by another vector on each component. + * + * @param x the value to multiply + * @param y the value to multiply + * @param z the value to multiply + * @return a new vector + */ + public Vector3 multiply(double x, double y, double z) { + return Vector3.at(this.x * x, this.y * y, this.z * z); + } + + /** + * Multiply this vector by zero or more vectors on each component. + * + * @param others an array of vectors + * @return a new vector + */ + public Vector3 multiply(Vector3... others) { + double newX = x, newY = y, newZ = z; + + for (Vector3 other : others) { + newX *= other.x; + newY *= other.y; + newZ *= other.z; + } + + return Vector3.at(newX, newY, newZ); + } + + /** + * Perform scalar multiplication and return a new vector. + * + * @param n the value to multiply + * @return a new vector + */ + public Vector3 multiply(double n) { + return multiply(n, n, n); + } + + /** + * Divide this vector by another vector on each component. + * + * @param other the other vector + * @return a new vector + */ + public Vector3 divide(Vector3 other) { + return divide(other.x, other.y, other.z); + } + + /** + * Divide this vector by another vector on each component. + * + * @param x the value to divide by + * @param y the value to divide by + * @param z the value to divide by + * @return a new vector + */ + public Vector3 divide(double x, double y, double z) { + return Vector3.at(this.x / x, this.y / y, this.z / z); + } + + /** + * Perform scalar division and return a new vector. + * + * @param n the value to divide by + * @return a new vector + */ + public Vector3 divide(double n) { + return divide(n, n, n); + } + + /** + * Get the length of the vector. + * + * @return length + */ + public double length() { + return Math.sqrt(lengthSq()); + } + + /** + * Get the length, squared, of the vector. + * + * @return length, squared + */ + public double lengthSq() { + return x * x + y * y + z * z; + } + + /** + * Get the distance between this vector and another vector. + * + * @param other the other vector + * @return distance + */ + public double distance(Vector3 other) { + return Math.sqrt(distanceSq(other)); + } + + /** + * Get the distance between this vector and another vector, squared. + * + * @param other the other vector + * @return distance + */ + public double distanceSq(Vector3 other) { + double dx = other.x - x; + double dy = other.y - y; + double dz = other.z - z; + return dx * dx + dy * dy + dz * dz; + } + + /** + * Get the normalized vector, which is the vector divided by its + * length, as a new vector. + * + * @return a new vector + */ + public Vector3 normalize() { + return divide(length()); + } + + /** + * Gets the dot product of this and another vector. + * + * @param other the other vector + * @return the dot product of this and the other vector + */ + public double dot(Vector3 other) { + return x * other.x + y * other.y + z * other.z; + } + + /** + * Gets the cross product of this and another vector. + * + * @param other the other vector + * @return the cross product of this and the other vector + */ + public Vector3 cross(Vector3 other) { + return new Vector3( + y * other.z - z * other.y, + z * other.x - x * other.z, + x * other.y - y * other.x + ); + } + + /** + * Checks to see if a vector is contained with another. + * + * @param min the minimum point (X, Y, and Z are the lowest) + * @param max the maximum point (X, Y, and Z are the lowest) + * @return true if the vector is contained + */ + public boolean containedWithin(Vector3 min, Vector3 max) { + return x >= min.x && x <= max.x && y >= min.y && y <= max.y && z >= min.z && z <= max.z; + } + + /** + * Clamp the Y component. + * + * @param min the minimum value + * @param max the maximum value + * @return a new vector + */ + public Vector3 clampY(int min, int max) { + checkArgument(min <= max, "minimum cannot be greater than maximum"); + if (y < min) { + return Vector3.at(x, min, z); + } + if (y > max) { + return Vector3.at(x, max, z); + } + return this; + } + + /** + * Floors the values of all components. + * + * @return a new vector + */ + public Vector3 floor() { + return Vector3.at(Math.floor(x), Math.floor(y), Math.floor(z)); + } + + /** + * Rounds all components up. + * + * @return a new vector + */ + public Vector3 ceil() { + return Vector3.at(Math.ceil(x), Math.ceil(y), Math.ceil(z)); + } + + /** + * Rounds all components to the closest integer. + * + *

Components < 0.5 are rounded down, otherwise up.

+ * + * @return a new vector + */ + public Vector3 round() { + return Vector3.at(Math.floor(x + 0.5), Math.floor(y + 0.5), Math.floor(z + 0.5)); + } + + /** + * Returns a vector with the absolute values of the components of + * this vector. + * + * @return a new vector + */ + public Vector3 abs() { + return Vector3.at(Math.abs(x), Math.abs(y), Math.abs(z)); + } + + /** + * Perform a 2D transformation on this vector and return a new one. + * + * @param angle in degrees + * @param aboutX about which x coordinate to rotate + * @param aboutZ about which z coordinate to rotate + * @param translateX what to add after rotation + * @param translateZ what to add after rotation + * @return a new vector + * @see AffineTransform another method to transform vectors + */ + public Vector3 transform2D(double angle, double aboutX, double aboutZ, double translateX, double translateZ) { + angle = Math.toRadians(angle); + double x = this.x - aboutX; + double z = this.z - aboutZ; + double cos = Math.cos(angle); + double sin = Math.sin(angle); + double x2 = x * cos - z * sin; + double z2 = x * sin + z * cos; + + return new Vector3( + x2 + aboutX + translateX, + y, + z2 + aboutZ + translateZ + ); + } + + /** + * Get this vector's pitch as used within the game. + * + * @return pitch in radians + */ + public double toPitch() { + double x = getX(); + double z = getZ(); + + if (x == 0 && z == 0) { + return getY() > 0 ? -90 : 90; + } else { + double x2 = x * x; + double z2 = z * z; + double xz = Math.sqrt(x2 + z2); + return Math.toDegrees(Math.atan(-getY() / xz)); + } + } + + /** + * Get this vector's yaw as used within the game. + * + * @return yaw in radians + */ + public double toYaw() { + double x = getX(); + double z = getZ(); + + double t = Math.atan2(-x, z); + double tau = 2 * Math.PI; + + return Math.toDegrees(((t + tau) % tau)); + } + + /** + * Gets the minimum components of two vectors. + * + * @param v2 the second vector + * @return minimum + */ + public Vector3 getMinimum(Vector3 v2) { + return new Vector3( + Math.min(x, v2.x), + Math.min(y, v2.y), + Math.min(z, v2.z) + ); + } + + /** + * Gets the maximum components of two vectors. + * + * @param v2 the second vector + * @return maximum + */ + public Vector3 getMaximum(Vector3 v2) { + return new Vector3( + Math.max(x, v2.x), + Math.max(y, v2.y), + Math.max(z, v2.z) + ); + } + + /** + * Create a new {@code BlockVector} using the given components. + * + * @param x the X coordinate + * @param y the Y coordinate + * @param z the Z coordinate + * @return a new {@code BlockVector} + */ + public static BlockVector3 toBlockPoint(double x, double y, double z) { + return BlockVector3.at(x, y, z); + } + + /** + * Create a new {@code BlockVector} from this vector. + * + * @return a new {@code BlockVector} + */ + public BlockVector3 toBlockPoint() { + return toBlockPoint(x, y, z); + } + + /** + * Creates a 2D vector by dropping the Y component from this vector. + * + * @return a new {@link Vector2} + */ + public Vector2 toVector2() { + return Vector2.at(x, z); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (!(obj instanceof Vector3)) { + return false; + } + + Vector3 other = (Vector3) obj; + return other.getX() == this.getX() && other.getZ() == this.getZ() && other.getY() == this.getY(); + } + + @Override + public int hashCode() { + return ((int) getX() ^ ((int) getZ() << 16)) ^ ((int) getY() << 30); + } + + @Override + public String toString() { + String x = (getX() == getBlockX() ? "" + getBlockX() : "" + getX()); + String y = (getY() == getBlockY() ? "" + getBlockY() : "" + getY()); + String z = (getZ() == getBlockZ() ? "" + getBlockZ() : "" + getZ()); + return "(" + x + ", " + y + ", " + z + ")"; + } + +} \ No newline at end of file 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 bf9533de7..34f757b44 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 @@ -3,10 +3,10 @@ package com.sk89q.worldedit.math.convolution; import com.boydti.fawe.object.visitor.Fast2DIterator; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; -import com.sk89q.worldedit.blocks.BaseBlock; + +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Regions; @@ -69,16 +69,15 @@ public class HeightMap { invalid = new boolean[data.length]; if (layers) { - Vector min = region.getMinimumPoint(); - Vector max = region.getMaximumPoint(); + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); int bx = min.getBlockX(); int bz = min.getBlockZ(); - Iterable flat = Regions.asFlatRegion(region).asFlatRegion(); - Iterator iter = new Fast2DIterator(flat, session).iterator(); + Iterable flat = Regions.asFlatRegion(region).asFlatRegion(); + Iterator iter = new Fast2DIterator(flat, session).iterator(); int layer = 0; - MutableBlockVector mutable = new MutableBlockVector(); while (iter.hasNext()) { - Vector2D pos = iter.next(); + BlockVector2 pos = iter.next(); int x = pos.getBlockX(); int z = pos.getBlockZ(); layer = session.getNearestSurfaceLayer(x, z, (layer + 7) >> 3, 0, maxY); @@ -152,7 +151,7 @@ public class HeightMap { public int applyLayers(int[] data) { checkNotNull(data); - Vector minY = region.getMinimumPoint(); + BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); @@ -181,6 +180,7 @@ public class HeightMap { // Depending on growing or shrinking we need to start at the bottom or top if (newHeight > curHeight) { // Set the top block of the column to be the same type (this might go wrong with rounding) +//<<<<<<< HEAD BlockStateHolder existing = session.getBlock(xr, curBlock, zr); // Skip water/lava @@ -200,13 +200,34 @@ public class HeightMap { } else { existing = PropertyGroup.LEVEL.set(existing, 15); session.setBlock(xr, newBlock, zr, existing); + +//======= +// BlockState existing = session.getBlock(BlockVector3.at(xr, curHeight, zr)); +// +// // Skip water/lava +// if (existing.getBlockType() != BlockTypes.WATER && existing.getBlockType() != BlockTypes.LAVA) { +// session.setBlock(BlockVector3.at(xr, newHeight, zr), existing); +// ++blocksChanged; +// +// // Grow -- start from 1 below top replacing airblocks +// for (int y = newHeight - 1 - originY; y >= 0; --y) { +// int copyFrom = (int) (y * scale); +// session.setBlock(BlockVector3.at(xr, originY + y, zr), session.getBlock(BlockVector3.at(xr, originY + copyFrom, zr))); +//>>>>>>> 2c8b2fe0... Move vectors to static creators, for caching ++blocksChanged; } } } else if (curHeight > newHeight) { +//<<<<<<< HEAD // Fill rest with air for (int y = newBlock + 1; y <= ((curHeight + 15) >> 4); ++y) { session.setBlock(xr, y, zr, fillerAir); +//======= +// // Shrink -- start from bottom +// for (int y = 0; y < newHeight - originY; ++y) { +// int copyFrom = (int) (y * scale); +// session.setBlock(BlockVector3.at(xr, originY + y, zr), session.getBlock(BlockVector3.at(xr, originY + copyFrom, zr))); +//>>>>>>> 2c8b2fe0... Move vectors to static creators, for caching ++blocksChanged; } // Set the top block of the column to be the same type @@ -230,7 +251,7 @@ public class HeightMap { public int apply(int[] data) throws MaxChangedBlocksException { checkNotNull(data); - Vector minY = region.getMinimumPoint(); + BlockVector3 minY = region.getMinimumPoint(); int originX = minY.getBlockX(); int originY = minY.getBlockY(); int originZ = minY.getBlockZ(); @@ -274,12 +295,12 @@ public class HeightMap { } else if (curHeight > newHeight) { // Set the top block of the column to be the same type // (this could otherwise go wrong with rounding) - session.setBlock(xr, newHeight, zr, session.getBlock(xr, curHeight, zr)); + session.setBlock(BlockVector3.at(xr, newHeight, zr), session.getBlock(BlockVector3.at(xr, curHeight, zr))); ++blocksChanged; // Fill rest with air for (int y = newHeight + 1; y <= curHeight; ++y) { - session.setBlock(xr, y, zr, fillerAir); + session.setBlock(BlockVector3.at(xr, y, zr), fillerAir); ++blocksChanged; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/geom/Polygons.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/geom/Polygons.java index 007977d58..13bc259ba 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/geom/Polygons.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/geom/Polygons.java @@ -19,8 +19,8 @@ package com.sk89q.worldedit.math.geom; -import com.sk89q.worldedit.BlockVector2D; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.Vector2; import java.util.ArrayList; import java.util.List; @@ -40,9 +40,9 @@ public final class Polygons { * @param center the center point of the cylinder * @param radius the radius of the cylinder * @param maxPoints max points to be used for the calculation - * @return a list of {@link BlockVector2D} which resemble the shape as a polygon + * @return a list of {@link BlockVector2} which resemble the shape as a polygon */ - public static List polygonizeCylinder(Vector2D center, Vector2D radius, int maxPoints) { + public static List polygonizeCylinder(BlockVector2 center, Vector2 radius, int maxPoints) { int nPoints = (int) Math.ceil(Math.PI*radius.length()); // These strange semantics for maxPoints are copied from the selectSecondary method. @@ -50,11 +50,11 @@ public final class Polygons { nPoints = maxPoints - 1; } - final List points = new ArrayList<>(nPoints); + final List points = new ArrayList<>(nPoints); for (int i = 0; i < nPoints; ++i) { double angle = i * (2.0 * Math.PI) / nPoints; - final Vector2D pos = new Vector2D(Math.cos(angle), Math.sin(angle)); - final BlockVector2D blockVector2D = pos.multiply(radius).add(center).toBlockVector2D(); + final Vector2 pos = Vector2.at(Math.cos(angle), Math.sin(angle)); + final BlockVector2 blockVector2D = pos.multiply(radius).toBlockPoint().add(center); points.add(blockVector2D); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/Interpolation.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/Interpolation.java index 68df24b0d..28ce2c492 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/Interpolation.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/Interpolation.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.math.interpolation; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; import java.util.List; @@ -44,7 +44,7 @@ public interface Interpolation { * @param position the position to interpolate * @return the result */ - Vector getPosition(double position); + Vector3 getPosition(double position); /** * Gets the result of f'(position). @@ -52,7 +52,7 @@ public interface Interpolation { * @param position the position to interpolate * @return the result */ - Vector get1stDerivative(double position); + Vector3 get1stDerivative(double position); /** * Gets the result of ∫ab|f'(t)| dt.
diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/KochanekBartelsInterpolation.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/KochanekBartelsInterpolation.java index ac58612ca..b5447ed5e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/KochanekBartelsInterpolation.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/KochanekBartelsInterpolation.java @@ -21,7 +21,11 @@ package com.sk89q.worldedit.math.interpolation; -import com.sk89q.worldedit.Vector; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.math.MutableBlockVector3; +import com.sk89q.worldedit.math.Vector3; + import java.util.Collections; import java.util.List; @@ -37,10 +41,10 @@ import static com.google.common.base.Preconditions.checkNotNull; public class KochanekBartelsInterpolation implements Interpolation { private List nodes; - private Vector[] coeffA; - private Vector[] coeffB; - private Vector[] coeffC; - private Vector[] coeffD; + private Vector3[] coeffA; + private Vector3[] coeffB; + private Vector3[] coeffC; + private Vector3[] coeffD; private double scaling; public KochanekBartelsInterpolation() { @@ -57,10 +61,10 @@ public class KochanekBartelsInterpolation implements Interpolation { private void recalc() { final int nNodes = nodes.size(); - coeffA = new Vector[nNodes]; - coeffB = new Vector[nNodes]; - coeffC = new Vector[nNodes]; - coeffD = new Vector[nNodes]; + coeffA = new Vector3[nNodes]; + coeffB = new Vector3[nNodes]; + coeffC = new Vector3[nNodes]; + coeffD = new Vector3[nNodes]; if (nNodes == 0) return; @@ -107,12 +111,11 @@ public class KochanekBartelsInterpolation implements Interpolation { * @param f4 coefficient for baseIndex+2 * @return linear combination of nodes[n-1..n+2] with f1..4 */ - private Vector linearCombination(int baseIndex, double f1, double f2, double f3, double f4) { - final Vector r1 = retrieve(baseIndex - 1).multiply(f1); - final Vector r2 = retrieve(baseIndex).multiply(f2); - final Vector r3 = retrieve(baseIndex + 1).multiply(f3); - final Vector r4 = retrieve(baseIndex + 2).multiply(f4); - + private Vector3 linearCombination(int baseIndex, double f1, double f2, double f3, double f4) { + final Vector3 r1 = retrieve(baseIndex - 1).multiply(f1); + final Vector3 r2 = retrieve(baseIndex ).multiply(f2); + final Vector3 r3 = retrieve(baseIndex + 1).multiply(f3); + final Vector3 r4 = retrieve(baseIndex + 2).multiply(f4); return r1.add(r2).add(r3).add(r4); } @@ -122,7 +125,7 @@ public class KochanekBartelsInterpolation implements Interpolation { * @param index node index to retrieve * @return nodes[clamp(0, nodes.length-1)] */ - private Vector retrieve(int index) { + private Vector3 retrieve(int index) { if (index < 0) return fastRetrieve(0); @@ -132,14 +135,14 @@ public class KochanekBartelsInterpolation implements Interpolation { return fastRetrieve(index); } - private Vector fastRetrieve(int index) { + private Vector3 fastRetrieve(int index) { return nodes.get(index).getPosition(); } - private Vector mutable = new Vector(); + private MutableBlockVector3 mutable = new MutableBlockVector3(); @Override - public Vector getPosition(double position) { + public Vector3 getPosition(double position) { if (coeffA == null) throw new IllegalStateException("Must call setNodes first."); @@ -151,21 +154,21 @@ public class KochanekBartelsInterpolation implements Interpolation { final int index = (int) Math.floor(position); final double remainder = position - index; - final Vector a = coeffA[index]; - final Vector b = coeffB[index]; - final Vector c = coeffC[index]; - final Vector d = coeffD[index]; + final Vector3 a = coeffA[index]; + final Vector3 b = coeffB[index]; + final Vector3 c = coeffC[index]; + final Vector3 d = coeffD[index]; double r2 = remainder * remainder; double r3 = r2 * remainder; mutable.mutX((a.getX() * r3 + b.getX() * r2 + c.getX() * remainder + d.getX())); mutable.mutY((a.getY() * r3 + b.getY() * r2 + c.getY() * remainder + d.getY())); mutable.mutZ((a.getZ() * r3 + b.getZ() * r2 + c.getZ() * remainder + d.getZ())); - return mutable; + return mutable.toVector3(); } @Override - public Vector get1stDerivative(double position) { + public Vector3 get1stDerivative(double position) { if (coeffA == null) throw new IllegalStateException("Must call setNodes first."); @@ -177,9 +180,9 @@ public class KochanekBartelsInterpolation implements Interpolation { final int index = (int) Math.floor(position); //final double remainder = position - index; - final Vector a = coeffA[index]; - final Vector b = coeffB[index]; - final Vector c = coeffC[index]; + final Vector3 a = coeffA[index]; + final Vector3 b = coeffB[index]; + final Vector3 c = coeffC[index]; return a.multiply(1.5 * position - 3.0 * index).add(b).multiply(2.0 * position).add(a.multiply(1.5 * index).subtract(b).multiply(2.0 * index)).add(c).multiply(scaling); } @@ -226,9 +229,9 @@ public class KochanekBartelsInterpolation implements Interpolation { } private double arcLengthRecursive(int index, double remainderLeft, double remainderRight) { - final Vector a = coeffA[index].multiply(3.0); - final Vector b = coeffB[index].multiply(2.0); - final Vector c = coeffC[index]; + final Vector3 a = coeffA[index].multiply(3.0); + final Vector3 b = coeffB[index].multiply(2.0); + final Vector3 c = coeffC[index]; final int nPoints = 8; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/LinearInterpolation.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/LinearInterpolation.java index ea1962119..7b701f5fe 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/LinearInterpolation.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/LinearInterpolation.java @@ -23,7 +23,7 @@ package com.sk89q.worldedit.math.interpolation; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; import java.util.List; @@ -42,7 +42,7 @@ public class LinearInterpolation implements Interpolation { } @Override - public Vector getPosition(double position) { + public Vector3 getPosition(double position) { if (nodes == null) throw new IllegalStateException("Must call setNodes first."); @@ -54,8 +54,8 @@ public class LinearInterpolation implements Interpolation { final int index1 = (int) Math.floor(position); final double remainder = position - index1; - final Vector position1 = nodes.get(index1).getPosition(); - final Vector position2 = nodes.get(index1 + 1).getPosition(); + final Vector3 position1 = nodes.get(index1).getPosition(); + final Vector3 position2 = nodes.get(index1 + 1).getPosition(); return position1.multiply(1.0 - remainder).add(position2.multiply(remainder)); } @@ -76,7 +76,7 @@ public class LinearInterpolation implements Interpolation { */ @Override - public Vector get1stDerivative(double position) { + public Vector3 get1stDerivative(double position) { if (nodes == null) throw new IllegalStateException("Must call setNodes first."); @@ -87,8 +87,8 @@ public class LinearInterpolation implements Interpolation { final int index1 = (int) Math.floor(position); - final Vector position1 = nodes.get(index1).getPosition(); - final Vector position2 = nodes.get(index1 + 1).getPosition(); + final Vector3 position1 = nodes.get(index1).getPosition(); + final Vector3 position2 = nodes.get(index1 + 1).getPosition(); return position2.subtract(position1); } @@ -135,8 +135,8 @@ public class LinearInterpolation implements Interpolation { } private double arcLengthRecursive(int index, double remainderA, double remainderB) { - final Vector position1 = nodes.get(index).getPosition(); - final Vector position2 = nodes.get(index + 1).getPosition(); + final Vector3 position1 = nodes.get(index).getPosition(); + final Vector3 position2 = nodes.get(index + 1).getPosition(); return position1.distance(position2) * (remainderB - remainderA); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/Node.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/Node.java index ce604824c..c29190b77 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/Node.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/Node.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.math.interpolation; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; /** * Represents a node for interpolation. @@ -31,14 +31,14 @@ import com.sk89q.worldedit.Vector; */ public class Node { - private Vector position; + private Vector3 position; private double tension; private double bias; private double continuity; public Node() { - this(new Vector(0, 0, 0)); + this(Vector3.at(0, 0, 0)); } public Node(Node other) { @@ -49,16 +49,16 @@ public class Node { this.continuity = other.continuity; } - public Node(Vector position) { + public Node(Vector3 position) { this.position = position; } - public Vector getPosition() { + public Vector3 getPosition() { return position; } - public void setPosition(Vector position) { + public void setPosition(Vector3 position) { this.position = position; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/ReparametrisingInterpolation.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/ReparametrisingInterpolation.java index d6920b829..29a3ee5ee 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/ReparametrisingInterpolation.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/interpolation/ReparametrisingInterpolation.java @@ -23,7 +23,7 @@ package com.sk89q.worldedit.math.interpolation; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; import java.util.List; import java.util.Map.Entry; @@ -65,7 +65,7 @@ public class ReparametrisingInterpolation implements Interpolation { } @Override - public Vector getPosition(double position) { + public Vector3 getPosition(double position) { if (position > 1) return null; @@ -73,7 +73,7 @@ public class ReparametrisingInterpolation implements Interpolation { } @Override - public Vector get1stDerivative(double position) { + public Vector3 get1stDerivative(double position) { if (position > 1) return null; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/JLibNoiseGenerator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/JLibNoiseGenerator.java index dbf7720fd..1da9d5b2d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/JLibNoiseGenerator.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/JLibNoiseGenerator.java @@ -19,8 +19,9 @@ package com.sk89q.worldedit.math.noise; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.Vector2; +import com.sk89q.worldedit.math.Vector3; + import net.royawesome.jlibnoise.module.Module; import java.util.Random; @@ -46,12 +47,12 @@ abstract class JLibNoiseGenerator implements NoiseGenerator { public abstract int getSeed(); @Override - public float noise(Vector2D position) { + public float noise(Vector2 position) { return forceRange(module.GetValue(position.getX(), 0, position.getZ())); } @Override - public float noise(Vector position) { + public float noise(Vector3 position) { return forceRange(module.GetValue(position.getX(), position.getY(), position.getZ())); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/NoiseGenerator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/NoiseGenerator.java index bb57d23f0..185e41fbb 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/NoiseGenerator.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/NoiseGenerator.java @@ -19,8 +19,8 @@ package com.sk89q.worldedit.math.noise; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.Vector2; +import com.sk89q.worldedit.math.Vector3; /** * Generates noise in a deterministic or non-deterministic manner. @@ -34,7 +34,7 @@ public interface NoiseGenerator { * @param position the position * @return a noise value between 0 (inclusive) and 1 (inclusive) */ - float noise(Vector2D position); + float noise(Vector2 position); /** * Get the noise value for the given position. The returned value may @@ -43,6 +43,6 @@ public interface NoiseGenerator { * @param position the position * @return a noise value between 0 (inclusive) and 1 (inclusive) */ - float noise(Vector position); + float noise(Vector3 position); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/RandomNoise.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/RandomNoise.java index 6daed2841..ff3421404 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/RandomNoise.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/noise/RandomNoise.java @@ -19,8 +19,8 @@ package com.sk89q.worldedit.math.noise; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.Vector2; +import com.sk89q.worldedit.math.Vector3; import java.util.Random; @@ -50,12 +50,12 @@ public class RandomNoise implements NoiseGenerator { } @Override - public float noise(Vector2D position) { + public float noise(Vector2 position) { return random.nextFloat(); } @Override - public float noise(Vector position) { + public float noise(Vector3 position) { return random.nextFloat(); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/AffineTransform.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/AffineTransform.java index 2bb5a63f5..5223ca718 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/AffineTransform.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/AffineTransform.java @@ -1,11 +1,13 @@ package com.sk89q.worldedit.math.transform; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.math.MathUtils; import java.io.IOException; import java.io.Serializable; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MathUtils; +import com.sk89q.worldedit.math.MutableBlockVector3; +import com.sk89q.worldedit.math.Vector3; + /** * An affine transform. *

@@ -15,7 +17,7 @@ import java.io.Serializable; */ public class AffineTransform implements Transform, Serializable { - private transient MutableBlockVector mutable = new MutableBlockVector(); + private transient MutableBlockVector3 mutable = new MutableBlockVector3(); /** * coefficients for x coordinate. @@ -234,7 +236,11 @@ public class AffineTransform implements Transform, Serializable { n20, n21, n22, n23); } - public AffineTransform translate(Vector vec) { + public AffineTransform translate(Vector3 vec) { + return translate(vec.getX(), vec.getY(), vec.getZ()); + } + + public AffineTransform translate(BlockVector3 vec) { return translate(vec.getX(), vec.getY(), vec.getZ()); } @@ -280,16 +286,13 @@ public class AffineTransform implements Transform, Serializable { return concatenate(new AffineTransform(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0)); } - public AffineTransform scale(Vector vec) { + public AffineTransform scale(Vector3 vec) { return scale(vec.getX(), vec.getY(), vec.getZ()); } @Override - public Vector apply(Vector vector) { - // vector.getX() * m00 + vector.getY() * m01 + vector.getZ() * m02 + m03 - // vector.getX() * m10 + vector.getY() * m11 + vector.getZ() * m12 + m13 - // vector.getX() * m20 + vector.getY() * m21 + vector.getZ() * m22 + m23 - return new Vector( + public Vector3 apply(Vector3 vector) { + return Vector3.at( vector.getX() * m00 + vector.getY() * m01 + vector.getZ() * m02 + m03, vector.getX() * m10 + vector.getY() * m11 + vector.getZ() * m12 + m13, vector.getX() * m20 + vector.getY() * m21 + vector.getZ() * m22 + m23); @@ -321,7 +324,7 @@ public class AffineTransform implements Transform, Serializable { private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - mutable = new MutableBlockVector(); + mutable = new MutableBlockVector3(); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/CombinedTransform.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/CombinedTransform.java index 646e2a209..e5f2a2586 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/CombinedTransform.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/CombinedTransform.java @@ -21,7 +21,7 @@ package com.sk89q.worldedit.math.transform; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; import java.util.ArrayList; import java.util.Arrays; @@ -66,7 +66,7 @@ public class CombinedTransform implements Transform { } @Override - public Vector apply(Vector vector) { + public Vector3 apply(Vector3 vector) { for (Transform transform : transforms) { vector = transform.apply(vector); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Identity.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Identity.java index b0f4dddef..f9f1ed125 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Identity.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Identity.java @@ -19,7 +19,7 @@ package com.sk89q.worldedit.math.transform; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; /** * Makes no transformation to given vectors. @@ -32,7 +32,7 @@ public class Identity implements Transform { } @Override - public Vector apply(Vector vector) { + public Vector3 apply(Vector3 vector) { return vector; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/RoundedTransform.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/RoundedTransform.java index 08ebbbb41..7ba7abb25 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/RoundedTransform.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/RoundedTransform.java @@ -1,11 +1,11 @@ package com.sk89q.worldedit.math.transform; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; public class RoundedTransform implements Transform{ private final Transform transform; - private MutableBlockVector mutable = new MutableBlockVector(); +// private MutableBlockVector3 mutable = new MutableBlockVector3(); public RoundedTransform(Transform transform) { this.transform = transform; @@ -17,12 +17,12 @@ public class RoundedTransform implements Transform{ } @Override - public Vector apply(Vector input) { - Vector val = transform.apply(input); - mutable.mutX((int) Math.floor(val.getX() + 0.5)); - mutable.mutY((int) Math.floor(val.getY() + 0.5)); - mutable.mutZ((int) Math.floor(val.getZ() + 0.5)); - return mutable; + public Vector3 apply(Vector3 input) { + Vector3 val = transform.apply(input); +// mutable.mutX((int) Math.floor(val.getX() + 0.5)); +// mutable.mutY((int) Math.floor(val.getY() + 0.5)); +// mutable.mutZ((int) Math.floor(val.getZ() + 0.5)); + return Vector3.at(Math.floor(val.getX() + 0.5), Math.floor(val.getY() + 0.5), Math.floor(val.getY() + 0.5)); } @Override diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Transform.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Transform.java index b8df8bcbd..e12030022 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Transform.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Transform.java @@ -19,10 +19,10 @@ package com.sk89q.worldedit.math.transform; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; /** - * Makes a transformation of {@link Vector}s. + * Makes a transformation of {@link Vector3}s. */ public interface Transform { @@ -41,7 +41,7 @@ public interface Transform { * @param input the input * @return the result */ - Vector apply(Vector input); + Vector3 apply(Vector3 input); /** * Create a new inverse transform. diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Transforms.java b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Transforms.java index 5d0412259..828f8b7ea 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Transforms.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/math/transform/Transforms.java @@ -43,7 +43,7 @@ public final class Transforms { public static Location transform(Location location, Transform transform) { checkNotNull(location); checkNotNull(transform); - return new Location(location.getExtent(), transform.apply(location.toVector()), location.getDirection()); + return new Location(location.getExtent(), transform.apply(location), location.getDirection()); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/patterns/Pattern.java b/worldedit-core/src/main/java/com/sk89q/worldedit/patterns/Pattern.java deleted file mode 100644 index 812c85029..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/patterns/Pattern.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.sk89q.worldedit.patterns; - -import com.sk89q.worldedit.*; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.world.block.BlockState; - -/** - * @deprecated See {@link com.sk89q.worldedit.function.pattern.Pattern} - */ -@Deprecated -public interface Pattern { - - /** - * Get a block for a position. This return value of this method does - * not have to be consistent for the same position. - * - * @param position the position where a block is needed - * @return a block - */ - public BaseBlock next(Vector position); - - /** - * Get a block for a position. This return value of this method does - * not have to be consistent for the same position. - * - * @param x the X coordinate - * @param y the Y coordinate - * @param z the Z coordinate - * @return a block - */ - public BaseBlock next(int x, int y, int z); - -} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/AbstractRegion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/AbstractRegion.java index 9bc7159f6..521f23c62 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/AbstractRegion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/AbstractRegion.java @@ -20,7 +20,9 @@ package com.sk89q.worldedit.regions; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.iterator.RegionIterator; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.storage.ChunkStore; @@ -36,8 +38,8 @@ public abstract class AbstractRegion implements Region { } @Override - public Vector getCenter() { - return getMinimumPoint().add(getMaximumPoint()).divide(2); + public Vector3 getCenter() { + return getMinimumPoint().add(getMaximumPoint()).toVector3().divide(2); } /** @@ -46,7 +48,7 @@ public abstract class AbstractRegion implements Region { * @return iterator of points inside the region */ @Override - public Iterator iterator() { + public Iterator iterator() { return new RegionIterator(this); } @@ -61,7 +63,7 @@ public abstract class AbstractRegion implements Region { } @Override - public void shift(Vector change) throws RegionOperationException { + public void shift(BlockVector3 change) throws RegionOperationException { expand(change); contract(change); } @@ -76,20 +78,20 @@ public abstract class AbstractRegion implements Region { } @Override - public List polygonize(int maxPoints) { + public List polygonize(int maxPoints) { if (maxPoints >= 0 && maxPoints < 4) { throw new IllegalArgumentException("Cannot polygonize an AbstractRegion with no overridden polygonize method into less than 4 points."); } - final BlockVector min = getMinimumPoint().toBlockVector(); - final BlockVector max = getMaximumPoint().toBlockVector(); + final BlockVector3 min = getMinimumPoint(); + final BlockVector3 max = getMaximumPoint(); - final List points = new ArrayList<>(4); + final List points = new ArrayList<>(4); - points.add(new BlockVector2D(min.getX(), min.getZ())); - points.add(new BlockVector2D(min.getX(), max.getZ())); - points.add(new BlockVector2D(max.getX(), max.getZ())); - points.add(new BlockVector2D(max.getX(), min.getZ())); + points.add(BlockVector2.at(min.getX(), min.getZ())); + points.add(BlockVector2.at(min.getX(), max.getZ())); + points.add(BlockVector2.at(max.getX(), max.getZ())); + points.add(BlockVector2.at(max.getX(), min.getZ())); return points; } @@ -101,12 +103,12 @@ public abstract class AbstractRegion implements Region { */ @Override public int getArea() { - Vector min = getMinimumPoint(); - Vector max = getMaximumPoint(); + BlockVector3 min = getMinimumPoint(); + BlockVector3 max = getMaximumPoint(); - return (int)((max.getX() - min.getX() + 1) * - (max.getY() - min.getY() + 1) * - (max.getZ() - min.getZ() + 1)); + return (max.getX() - min.getX() + 1) * + (max.getY() - min.getY() + 1) * + (max.getZ() - min.getZ() + 1); } /** @@ -116,10 +118,10 @@ public abstract class AbstractRegion implements Region { */ @Override public int getWidth() { - Vector min = getMinimumPoint(); - Vector max = getMaximumPoint(); + BlockVector3 min = getMinimumPoint(); + BlockVector3 max = getMaximumPoint(); - return (int) (max.getX() - min.getX() + 1); + return max.getX() - min.getX() + 1; } /** @@ -129,10 +131,10 @@ public abstract class AbstractRegion implements Region { */ @Override public int getHeight() { - Vector min = getMinimumPoint(); - Vector max = getMaximumPoint(); + BlockVector3 min = getMinimumPoint(); + BlockVector3 max = getMaximumPoint(); - return (int) (max.getY() - min.getY() + 1); + return max.getY() - min.getY() + 1; } /** @@ -142,10 +144,10 @@ public abstract class AbstractRegion implements Region { */ @Override public int getLength() { - Vector min = getMinimumPoint(); - Vector max = getMaximumPoint(); + BlockVector3 min = getMinimumPoint(); + BlockVector3 max = getMaximumPoint(); - return (int) (max.getZ() - min.getZ() + 1); + return max.getZ() - min.getZ() + 1; } /** @@ -154,21 +156,21 @@ public abstract class AbstractRegion implements Region { * @return a set of chunks */ @Override - public Set getChunks() { - final Set chunks = new HashSet<>(); + public Set getChunks() { + final Set chunks = new HashSet<>(); - final Vector min = getMinimumPoint(); - final Vector max = getMaximumPoint(); + final BlockVector3 min = getMinimumPoint(); + final BlockVector3 max = getMaximumPoint(); final int minY = min.getBlockY(); for (int x = min.getBlockX(); x <= max.getBlockX(); ++x) { for (int z = min.getBlockZ(); z <= max.getBlockZ(); ++z) { - if (!contains(new Vector(x, minY, z))) { + if (!contains(BlockVector3.at(x, minY, z))) { continue; } - chunks.add(new BlockVector2D( + chunks.add(BlockVector2.at( x >> ChunkStore.CHUNK_SHIFTS, z >> ChunkStore.CHUNK_SHIFTS )); @@ -179,20 +181,20 @@ public abstract class AbstractRegion implements Region { } @Override - public Set getChunkCubes() { - final Set chunks = new HashSet<>(); + public Set getChunkCubes() { + final Set chunks = new HashSet<>(); - final Vector min = getMinimumPoint(); - final Vector max = getMaximumPoint(); + final BlockVector3 min = getMinimumPoint(); + final BlockVector3 max = getMaximumPoint(); for (int x = min.getBlockX(); x <= max.getBlockX(); ++x) { for (int y = min.getBlockY(); y <= max.getBlockY(); ++y) { for (int z = min.getBlockZ(); z <= max.getBlockZ(); ++z) { - if (!contains(new Vector(x, y, z))) { + if (!contains(BlockVector3.at(x, y, z))) { continue; } - chunks.add(new BlockVector( + chunks.add(BlockVector3.at( x >> ChunkStore.CHUNK_SHIFTS, y >> ChunkStore.CHUNK_SHIFTS, z >> ChunkStore.CHUNK_SHIFTS diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/ConvexPolyhedralRegion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/ConvexPolyhedralRegion.java index fce016e23..ce1fc5b22 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/ConvexPolyhedralRegion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/ConvexPolyhedralRegion.java @@ -21,7 +21,8 @@ package com.sk89q.worldedit.regions; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.polyhedron.Edge; import com.sk89q.worldedit.regions.polyhedron.Triangle; import com.sk89q.worldedit.world.World; @@ -40,7 +41,7 @@ public class ConvexPolyhedralRegion extends AbstractRegion { /** * Vertices that are contained in the convex hull. */ - private final Set vertices = new LinkedHashSet<>(); + private final Set vertices = new LinkedHashSet<>(); /** * Triangles that form the convex hull. @@ -50,25 +51,25 @@ public class ConvexPolyhedralRegion extends AbstractRegion { /** * Vertices that are coplanar to the first 3 vertices. */ - private final Set vertexBacklog = new LinkedHashSet<>(); + private final Set vertexBacklog = new LinkedHashSet<>(); /** * Minimum point of the axis-aligned bounding box. */ - private Vector minimumPoint; + private BlockVector3 minimumPoint; /** * Maximum point of the axis-aligned bounding box. */ - private Vector maximumPoint; + private BlockVector3 maximumPoint; /** * Accumulator for the barycenter of the polyhedron. Divide by vertices.size() to get the actual center. */ - private Vector centerAccum = Vector.ZERO; + private BlockVector3 centerAccum = BlockVector3.ZERO; /** - * The last triangle that caused a {@link #contains(Vector)} to classify a point as "outside". Used for optimization. + * The last triangle that caused a {@link #contains(Vector3)} to classify a point as "outside". Used for optimization. */ private Triangle lastTriangle; @@ -108,7 +109,7 @@ public class ConvexPolyhedralRegion extends AbstractRegion { minimumPoint = null; maximumPoint = null; - centerAccum = Vector.ZERO; + centerAccum = BlockVector3.ZERO; lastTriangle = null; } @@ -118,7 +119,7 @@ public class ConvexPolyhedralRegion extends AbstractRegion { * @param vertex the vertex * @return true, if something changed. */ - public boolean addVertex(Vector vertex) { + public boolean addVertex(BlockVector3 vertex) { checkNotNull(vertex); lastTriangle = null; // Probably not necessary @@ -132,7 +133,7 @@ public class ConvexPolyhedralRegion extends AbstractRegion { return false; } - if (containsRaw(vertex)) { + if (containsRaw(vertex.toVector3())) { return vertexBacklog.add(vertex); } } @@ -144,8 +145,8 @@ public class ConvexPolyhedralRegion extends AbstractRegion { if (minimumPoint == null) { minimumPoint = maximumPoint = vertex; } else { - minimumPoint = Vector.getMinimum(minimumPoint, vertex); - maximumPoint = Vector.getMaximum(maximumPoint, vertex); + minimumPoint = minimumPoint.getMinimum(vertex); + maximumPoint = maximumPoint.getMaximum(vertex); } @@ -158,10 +159,10 @@ public class ConvexPolyhedralRegion extends AbstractRegion { case 3: // Generate minimal mesh to start from - final Vector[] v = vertices.toArray(new Vector[vertices.size()]); + final BlockVector3[] v = vertices.toArray(new BlockVector3[vertices.size()]); - triangles.add((new Triangle(v[0], v[1], v[2]))); - triangles.add((new Triangle(v[0], v[2], v[1]))); + triangles.add((new Triangle(v[0].toVector3(), v[1].toVector3(), v[2].toVector3()))); + triangles.add((new Triangle(v[0].toVector3(), v[2].toVector3(), v[1].toVector3()))); return true; } @@ -171,7 +172,7 @@ public class ConvexPolyhedralRegion extends AbstractRegion { final Triangle triangle = it.next(); // If the triangle can't be seen, it's not relevant - if (!triangle.above(vertex)) { + if (!triangle.above(vertex.toVector3())) { continue; } @@ -191,7 +192,7 @@ public class ConvexPolyhedralRegion extends AbstractRegion { // Add triangles between the remembered edges and the new vertex. for (Edge edge : borderEdges) { - triangles.add(edge.createTriangle(vertex)); + triangles.add(edge.createTriangle(vertex.toVector3())); } if (!vertexBacklog.isEmpty()) { @@ -199,9 +200,9 @@ public class ConvexPolyhedralRegion extends AbstractRegion { vertices.remove(vertex); // Clone, clear and work through the backlog - final List vertexBacklog2 = new ArrayList<>(vertexBacklog); + final List vertexBacklog2 = new ArrayList<>(vertexBacklog); vertexBacklog.clear(); - for (Vector vertex2 : vertexBacklog2) { + for (BlockVector3 vertex2 : vertexBacklog2) { addVertex(vertex2); } @@ -217,39 +218,40 @@ public class ConvexPolyhedralRegion extends AbstractRegion { } @Override - public Vector getMinimumPoint() { + public BlockVector3 getMinimumPoint() { return minimumPoint; } @Override - public Vector getMaximumPoint() { + public BlockVector3 getMaximumPoint() { return maximumPoint; } @Override - public Vector getCenter() { - return centerAccum.divide(vertices.size()); + public Vector3 getCenter() { + return centerAccum.toVector3().divide(vertices.size()); } @Override - public void expand(Vector... changes) throws RegionOperationException { + public void expand(BlockVector3... changes) throws RegionOperationException { } @Override - public void contract(Vector... changes) throws RegionOperationException { + public void contract(BlockVector3... changes) throws RegionOperationException { } @Override - public void shift(Vector change) throws RegionOperationException { + public void shift(BlockVector3 change) throws RegionOperationException { + Vector3 vec = change.toVector3(); shiftCollection(vertices, change); shiftCollection(vertexBacklog, change); for (int i = 0; i < triangles.size(); ++i) { final Triangle triangle = triangles.get(i); - final Vector v0 = change.add(triangle.getVertex(0)); - final Vector v1 = change.add(triangle.getVertex(1)); - final Vector v2 = change.add(triangle.getVertex(2)); + final Vector3 v0 = vec.add(triangle.getVertex(0)); + final Vector3 v1 = vec.add(triangle.getVertex(1)); + final Vector3 v2 = vec.add(triangle.getVertex(2)); triangles.set(i, new Triangle(v0, v1, v2)); } @@ -260,16 +262,16 @@ public class ConvexPolyhedralRegion extends AbstractRegion { lastTriangle = null; } - private static void shiftCollection(Collection collection, Vector change) { - final List tmp = new ArrayList<>(collection); + private static void shiftCollection(Collection collection, BlockVector3 change) { + final List tmp = new ArrayList<>(collection); collection.clear(); - for (Vector vertex : tmp) { + for (BlockVector3 vertex : tmp) { collection.add(change.add(vertex)); } } @Override - public boolean contains(Vector position) { + public boolean contains(BlockVector3 position) { if (!isDefined()) { return false; } @@ -278,8 +280,8 @@ public class ConvexPolyhedralRegion extends AbstractRegion { final int y = position.getBlockY(); final int z = position.getBlockZ(); - final Vector min = getMinimumPoint(); - final Vector max = getMaximumPoint(); + final BlockVector3 min = getMinimumPoint(); + final BlockVector3 max = getMaximumPoint(); if (x < min.getBlockX()) return false; if (x > max.getBlockX()) return false; @@ -288,10 +290,10 @@ public class ConvexPolyhedralRegion extends AbstractRegion { if (z < min.getBlockZ()) return false; if (z > max.getBlockZ()) return false; - return containsRaw(position); + return containsRaw(position.toVector3()); } - private boolean containsRaw(Vector pt) { + private boolean containsRaw(Vector3 pt) { if (lastTriangle != null && lastTriangle.above(pt)) { return false; } @@ -310,12 +312,12 @@ public class ConvexPolyhedralRegion extends AbstractRegion { return true; } - public Collection getVertices() { + public Collection getVertices() { if (vertexBacklog.isEmpty()) { return vertices; } - final List ret = new ArrayList<>(vertices); + final List ret = new ArrayList<>(vertices); ret.addAll(vertexBacklog); return ret; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/CuboidRegion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/CuboidRegion.java index 69b7de440..5ead3a841 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/CuboidRegion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/CuboidRegion.java @@ -20,14 +20,19 @@ package com.sk89q.worldedit.regions; import com.boydti.fawe.config.Settings; -import com.boydti.fawe.object.collection.LocalBlockVectorSet; -import com.sk89q.worldedit.*; -import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.util.Location; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector3; +import com.sk89q.worldedit.math.MutableBlockVector2; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.storage.ChunkStore; import java.util.AbstractSet; +import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; @@ -40,10 +45,11 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class CuboidRegion extends AbstractRegion implements FlatRegion { - private Vector pos1; - private Vector pos2; + private boolean useOldIterator; private int minX, minY, minZ, maxX, maxY, maxZ; + private BlockVector3 pos1; + private BlockVector3 pos2; /** * Construct a new instance of this cuboid using two corners of the cuboid. @@ -51,7 +57,7 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { * @param pos1 the first position * @param pos2 the second position */ - public CuboidRegion(Vector pos1, Vector pos2) { + public CuboidRegion(BlockVector3 pos1, BlockVector3 pos2) { this(null, pos1, pos2); } @@ -62,19 +68,12 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { * @param pos1 the first position * @param pos2 the second position */ - public CuboidRegion(World world, Vector pos1, Vector pos2) { + public CuboidRegion(World world, BlockVector3 pos1, BlockVector3 pos2) { super(world); checkNotNull(pos1); checkNotNull(pos2); this.pos1 = pos1; this.pos2 = pos2; - if (pos1 instanceof Location) { - Extent extent = ((Location) pos1).getExtent(); - if (extent instanceof World) setWorld((World) extent); - } else if (pos2 instanceof Location) { - Extent extent = ((Location) pos2).getExtent(); - if (extent instanceof World) setWorld((World) extent); - } recalculate(); } @@ -87,7 +86,7 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { * * @return a position */ - public Vector getPos1() { + public BlockVector3 getPos1() { return pos1; } @@ -96,7 +95,7 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { * * @param pos1 a position */ - public void setPos1(Vector pos1) { + public void setPos1(BlockVector3 pos1) { this.pos1 = pos1; recalculate(); } @@ -106,7 +105,7 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { * * @return a position */ - public Vector getPos2() { + public BlockVector3 getPos2() { return pos2; } @@ -115,7 +114,7 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { * * @param pos2 a position */ - public void setPos2(Vector pos2) { + public void setPos2(BlockVector3 pos2) { this.pos2 = pos2; recalculate(); } @@ -129,8 +128,8 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } pos1 = pos1.clampY(world == null ? Integer.MIN_VALUE : 0, world == null ? Integer.MAX_VALUE : world.getMaxY()); pos2 = pos2.clampY(world == null ? Integer.MIN_VALUE : 0, world == null ? Integer.MAX_VALUE : world.getMaxY()); - Vector min = getMinimumPoint(); - Vector max = getMaximumPoint(); + BlockVector3 min = getMinimumPoint(); + BlockVector3 max = getMaximumPoint(); minX = min.getBlockX(); minY = min.getBlockY(); minZ = min.getBlockZ(); @@ -145,21 +144,21 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { * @return a new complex region */ public Region getFaces() { - Vector min = getMinimumPoint(); - Vector max = getMaximumPoint(); + BlockVector3 min = getMinimumPoint(); + BlockVector3 max = getMaximumPoint(); return new RegionIntersection( // Project to Z-Y plane - new CuboidRegion(new Vector(min.getX(), pos1.getY(), pos1.getZ()), new Vector(min.getX(), pos2.getY(), pos2.getZ())), - new CuboidRegion(new Vector(max.getX(), pos1.getY(), pos1.getZ()), new Vector(max.getX(), pos2.getY(), pos2.getZ())), + new CuboidRegion(pos1.withX(min.getX()), pos2.withX(min.getX())), + new CuboidRegion(pos1.withX(max.getX()), pos2.withX(max.getX())), // Project to X-Y plane - new CuboidRegion(new Vector(pos1.getX(), pos1.getY(), min.getZ()), new Vector(pos2.getX(), pos2.getY(), min.getZ())), - new CuboidRegion(new Vector(pos1.getX(), pos1.getY(), max.getZ()), new Vector(pos2.getX(), pos2.getY(), max.getZ())), + new CuboidRegion(pos1.withZ(min.getZ()), pos2.withZ(min.getZ())), + new CuboidRegion(pos1.withZ(max.getZ()), pos2.withZ(max.getZ())), // Project to the X-Z plane - new CuboidRegion(new Vector(pos1.getX(), min.getY(), pos1.getZ()), new Vector(pos2.getX(), min.getY(), pos2.getZ())), - new CuboidRegion(new Vector(pos1.getX(), max.getY(), pos1.getZ()), new Vector(pos2.getX(), max.getY(), pos2.getZ()))); + new CuboidRegion(pos1.withY(min.getY()), pos2.withY(min.getY())), + new CuboidRegion(pos1.withY(max.getY()), pos2.withY(max.getY()))); } /** @@ -169,31 +168,27 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { * @return a new complex region */ public Region getWalls() { - Vector min = getMinimumPoint(); - Vector max = getMaximumPoint(); + BlockVector3 min = getMinimumPoint(); + BlockVector3 max = getMaximumPoint(); return new RegionIntersection( // Project to Z-Y plane - new CuboidRegion(new Vector(min.getX(), pos1.getY(), pos1.getZ()), new Vector(min.getX(), pos2.getY(), pos2.getZ())), - new CuboidRegion(new Vector(max.getX(), pos1.getY(), pos1.getZ()), new Vector(max.getX(), pos2.getY(), pos2.getZ())), + new CuboidRegion(pos1.withX(min.getX()), pos2.withX(min.getX())), + new CuboidRegion(pos1.withX(max.getX()), pos2.withX(max.getX())), // Project to X-Y plane - new CuboidRegion(new Vector(pos1.getX(), pos1.getY(), min.getZ()), new Vector(pos2.getX(), pos2.getY(), min.getZ())), - new CuboidRegion(new Vector(pos1.getX(), pos1.getY(), max.getZ()), new Vector(pos2.getX(), pos2.getY(), max.getZ()))); + new CuboidRegion(pos1.withZ(min.getZ()), pos2.withZ(min.getZ())), + new CuboidRegion(pos1.withZ(max.getZ()), pos2.withZ(max.getZ()))); } @Override - public Vector getMinimumPoint() { - return new Vector(Math.min(pos1.getX(), pos2.getX()), - Math.min(pos1.getY(), pos2.getY()), - Math.min(pos1.getZ(), pos2.getZ())); + public BlockVector3 getMinimumPoint() { + return pos1.getMinimum(pos2); } @Override - public Vector getMaximumPoint() { - return new Vector(Math.max(pos1.getX(), pos2.getX()), - Math.max(pos1.getY(), pos2.getY()), - Math.max(pos1.getZ(), pos2.getZ())); + public BlockVector3 getMaximumPoint() { + return pos1.getMaximum(pos2); } @Override @@ -207,49 +202,49 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } @Override - public void expand(Vector... changes) { + public void expand(BlockVector3... changes) { checkNotNull(changes); - for (Vector change : changes) { + for (BlockVector3 change : changes) { if (change.getX() > 0) { if (Math.max(pos1.getX(), pos2.getX()) == pos1.getX()) { - pos1 = pos1.add(new Vector(change.getX(), 0, 0)); + pos1 = pos1.add(change.getX(), 0, 0); } else { - pos2 = pos2.add(new Vector(change.getX(), 0, 0)); + pos2 = pos2.add(change.getX(), 0, 0); } } else { if (Math.min(pos1.getX(), pos2.getX()) == pos1.getX()) { - pos1 = pos1.add(new Vector(change.getX(), 0, 0)); + pos1 = pos1.add(change.getX(), 0, 0); } else { - pos2 = pos2.add(new Vector(change.getX(), 0, 0)); + pos2 = pos2.add(change.getX(), 0, 0); } } if (change.getY() > 0) { if (Math.max(pos1.getY(), pos2.getY()) == pos1.getY()) { - pos1 = pos1.add(new Vector(0, change.getY(), 0)); + pos1 = pos1.add(0, change.getY(), 0); } else { - pos2 = pos2.add(new Vector(0, change.getY(), 0)); + pos2 = pos2.add(0, change.getY(), 0); } } else { if (Math.min(pos1.getY(), pos2.getY()) == pos1.getY()) { - pos1 = pos1.add(new Vector(0, change.getY(), 0)); + pos1 = pos1.add(0, change.getY(), 0); } else { - pos2 = pos2.add(new Vector(0, change.getY(), 0)); + pos2 = pos2.add(0, change.getY(), 0); } } if (change.getZ() > 0) { if (Math.max(pos1.getZ(), pos2.getZ()) == pos1.getZ()) { - pos1 = pos1.add(new Vector(0, 0, change.getZ())); + pos1 = pos1.add(0, 0, change.getZ()); } else { - pos2 = pos2.add(new Vector(0, 0, change.getZ())); + pos2 = pos2.add(0, 0, change.getZ()); } } else { if (Math.min(pos1.getZ(), pos2.getZ()) == pos1.getZ()) { - pos1 = pos1.add(new Vector(0, 0, change.getZ())); + pos1 = pos1.add(0, 0, change.getZ()); } else { - pos2 = pos2.add(new Vector(0, 0, change.getZ())); + pos2 = pos2.add(0, 0, change.getZ()); } } } @@ -258,49 +253,49 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } @Override - public void contract(Vector... changes) { + public void contract(BlockVector3... changes) { checkNotNull(changes); - for (Vector change : changes) { + for (BlockVector3 change : changes) { if (change.getX() < 0) { if (Math.max(pos1.getX(), pos2.getX()) == pos1.getX()) { - pos1 = pos1.add(new Vector(change.getX(), 0, 0)); + pos1 = pos1.add(change.getX(), 0, 0); } else { - pos2 = pos2.add(new Vector(change.getX(), 0, 0)); + pos2 = pos2.add(change.getX(), 0, 0); } } else { if (Math.min(pos1.getX(), pos2.getX()) == pos1.getX()) { - pos1 = pos1.add(new Vector(change.getX(), 0, 0)); + pos1 = pos1.add(change.getX(), 0, 0); } else { - pos2 = pos2.add(new Vector(change.getX(), 0, 0)); + pos2 = pos2.add(change.getX(), 0, 0); } } if (change.getY() < 0) { if (Math.max(pos1.getY(), pos2.getY()) == pos1.getY()) { - pos1 = pos1.add(new Vector(0, change.getY(), 0)); + pos1 = pos1.add(0, change.getY(), 0); } else { - pos2 = pos2.add(new Vector(0, change.getY(), 0)); + pos2 = pos2.add(0, change.getY(), 0); } } else { if (Math.min(pos1.getY(), pos2.getY()) == pos1.getY()) { - pos1 = pos1.add(new Vector(0, change.getY(), 0)); + pos1 = pos1.add(0, change.getY(), 0); } else { - pos2 = pos2.add(new Vector(0, change.getY(), 0)); + pos2 = pos2.add(0, change.getY(), 0); } } if (change.getZ() < 0) { if (Math.max(pos1.getZ(), pos2.getZ()) == pos1.getZ()) { - pos1 = pos1.add(new Vector(0, 0, change.getZ())); + pos1 = pos1.add(0, 0, change.getZ()); } else { - pos2 = pos2.add(new Vector(0, 0, change.getZ())); + pos2 = pos2.add(0, 0, change.getZ()); } } else { if (Math.min(pos1.getZ(), pos2.getZ()) == pos1.getZ()) { - pos1 = pos1.add(new Vector(0, 0, change.getZ())); + pos1 = pos1.add(0, 0, change.getZ()); } else { - pos2 = pos2.add(new Vector(0, 0, change.getZ())); + pos2 = pos2.add(0, 0, change.getZ()); } } } @@ -309,20 +304,20 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } @Override - public Set getChunks() { - Vector min = getMinimumPoint(); - Vector max = getMaximumPoint(); + public Set getChunks() { + BlockVector3 min = getMinimumPoint(); + BlockVector3 max = getMaximumPoint(); final int maxX = max.getBlockX() >> ChunkStore.CHUNK_SHIFTS; final int minX = min.getBlockX() >> ChunkStore.CHUNK_SHIFTS; final int maxZ = max.getBlockZ() >> ChunkStore.CHUNK_SHIFTS; final int minZ = min.getBlockZ() >> ChunkStore.CHUNK_SHIFTS; final int size = (maxX - minX + 1) * (maxZ - minZ + 1); - return new AbstractSet() { + return new AbstractSet() { @Override - public Iterator iterator() { - return new Iterator() { - private MutableBlockVector2D pos = new MutableBlockVector2D().setComponents(maxX + 1, maxZ); + public Iterator iterator() { + return new Iterator() { + private MutableBlockVector2 pos = new MutableBlockVector2().setComponents(maxX + 1, maxZ); @Override public boolean hasNext() { @@ -330,8 +325,8 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } @Override - public Vector2D next() { - Vector2D result = pos; + public BlockVector2 next() { + MutableBlockVector2 result = pos; // calc next pos.setComponents(pos.getX() - 1, pos.getZ()); if (pos.getX() <= minX) { @@ -351,15 +346,22 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { }; } +//<<<<<<< HEAD @Override public int size() { return size; } +//======= +// for (int x = min.getBlockX() >> ChunkStore.CHUNK_SHIFTS; x <= max.getBlockX() >> ChunkStore.CHUNK_SHIFTS; ++x) { +// for (int z = min.getBlockZ() >> ChunkStore.CHUNK_SHIFTS; z <= max.getBlockZ() >> ChunkStore.CHUNK_SHIFTS; ++z) { +// chunks.add(BlockVector2.at(x, z)); +//>>>>>>> 2c8b2fe0... Move vectors to static creators, for caching + @Override public boolean contains(Object o) { - if (o instanceof Vector2D) { - Vector2D cv = (Vector2D) o; + if (o instanceof BlockVector2) { + BlockVector2 cv = (BlockVector2) o; return cv.getX() >= minX && cv.getX() <= maxX && cv.getZ() >= minZ && cv.getZ() <= maxZ; } else { return false; @@ -367,26 +369,23 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } }; } - - @Override - public void shift(Vector change) throws RegionOperationException { + public void shift(BlockVector3 change) throws RegionOperationException { pos1 = pos1.add(change); pos2 = pos2.add(change); recalculate(); } - @Override - public Set getChunkCubes() { - Set chunks = new LocalBlockVectorSet(); + public Set getChunkCubes() { + Set chunks = new HashSet<>(); - Vector min = getMinimumPoint(); - Vector max = getMaximumPoint(); + BlockVector3 min = getMinimumPoint(); + BlockVector3 max = getMaximumPoint(); - for (int x = max.getBlockX() >> ChunkStore.CHUNK_SHIFTS; x >= min.getBlockX() >> ChunkStore.CHUNK_SHIFTS; --x) { - for (int z = max.getBlockZ() >> ChunkStore.CHUNK_SHIFTS; z >= min.getBlockZ() >> ChunkStore.CHUNK_SHIFTS; --z) { - for (int y = max.getBlockY() >> ChunkStore.CHUNK_SHIFTS; y >= min.getBlockY() >> ChunkStore.CHUNK_SHIFTS; --y) { - chunks.add(new Vector(x, y, z)); + for (int x = min.getBlockX() >> ChunkStore.CHUNK_SHIFTS; x <= max.getBlockX() >> ChunkStore.CHUNK_SHIFTS; ++x) { + for (int z = min.getBlockZ() >> ChunkStore.CHUNK_SHIFTS; z <= max.getBlockZ() >> ChunkStore.CHUNK_SHIFTS; ++z) { + for (int y = min.getBlockY() >> ChunkStore.CHUNK_SHIFTS; y <= max.getBlockY() >> ChunkStore.CHUNK_SHIFTS; ++y) { + chunks.add(BlockVector3.at(x, y, z)); } } } @@ -394,10 +393,6 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { return chunks; } - @Override - public boolean contains(Vector position) { - return contains(position.getBlockX(), position.getBlockY(), position.getBlockZ()); - } // private int ly = Integer.MIN_VALUE; // private int lz = Integer.MIN_VALUE; @@ -426,16 +421,22 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { public boolean contains(int x, int z) { return x >= this.minX && x <= this.maxX && z >= this.minZ && z <= this.maxZ; } + @Override + public boolean contains(BlockVector3 position) { + BlockVector3 min = getMinimumPoint(); + BlockVector3 max = getMaximumPoint(); + return position.containedWithin(min, max); + } @Override - public Iterator iterator() { + public Iterator iterator() { if (Settings.IMP.HISTORY.COMPRESSION_LEVEL >= 9 || useOldIterator) { return iterator_old(); } - return new Iterator() { - final MutableBlockVector mutable = new MutableBlockVector(0, 0, 0); - private Vector min = getMinimumPoint(); - private Vector max = getMaximumPoint(); + return new Iterator() { + final MutableBlockVector3 mutable = new MutableBlockVector3(0, 0, 0); + private BlockVector3 min = getMinimumPoint(); + private BlockVector3 max = getMaximumPoint(); int bx = min.getBlockX(); int by = min.getBlockY(); @@ -458,13 +459,15 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { public boolean hasNext = true; + @Override public boolean hasNext() { return hasNext; } @Override - public BlockVector next() { + public BlockVector3 next() { +//<<<<<<< HEAD mutable.mutX(x); mutable.mutY(y); mutable.mutZ(z); @@ -500,6 +503,16 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } else { x = cbx; z = cbz; +//======= +// if (!hasNext()) throw new NoSuchElementException(); +// BlockVector3 answer = BlockVector3.at(nextX, nextY, nextZ); +// if (++nextX > max.getBlockX()) { +// nextX = min.getBlockX(); +// if (++nextY > max.getBlockY()) { +// nextY = min.getBlockY(); +// if (++nextZ > max.getBlockZ()) { +// nextX = Integer.MIN_VALUE; +//>>>>>>> 2c8b2fe0... Move vectors to static creators, for caching } } else { x = cbx; @@ -507,19 +520,15 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } return mutable; } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } }; } - public Iterator iterator_old() { - final MutableBlockVector mutable = new MutableBlockVector(0, 0, 0); - return new Iterator() { - private Vector min = getMinimumPoint(); - private Vector max = getMaximumPoint(); + public Iterator iterator_old() { + final MutableBlockVector3 mutable = new MutableBlockVector3(0, 0, 0); + return new Iterator() { + private BlockVector3 min = getMinimumPoint(); + private BlockVector3 max = getMaximumPoint(); + private int nextX = min.getBlockX(); private int nextY = min.getBlockY(); private int nextZ = min.getBlockZ(); @@ -531,10 +540,16 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } @Override - public BlockVector next() { +//<<<<<<< HEAD + public BlockVector3 next() { mutable.mutX(nextX); mutable.mutY(nextY); mutable.mutZ(nextZ); +//======= +// public BlockVector2 next() { +// if (!hasNext()) throw new NoSuchElementException(); +// BlockVector2 answer = BlockVector2.at(nextX, nextZ); +//>>>>>>> 2c8b2fe0... Move vectors to static creators, for caching if (++nextX > max.getBlockX()) { nextX = min.getBlockX(); if (++nextZ > max.getBlockZ()) { @@ -557,23 +572,18 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } return mutable; } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } }; } @Override - public Iterable asFlatRegion() { - return new Iterable() { + public Iterable asFlatRegion() { + return new Iterable() { @Override - public Iterator iterator() { - MutableBlockVector2D mutable = new MutableBlockVector2D(); - return new Iterator() { - private Vector min = getMinimumPoint(); - private Vector max = getMaximumPoint(); + public Iterator iterator() { + MutableBlockVector2 mutable = new MutableBlockVector2(); + return new Iterator() { + private BlockVector3 min = getMinimumPoint(); + private BlockVector3 max = getMaximumPoint(); private int nextX = min.getBlockX(); private int nextZ = min.getBlockZ(); @@ -583,9 +593,10 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } @Override - public Vector2D next() { + public BlockVector2 next() { if (!hasNext()) throw new java.util.NoSuchElementException(); - Vector2D answer = mutable.setComponents(nextX, nextZ); +// BlockVector2 answer = mutable.setComponents(nextX, nextZ); + BlockVector2 answer = BlockVector2.at(nextX, nextZ); if (++nextX > max.getBlockX()) { nextX = min.getBlockX(); if (++nextZ > max.getBlockZ()) { @@ -636,8 +647,8 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { } public static boolean contains(CuboidRegion region) { - Vector min = region.getMinimumPoint(); - Vector max = region.getMaximumPoint(); + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); return region.contains(min.getBlockX(), min.getBlockY(), min.getBlockZ()) && region.contains(max.getBlockX(), max.getBlockY(), max.getBlockZ()); } @@ -648,10 +659,10 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion { * @param apothem the apothem, where 0 is the minimum value to make a 1x1 cuboid * @return a cuboid region */ - public static CuboidRegion fromCenter(Vector origin, int apothem) { + public static CuboidRegion fromCenter(BlockVector3 origin, int apothem) { checkNotNull(origin); checkArgument(apothem >= 0, "apothem => 0 required"); - Vector size = new Vector(1, 1, 1).multiply(apothem); + BlockVector3 size = BlockVector3.ONE.multiply(apothem); return new CuboidRegion(origin.subtract(size), origin.add(size)); } 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 afe7a7367..9524874f2 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 @@ -19,11 +19,13 @@ package com.sk89q.worldedit.regions; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.BlockVector2D; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.Vector2; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.geom.Polygons; import com.sk89q.worldedit.regions.iterator.FlatRegion3DIterator; import com.sk89q.worldedit.regions.iterator.FlatRegionIterator; @@ -39,9 +41,9 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class CylinderRegion extends AbstractRegion implements FlatRegion { - private BlockVector2D center; - private BlockVector2D radius; - private Vector2D radiusInverse; + private BlockVector2 center; + private Vector2 radius; + private Vector2 radiusInverse; private int minY; private int maxY; private boolean hasY = false; @@ -59,7 +61,7 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * @param world the world */ public CylinderRegion(World world) { - this(world, new Vector(), new Vector2D(), 0, 0); + this(world, BlockVector3.ZERO, Vector2.ZERO, 0, 0); hasY = false; } @@ -72,9 +74,9 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * @param minY the minimum Y, inclusive * @param maxY the maximum Y, inclusive */ - public CylinderRegion(World world, Vector center, Vector2D radius, int minY, int maxY) { + public CylinderRegion(World world, BlockVector3 center, Vector2 radius, int minY, int maxY) { super(world); - setCenter(center.toVector2D()); + setCenter(center.toBlockVector2()); setRadius(radius); this.minY = minY; this.maxY = maxY; @@ -89,9 +91,9 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * @param minY the minimum Y, inclusive * @param maxY the maximum Y, inclusive */ - public CylinderRegion(Vector center, Vector2D radius, int minY, int maxY) { + public CylinderRegion(BlockVector3 center, Vector2 radius, int minY, int maxY) { super(null); - setCenter(center.toVector2D()); + setCenter(center.toBlockVector2()); setRadius(radius); this.minY = minY; this.maxY = maxY; @@ -99,23 +101,13 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { } public CylinderRegion(CylinderRegion region) { - this(region.world, region.getCenter(), region.getRadius(), region.minY, region.maxY); + this(region.world, region.getCenter().toBlockPoint(), region.getRadius(), region.minY, region.maxY); hasY = region.hasY; } - @Override - public Vector getCenter() { - return center.toVector((getMaximumY() + getMinimumY()) / 2); - } - - /** - * Sets the main center point of the region - * - * @deprecated replaced by {@link #setCenter(Vector2D)} - */ - @Deprecated - public void setCenter(Vector center) { - setCenter(center.toVector2D()); + @Override + public Vector3 getCenter() { + return center.toVector3((maxY + minY) / 2); } /** @@ -123,8 +115,8 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * * @param center the center point */ - public void setCenter(Vector2D center) { - this.center = new BlockVector2D(center); + public void setCenter(BlockVector2 center) { + this.center = center; } /** @@ -132,7 +124,7 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * * @return the radius along the X and Z axes */ - public Vector2D getRadius() { + public Vector2 getRadius() { return radius.subtract(0.5, 0.5); } @@ -141,9 +133,9 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * * @param radius the radius along the X and Z axes */ - public void setRadius(Vector2D radius) { - this.radius = radius.add(0.5, 0.5).toBlockVector2D(); - this.radiusInverse = Vector2D.ONE.divide(radius); + public void setRadius(Vector2 radius) { + this.radius = radius.add(0.5, 0.5); + this.radiusInverse = Vector2.ONE.divide(radius); } /** @@ -151,8 +143,8 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * * @param minRadius the minimum radius */ - public void extendRadius(Vector2D minRadius) { - setRadius(Vector2D.getMaximum(minRadius, getRadius())); + public void extendRadius(Vector2 minRadius) { + setRadius(minRadius.getMaximum(getRadius())); } /** @@ -174,15 +166,15 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { hasY = true; maxY = y; } - + @Override - public Vector getMinimumPoint() { - return center.subtract(getRadius()).toVector(getMinimumY()); + public BlockVector3 getMinimumPoint() { + return center.toVector2().subtract(getRadius()).toVector3(minY).toBlockPoint(); } @Override - public Vector getMaximumPoint() { - return center.add(getRadius()).toVector(getMaximumY()); + public BlockVector3 getMaximumPoint() { + return center.toVector2().add(getRadius()).toVector3(maxY).toBlockPoint(); } @Override @@ -222,10 +214,10 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { return (int) (2 * radius.getZ()); } - private Vector2D calculateDiff2D(Vector... changes) throws RegionOperationException { - Vector2D diff = new Vector2D(); - for (Vector change : changes) { - diff = diff.add(change.toVector2D()); + private BlockVector2 calculateDiff2D(BlockVector3... changes) throws RegionOperationException { + BlockVector2 diff = BlockVector2.ZERO; + for (BlockVector3 change : changes) { + diff = diff.add(change.toBlockVector2()); } if ((diff.getBlockX() & 1) + (diff.getBlockZ() & 1) != 0) { @@ -235,10 +227,10 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { return diff.divide(2).floor(); } - private Vector2D calculateChanges2D(Vector... changes) { - Vector2D total = new Vector2D(); - for (Vector change : changes) { - total = total.add(change.toVector2D().positive()); + private BlockVector2 calculateChanges2D(BlockVector3... changes) { + BlockVector2 total = BlockVector2.ZERO; + for (BlockVector3 change : changes) { + total = total.add(change.toBlockVector2().abs()); } return total.divide(2).floor(); @@ -252,11 +244,11 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * @throws RegionOperationException */ @Override - public void expand(Vector... changes) throws RegionOperationException { - center = center.add(calculateDiff2D(changes)).toBlockVector2D(); - radius = radius.add(calculateChanges2D(changes)).toBlockVector2D(); - this.radiusInverse = Vector2D.ONE.divide(radius); - for (Vector change : changes) { + public void expand(BlockVector3... changes) throws RegionOperationException { + center = center.add(calculateDiff2D(changes)); + radius = radius.add(calculateChanges2D(changes).toVector2()); + this.radiusInverse = Vector2.ONE.divide(radius); + for (BlockVector3 change : changes) { int changeY = change.getBlockY(); if (changeY > 0) { maxY += changeY; @@ -273,12 +265,12 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * @throws RegionOperationException */ @Override - public void contract(Vector... changes) throws RegionOperationException { - center = center.subtract(calculateDiff2D(changes)).toBlockVector2D(); - Vector2D newRadius = radius.subtract(calculateChanges2D(changes)); - radius = Vector2D.getMaximum(new Vector2D(1.5, 1.5), newRadius).toBlockVector2D(); - this.radiusInverse = Vector2D.ONE.divide(radius); - for (Vector change : changes) { + public void contract(BlockVector3... changes) throws RegionOperationException { + center = center.subtract(calculateDiff2D(changes)); + Vector2 newRadius = radius.subtract(calculateChanges2D(changes).toVector2()); + radius = Vector2.at(1.5, 1.5).getMaximum(newRadius); + this.radiusInverse = Vector2.ONE.divide(radius); + for (BlockVector3 change : changes) { int height = maxY - minY; int changeY = change.getBlockY(); if (changeY > 0) { @@ -290,8 +282,8 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { } @Override - public void shift(Vector change) throws RegionOperationException { - center = center.add(change.toVector2D()).toBlockVector2D(); + public void shift(BlockVector3 change) throws RegionOperationException { + center = center.add(change.toBlockVector2()); int changeY = change.getBlockY(); maxY += changeY; @@ -302,9 +294,9 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * Checks to see if a point is inside this region. */ @Override - public boolean contains(Vector position) { - final int pt = position.getBlockY(); - if (pt < getMinimumY() || pt > getMaximumY()) { + public boolean contains(BlockVector3 position) { + final int blockY = position.getBlockY(); + if (blockY < minY || blockY > maxY) { return false; } int px = position.getBlockX(); @@ -314,6 +306,7 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { double dz = Math.abs(pz - center.getBlockZ()) * radiusInverse.getZ(); return dx * dx + dz * dz <= 1; +// return position.subtract(center).toVector2().divide(radius).lengthSq() <= 1; } @@ -341,18 +334,13 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { } @Override - public Iterator iterator() { + public Iterator iterator() { return new FlatRegion3DIterator(this); } @Override - public Iterable asFlatRegion() { - return new Iterable() { - @Override - public Iterator iterator() { - return new FlatRegionIterator(CylinderRegion.this); - } - }; + public Iterable asFlatRegion() { + return () -> new FlatRegionIterator(CylinderRegion.this); } /** @@ -372,7 +360,7 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { } @Override - public List polygonize(int maxPoints) { + public List polygonize(int maxPoints) { return Polygons.polygonizeCylinder(center, radius, maxPoints); } @@ -386,10 +374,10 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion { * @param radius the radius in the X and Z axes * @return a region */ - public static CylinderRegion createRadius(Extent extent, Vector center, double radius) { + public static CylinderRegion createRadius(Extent extent, BlockVector3 center, double radius) { checkNotNull(extent); checkNotNull(center); - Vector2D radiusVec = new Vector2D(radius, radius); + Vector2 radiusVec = Vector2.at(radius, radius); int minY = extent.getMinimumPoint().getBlockY(); int maxY = extent.getMaximumPoint().getBlockY(); return new CylinderRegion(center, radiusVec, minY, maxY); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/EllipsoidRegion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/EllipsoidRegion.java index a35614bc5..f7c209a14 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/EllipsoidRegion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/EllipsoidRegion.java @@ -19,11 +19,11 @@ package com.sk89q.worldedit.regions; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.BlockVector2D; -import com.sk89q.worldedit.MutableBlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; + +import com.sk89q.worldedit.math.MutableBlockVector3; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.storage.ChunkStore; import java.util.HashSet; @@ -37,13 +37,13 @@ public class EllipsoidRegion extends AbstractRegion { /** * Stores the center. */ - private MutableBlockVector center; + private BlockVector3 center; /** * Stores the radii plus 0.5 on each axis. */ - private MutableBlockVector radius; - private MutableBlockVector radiusSqr; + private Vector3 radius; + private Vector3 radiusSqr; private int radiusLengthSqr; private boolean sphere; @@ -53,7 +53,7 @@ public class EllipsoidRegion extends AbstractRegion { * @param pos1 the first position * @param pos2 the second position */ - public EllipsoidRegion(Vector pos1, Vector pos2) { + public EllipsoidRegion(BlockVector3 pos1, Vector3 pos2) { this(null, pos1, pos2); } @@ -65,9 +65,9 @@ public class EllipsoidRegion extends AbstractRegion { * @param center the center * @param radius the radius */ - public EllipsoidRegion(World world, Vector center, Vector radius) { + public EllipsoidRegion(World world, BlockVector3 center, Vector3 radius) { super(world); - this.center = new MutableBlockVector(center); + this.center = center; setRadius(radius); } @@ -76,13 +76,13 @@ public class EllipsoidRegion extends AbstractRegion { } @Override - public Vector getMinimumPoint() { - return center.subtract(getRadius()).clampY(0, 255); + public BlockVector3 getMinimumPoint() { + return center.toVector3().subtract(getRadius()).toBlockPoint(); } @Override - public Vector getMaximumPoint() { - return center.add(getRadius()).clampY(0, 255); + public BlockVector3 getMaximumPoint() { + return center.toVector3().add(getRadius()).toBlockPoint(); } @Override @@ -106,8 +106,8 @@ public class EllipsoidRegion extends AbstractRegion { return (int) (2 * radius.getZ()); } - private Vector calculateDiff(Vector... changes) throws RegionOperationException { - Vector diff = new Vector().add(changes); + private BlockVector3 calculateDiff(BlockVector3... changes) throws RegionOperationException { + BlockVector3 diff = BlockVector3.ZERO.add(changes); if ((diff.getBlockX() & 1) + (diff.getBlockY() & 1) + (diff.getBlockZ() & 1) != 0) { throw new RegionOperationException( @@ -117,31 +117,31 @@ public class EllipsoidRegion extends AbstractRegion { return diff.divide(2).floor(); } - private Vector calculateChanges(Vector... changes) { - Vector total = new Vector(); - for (Vector change : changes) { - total = total.add(change.positive()); + private BlockVector3 calculateChanges(BlockVector3... changes) { + BlockVector3 total = BlockVector3.ZERO; + for (BlockVector3 change : changes) { + total = total.add(change.abs()); } return total.divide(2).floor(); } @Override - public void expand(Vector... changes) throws RegionOperationException { - center = new MutableBlockVector(center.add(calculateDiff(changes))); - setRadius(radius.add(calculateChanges(changes))); + public void expand(BlockVector3... changes) throws RegionOperationException { + center = center.add(calculateDiff(changes)); + setRadius(radius.add(calculateChanges(changes).toVector3())); } @Override - public void contract(Vector... changes) throws RegionOperationException { - center = new MutableBlockVector(center.subtract(calculateDiff(changes))); - Vector newRadius = radius.subtract(calculateChanges(changes)); - setRadius(Vector.getMaximum(new Vector(1.5, 1.5, 1.5), newRadius)); + public void contract(BlockVector3... changes) throws RegionOperationException { + center = center.subtract(calculateDiff(changes)); + Vector3 newRadius = radius.subtract(calculateChanges(changes).toVector3()); + setRadius(Vector3.at(1.5, 1.5, 1.5).getMaximum(newRadius)); } @Override - public void shift(Vector change) throws RegionOperationException { - center = new MutableBlockVector(center.add(change)); + public void shift(BlockVector3 change) throws RegionOperationException { + center = center.add(change); } /** @@ -150,8 +150,8 @@ public class EllipsoidRegion extends AbstractRegion { * @return center */ @Override - public Vector getCenter() { - return center; + public Vector3 getCenter() { + return center.toVector3(); } /** @@ -159,8 +159,8 @@ public class EllipsoidRegion extends AbstractRegion { * * @param center the center */ - public void setCenter(Vector center) { - this.center = new MutableBlockVector(center); + public void setCenter(BlockVector3 center) { + this.center = center; } /** @@ -168,7 +168,7 @@ public class EllipsoidRegion extends AbstractRegion { * * @return radii */ - public Vector getRadius() { + public Vector3 getRadius() { if (radius == null) return null; return radius.subtract(0.5, 0.5, 0.5); } @@ -178,11 +178,11 @@ public class EllipsoidRegion extends AbstractRegion { * * @param radius the radius */ - public void setRadius(Vector radius) { - this.radius = new MutableBlockVector(radius.add(0.5, 0.5, 0.5)); - radiusSqr = new MutableBlockVector(radius.multiply(radius)); - radiusLengthSqr = radiusSqr.getBlockX(); - if (radius.getBlockY() == radius.getBlockX() && radius.getBlockX() == radius.getBlockZ()) { + public void setRadius(Vector3 radius) { + this.radius = radius; + radiusSqr = radius.multiply(radius); + radiusLengthSqr = (int) radiusSqr.getX(); + if (radius.getY() == radius.getX() && radius.getX() == radius.getZ()) { this.sphere = true; } else { this.sphere = false; @@ -190,22 +190,22 @@ public class EllipsoidRegion extends AbstractRegion { } @Override - public Set getChunks() { - final Set chunks = new HashSet(); + public Set getChunks() { + final Set chunks = new HashSet<>(); - final Vector min = getMinimumPoint(); - final Vector max = getMaximumPoint(); - final int centerY = getCenter().getBlockY(); + final BlockVector3 min = getMinimumPoint(); + final BlockVector3 max = getMaximumPoint(); + final int centerY = center.getBlockY(); for (int x = min.getBlockX(); x <= max.getBlockX(); ++x) { for (int z = min.getBlockZ(); z <= max.getBlockZ(); ++z) { - if (!contains(new BlockVector(x, centerY, z))) { + if (!contains(BlockVector3.at(x, centerY, z))) { continue; } - chunks.add(new BlockVector2D( - x >> ChunkStore.CHUNK_SHIFTS, - z >> ChunkStore.CHUNK_SHIFTS + chunks.add(BlockVector2.at( + x >> ChunkStore.CHUNK_SHIFTS, + z >> ChunkStore.CHUNK_SHIFTS )); } } @@ -214,29 +214,31 @@ public class EllipsoidRegion extends AbstractRegion { } @Override - public boolean contains(Vector position) { - int cx = position.getBlockX() - center.getBlockX(); - int cx2 = cx * cx; - if (cx2 > radiusSqr.getBlockX()) { - return false; - } - int cz = position.getBlockZ() - center.getBlockZ(); - int cz2 = cz * cz; - if (cz2 > radiusSqr.getBlockZ()) { - return false; - } - int cy = position.getBlockY() - center.getBlockY(); - int cy2 = cy * cy; - if (radiusSqr.getBlockY() < 255 && cy2 > radiusSqr.getBlockY()) { - return false; - } - if (sphere) { - return cx2 + cy2 + cz2 <= radiusLengthSqr; - } - double cxd = (double) cx / radius.getBlockX(); - double cyd = (double) cy / radius.getBlockY(); - double czd = (double) cz / radius.getBlockZ(); - return cxd * cxd + cyd * cyd + czd * czd <= 1; +// public boolean contains(Vector position) { +// int cx = position.getBlockX() - center.getBlockX(); +// int cx2 = cx * cx; +// if (cx2 > radiusSqr.getBlockX()) { +// return false; +// } +// int cz = position.getBlockZ() - center.getBlockZ(); +// int cz2 = cz * cz; +// if (cz2 > radiusSqr.getBlockZ()) { +// return false; +// } +// int cy = position.getBlockY() - center.getBlockY(); +// int cy2 = cy * cy; +// if (radiusSqr.getBlockY() < 255 && cy2 > radiusSqr.getBlockY()) { +// return false; +// } +// if (sphere) { +// return cx2 + cy2 + cz2 <= radiusLengthSqr; +// } +// double cxd = (double) cx / radius.getBlockX(); +// double cyd = (double) cy / radius.getBlockY(); +// double czd = (double) cz / radius.getBlockZ(); +// return cxd * cxd + cyd * cyd + czd * czd <= 1; + public boolean contains(BlockVector3 position) { + return position.subtract(center).divide(radius.toBlockPoint()).lengthSq() <= 1; } /** @@ -250,8 +252,8 @@ public class EllipsoidRegion extends AbstractRegion { return center + " - " + getRadius(); } - public void extendRadius(Vector minRadius) { - setRadius(Vector.getMaximum(minRadius, getRadius())); + public void extendRadius(Vector3 minRadius) { + setRadius(minRadius.getMaximum(getRadius())); } @Override diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/FlatRegion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/FlatRegion.java index 92cdf6e36..bd4561e4d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/FlatRegion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/FlatRegion.java @@ -19,7 +19,7 @@ package com.sk89q.worldedit.regions; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; public interface FlatRegion extends Region { @@ -42,5 +42,5 @@ public interface FlatRegion extends Region { * * @return a flat region iterable */ - Iterable asFlatRegion(); + Iterable asFlatRegion(); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/IDelegateRegion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/IDelegateRegion.java index 131e46b8b..be3c64e82 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/IDelegateRegion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/IDelegateRegion.java @@ -1,6 +1,10 @@ package com.sk89q.worldedit.regions; import com.sk89q.worldedit.*; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector2; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.world.World; import java.util.Iterator; import java.util.List; @@ -12,22 +16,22 @@ public interface IDelegateRegion extends Region { public Region getRegion(); @Override - default Iterator iterator() { + default Iterator iterator() { return getRegion().iterator(); } @Override - default Vector getMinimumPoint() { + default BlockVector3 getMinimumPoint() { return getRegion().getMinimumPoint(); } @Override - default Vector getMaximumPoint() { + default BlockVector3 getMaximumPoint() { return getRegion().getMaximumPoint(); } @Override - default Vector getCenter() { + default Vector3 getCenter() { return getRegion().getCenter(); } @@ -52,32 +56,32 @@ public interface IDelegateRegion extends Region { } @Override - default void expand(Vector... changes) throws RegionOperationException { + default void expand(BlockVector3... changes) throws RegionOperationException { getRegion().expand(changes); } @Override - default void contract(Vector... changes) throws RegionOperationException { + default void contract(BlockVector3... changes) throws RegionOperationException { getRegion().contract(changes); } @Override - default void shift(Vector change) throws RegionOperationException { + default void shift(BlockVector3 change) throws RegionOperationException { getRegion().shift(change); } @Override - default boolean contains(Vector position) { + default boolean contains(BlockVector3 position) { return getRegion().contains(position); } @Override - default Set getChunks() { + default Set getChunks() { return getRegion().getChunks(); } @Override - default Set getChunkCubes() { + default Set getChunkCubes() { return getRegion().getChunkCubes(); } @@ -98,7 +102,7 @@ public interface IDelegateRegion extends Region { } @Override - default List polygonize(int maxPoints) { + default List polygonize(int maxPoints) { return getRegion().polygonize(maxPoints); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/NullRegion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/NullRegion.java index 7730b6756..570f0a80d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/NullRegion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/NullRegion.java @@ -20,7 +20,9 @@ package com.sk89q.worldedit.regions; import com.sk89q.worldedit.*; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.world.World; import java.util.*; @@ -33,18 +35,18 @@ public class NullRegion implements Region { private World world; @Override - public Vector getMinimumPoint() { - return new Vector(0, 0, 0); + public BlockVector3 getMinimumPoint() { + return BlockVector3.ZERO; } @Override - public Vector getMaximumPoint() { - return new Vector(0, 0, 0); + public BlockVector3 getMaximumPoint() { + return BlockVector3.ZERO; } @Override - public Vector getCenter() { - return new Vector(0, 0, 0); + public Vector3 getCenter() { + return Vector3.ZERO; } @Override @@ -68,32 +70,32 @@ public class NullRegion implements Region { } @Override - public void expand(Vector... changes) throws RegionOperationException { + public void expand(BlockVector3... changes) throws RegionOperationException { throw new RegionOperationException("Cannot change NullRegion"); } @Override - public void contract(Vector... changes) throws RegionOperationException { + public void contract(BlockVector3... changes) throws RegionOperationException { throw new RegionOperationException("Cannot change NullRegion"); } @Override - public void shift(Vector change) throws RegionOperationException { + public void shift(BlockVector3 change) throws RegionOperationException { throw new RegionOperationException("Cannot change NullRegion"); } @Override - public boolean contains(Vector position) { + public boolean contains(BlockVector3 position) { return false; } @Override - public Set getChunks() { + public Set getChunks() { return Collections.emptySet(); } @Override - public Set getChunkCubes() { + public Set getChunkCubes() { return Collections.emptySet(); } @@ -113,27 +115,22 @@ public class NullRegion implements Region { } @Override - public List polygonize(int maxPoints) { + public List polygonize(int maxPoints) { return Collections.emptyList(); } @Override - public Iterator iterator() { - return new Iterator() { + public Iterator iterator() { + return new Iterator() { @Override public boolean hasNext() { return false; } @Override - public BlockVector next() { + public BlockVector3 next() { throw new NoSuchElementException(); } - - @Override - public void remove() { - throw new UnsupportedOperationException("Cannot remove"); - } }; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/Polygonal2DRegion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/Polygonal2DRegion.java index 4371aec40..5ea83211e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/Polygonal2DRegion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/Polygonal2DRegion.java @@ -19,10 +19,8 @@ package com.sk89q.worldedit.regions; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.BlockVector2D; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.iterator.FlatRegion3DIterator; import com.sk89q.worldedit.regions.iterator.FlatRegionIterator; import com.sk89q.worldedit.world.World; @@ -37,9 +35,9 @@ import java.util.List; */ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { - private List points; - private Vector2D min; - private Vector2D max; + private List points; + private BlockVector2 min; + private BlockVector2 max; private int minY; private int maxY; private boolean hasY = false; @@ -57,7 +55,7 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { * @param world the world */ public Polygonal2DRegion(World world) { - this(world, Collections.emptyList(), 0, 0); + this(world, Collections.emptyList(), 0, 0); hasY = false; } @@ -69,7 +67,7 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { * @param minY minimum Y * @param maxY maximum Y */ - public Polygonal2DRegion(World world, List points, int minY, int maxY) { + public Polygonal2DRegion(World world, List points, int minY, int maxY) { super(world); this.points = new ArrayList<>(points); this.minY = minY; @@ -93,7 +91,7 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { * * @return a list of points */ - public List getPoints() { + public List getPoints() { return Collections.unmodifiableList(points); } @@ -103,9 +101,9 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { */ protected void recalculate() { if (points.isEmpty()) { - min = new Vector2D(0, 0); + min = BlockVector2.ZERO; minY = 0; - max = new Vector2D(0, 0); + max = BlockVector2.ZERO; maxY = 0; return; } @@ -115,7 +113,7 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { int maxX = points.get(0).getBlockX(); int maxZ = points.get(0).getBlockZ(); - for (BlockVector2D v : points) { + for (BlockVector2 v : points) { int x = v.getBlockX(); int z = v.getBlockZ(); if (x < minX) minX = x; @@ -132,8 +130,8 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { minY = Math.min(Math.max(0, minY), world == null ? 255 : world.getMaxY()); maxY = Math.min(Math.max(0, maxY), world == null ? 255 : world.getMaxY()); - min = new Vector2D(minX, minZ); - max = new Vector2D(maxX, maxZ); + min = BlockVector2.at(minX, minZ); + max = BlockVector2.at(maxX, maxZ); } /** @@ -141,17 +139,7 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { * * @param position the position */ - public void addPoint(Vector2D position) { - points.add(position.toBlockVector2D()); - recalculate(); - } - - /** - * Add a point to the list. - * - * @param position the position - */ - public void addPoint(BlockVector2D position) { + public void addPoint(BlockVector2 position) { points.add(position); recalculate(); } @@ -161,8 +149,8 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { * * @param position the position */ - public void addPoint(Vector position) { - points.add(new BlockVector2D(position.getBlockX(), position.getBlockZ())); + public void addPoint(BlockVector3 position) { + points.add(BlockVector2.at(position.getBlockX(), position.getBlockZ())); recalculate(); } @@ -199,13 +187,13 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { } @Override - public Vector getMinimumPoint() { - return min.toVector(minY); + public BlockVector3 getMinimumPoint() { + return min.toBlockVector3(minY); } @Override - public Vector getMaximumPoint() { - return max.toVector(maxY); + public BlockVector3 getMaximumPoint() { + return max.toBlockVector3(maxY); } @Override @@ -239,14 +227,11 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { } @Override - public void expand(Vector... changes) throws RegionOperationException { - for (Vector change : changes) { + public void expand(BlockVector3... changes) throws RegionOperationException { + for (BlockVector3 change : changes) { if (change.getBlockX() != 0 || change.getBlockZ() != 0) { throw new RegionOperationException("Polygons can only be expanded vertically."); } - } - - for (Vector change : changes) { int changeY = change.getBlockY(); if (changeY > 0) { maxY += changeY; @@ -258,14 +243,11 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { } @Override - public void contract(Vector... changes) throws RegionOperationException { - for (Vector change : changes) { + public void contract(BlockVector3... changes) throws RegionOperationException { + for (BlockVector3 change : changes) { if (change.getBlockX() != 0 || change.getBlockZ() != 0) { throw new RegionOperationException("Polygons can only be contracted vertically."); } - } - - for (Vector change : changes) { int changeY = change.getBlockY(); if (changeY > 0) { minY += changeY; @@ -277,14 +259,14 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { } @Override - public void shift(Vector change) throws RegionOperationException { + public void shift(BlockVector3 change) throws RegionOperationException { final double changeX = change.getX(); final double changeY = change.getY(); final double changeZ = change.getZ(); for (int i = 0; i < points.size(); ++i) { - BlockVector2D point = points.get(i); - points.set(i, new BlockVector2D(point.getX() + changeX, point.getZ() + changeZ)); + BlockVector2 point = points.get(i); + points.set(i, BlockVector2.at(point.getX() + changeX, point.getZ() + changeZ)); } minY += changeY; @@ -341,8 +323,7 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { return inside; } - @Override - public boolean contains(Vector position) { + public boolean contains(BlockVector3 position) { return contains(points, minY, maxY, position); } @@ -355,7 +336,7 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { * @param pt the position to check * @return true if the given polygon contains the given point */ - public static boolean contains(List points, int minY, int maxY, Vector pt) { + public static boolean contains(List points, int minY, int maxY, BlockVector3 pt) { if (points.size() < 3) { return false; } @@ -446,12 +427,12 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { } @Override - public Iterator iterator() { + public Iterator iterator() { return new FlatRegion3DIterator(this); } @Override - public Iterable asFlatRegion() { + public Iterable asFlatRegion() { return () -> new FlatRegionIterator(Polygonal2DRegion.this); } @@ -464,10 +445,10 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { @Override public String toString() { StringBuilder sb = new StringBuilder(); - List pts = getPoints(); - Iterator it = pts.iterator(); + List pts = getPoints(); + Iterator it = pts.iterator(); while (it.hasNext()) { - BlockVector2D current = it.next(); + BlockVector2 current = it.next(); sb.append("(").append(current.getBlockX()).append(", ").append(current.getBlockZ()).append(")"); if (it.hasNext()) sb.append(" - "); } @@ -483,7 +464,7 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion { } @Override - public List polygonize(int maxPoints) { + public List polygonize(int maxPoints) { if (maxPoints >= 0 && maxPoints < points.size()) { throw new IllegalArgumentException("Cannot polygonize a this Polygonal2DRegion into the amount of points given."); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/Region.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/Region.java index d35c0a5e7..96d0bfa63 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/Region.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/Region.java @@ -19,7 +19,9 @@ package com.sk89q.worldedit.regions; -import com.sk89q.worldedit.*; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.world.World; import javax.annotation.Nullable; @@ -29,21 +31,21 @@ import java.util.Set; /** * Represents a physical shape. */ -public interface Region extends Iterable, Cloneable { +public interface Region extends Iterable, Cloneable { /** * Get the lower point of a region. * * @return min. point */ - public Vector getMinimumPoint(); + BlockVector3 getMinimumPoint(); /** * Get the upper point of a region. * * @return max. point */ - public Vector getMaximumPoint(); + BlockVector3 getMaximumPoint(); /** * Get the center point of a region. @@ -52,7 +54,7 @@ public interface Region extends Iterable, Cloneable { * * @return center point */ - public Vector getCenter(); + Vector3 getCenter(); /** * Get the number of blocks in the region. @@ -88,7 +90,7 @@ public interface Region extends Iterable, Cloneable { * @param changes array/arguments with multiple related changes * @throws RegionOperationException */ - public void expand(Vector... changes) throws RegionOperationException; + void expand(BlockVector3... changes) throws RegionOperationException; /** * Contract the region. @@ -96,7 +98,7 @@ public interface Region extends Iterable, Cloneable { * @param changes array/arguments with multiple related changes * @throws RegionOperationException */ - public void contract(Vector... changes) throws RegionOperationException; + void contract(BlockVector3... changes) throws RegionOperationException; /** * Shift the region. @@ -104,43 +106,43 @@ public interface Region extends Iterable, Cloneable { * @param change the change * @throws RegionOperationException */ - public void shift(Vector change) throws RegionOperationException; + void shift(BlockVector3 change) throws RegionOperationException; - /** - * Returns true based on whether the region contains the point. - * - * @param position the position - * @return true if contained - */ - public boolean contains(Vector position); default boolean contains(int x, int y, int z) { - return contains(MutableBlockVector.get(x, y, z)); + return contains(BlockVector3.at(x, y, z)); } default boolean contains(int x, int z) { - return contains(MutableBlockVector.get(x, 0, z)); + return contains(BlockVector3.at(x, 0, z)); } default boolean isGlobal() { - Vector pos1 = getMinimumPoint(); - Vector pos2 = getMaximumPoint(); + BlockVector3 pos1 = getMinimumPoint(); + BlockVector3 pos2 = getMaximumPoint(); return pos1.getBlockX() == Integer.MIN_VALUE && pos1.getBlockZ() == Integer.MIN_VALUE && pos2.getBlockX() == Integer.MAX_VALUE && pos2.getBlockZ() == Integer.MAX_VALUE && pos1.getBlockY() <= 0 && pos2.getBlockY() >= 255; } + /** + * Returns true based on whether the region contains the point. + * + * @param position the position + * @return true if contained + */ + boolean contains(BlockVector3 position); /** * Get a list of chunks. * * @return a list of chunk coordinates */ - public Set getChunks(); + Set getChunks(); /** * Return a list of 16*16*16 chunks in a region * * @return the chunk cubes this region overlaps with */ - public Set getChunkCubes(); + Set getChunkCubes(); /** * Sets the world that the selection is in. @@ -170,5 +172,5 @@ public interface Region extends Iterable, Cloneable { * @param maxPoints maximum number of points to generate. -1 for no limit. * @return the points. */ - public List polygonize(int maxPoints); + List polygonize(int maxPoints); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/RegionIntersection.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/RegionIntersection.java index ad93903ee..9442deaca 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/RegionIntersection.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/RegionIntersection.java @@ -23,8 +23,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.Iterators; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.World; import java.util.ArrayList; @@ -90,37 +89,37 @@ public class RegionIntersection extends AbstractRegion { } @Override - public Vector getMinimumPoint() { - Vector minimum = regions.get(0).getMinimumPoint(); + public BlockVector3 getMinimumPoint() { + BlockVector3 minimum = regions.get(0).getMinimumPoint(); for (int i = 1; i < regions.size(); i++) { - minimum = Vector.getMinimum(regions.get(i).getMinimumPoint(), minimum); + minimum = regions.get(i).getMinimumPoint().getMinimum(minimum); } return minimum; } @Override - public Vector getMaximumPoint() { - Vector maximum = regions.get(0).getMaximumPoint(); + public BlockVector3 getMaximumPoint() { + BlockVector3 maximum = regions.get(0).getMaximumPoint(); for (int i = 1; i < regions.size(); i++) { - maximum = Vector.getMaximum(regions.get(i).getMaximumPoint(), maximum); + maximum = regions.get(i).getMaximumPoint().getMaximum(maximum); } return maximum; } @Override - public void expand(Vector... changes) throws RegionOperationException { + public void expand(BlockVector3... changes) throws RegionOperationException { checkNotNull(changes); throw new RegionOperationException("Cannot expand a region intersection"); } @Override - public void contract(Vector... changes) throws RegionOperationException { + public void contract(BlockVector3... changes) throws RegionOperationException { checkNotNull(changes); throw new RegionOperationException("Cannot contract a region intersection"); } @Override - public boolean contains(Vector position) { + public boolean contains(BlockVector3 position) { checkNotNull(position); for (Region region : regions) { @@ -132,10 +131,10 @@ public class RegionIntersection extends AbstractRegion { return false; } - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({"unchecked"}) @Override - public Iterator iterator() { - Iterator[] iterators = (Iterator[]) new Iterator[regions.size()]; + public Iterator iterator() { + Iterator[] iterators = (Iterator[]) new Iterator[regions.size()]; for (int i = 0; i < regions.size(); i++) { iterators[i] = regions.get(i).iterator(); } 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 247a9e250..051731cdc 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 @@ -19,11 +19,10 @@ package com.sk89q.worldedit.regions; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.selector.limit.SelectorLimits; import com.sk89q.worldedit.world.World; @@ -59,7 +58,7 @@ public interface RegionSelector { * @param position the position * @return true if something changed */ - boolean selectPrimary(Vector position, SelectorLimits limits); + boolean selectPrimary(BlockVector3 position, SelectorLimits limits); /** * Called when the second point is selected. @@ -67,7 +66,7 @@ public interface RegionSelector { * @param position the position * @return true if something changed */ - boolean selectSecondary(Vector position, SelectorLimits limits); + boolean selectSecondary(BlockVector3 position, SelectorLimits limits); /** * Tell the player information about his/her primary selection. @@ -76,7 +75,7 @@ public interface RegionSelector { * @param session the session * @param position position */ - void explainPrimarySelection(Actor actor, LocalSession session, Vector position); + void explainPrimarySelection(Actor actor, LocalSession session, BlockVector3 position); /** * Tell the player information about his/her secondary selection. @@ -85,7 +84,7 @@ public interface RegionSelector { * @param session the session * @param position position */ - void explainSecondarySelection(Actor actor, LocalSession session, Vector position); + void explainSecondarySelection(Actor actor, LocalSession session, BlockVector3 position); /** * The the player information about the region's changes. This may resend @@ -102,7 +101,7 @@ public interface RegionSelector { * @return the primary position * @throws IncompleteRegionException thrown if a region has not been fully defined */ - BlockVector getPrimaryPosition() throws IncompleteRegionException; + BlockVector3 getPrimaryPosition() throws IncompleteRegionException; /** * Get the selection. @@ -162,7 +161,7 @@ public interface RegionSelector { * @return * @throws IncompleteRegionException */ - default List getVerticies() throws IncompleteRegionException { + default List getVerticies() throws IncompleteRegionException { return Collections.singletonList(getPrimaryPosition()); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/TransformRegion.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/TransformRegion.java index 338d5f0e9..911e40b8b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/TransformRegion.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/TransformRegion.java @@ -21,9 +21,9 @@ package com.sk89q.worldedit.regions; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.BlockVector2D; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.transform.Identity; import com.sk89q.worldedit.math.transform.Transform; import com.sk89q.worldedit.world.World; @@ -98,17 +98,17 @@ public class TransformRegion extends AbstractRegion { } @Override - public Vector getMinimumPoint() { - return transform.apply(region.getMinimumPoint()); + public BlockVector3 getMinimumPoint() { + return transform.apply(region.getMinimumPoint().toVector3()).toBlockPoint(); } @Override - public Vector getMaximumPoint() { - return transform.apply(region.getMaximumPoint()); + public BlockVector3 getMaximumPoint() { + return transform.apply(region.getMaximumPoint().toVector3()).toBlockPoint(); } @Override - public Vector getCenter() { + public Vector3 getCenter() { return transform.apply(region.getCenter()); } @@ -133,50 +133,50 @@ public class TransformRegion extends AbstractRegion { } @Override - public void expand(Vector... changes) throws RegionOperationException { + public void expand(BlockVector3... changes) throws RegionOperationException { throw new RegionOperationException("Can't expand a TransformedRegion"); } @Override - public void contract(Vector... changes) throws RegionOperationException { + public void contract(BlockVector3... changes) throws RegionOperationException { throw new RegionOperationException("Can't contract a TransformedRegion"); } @Override - public void shift(Vector change) throws RegionOperationException { + public void shift(BlockVector3 change) throws RegionOperationException { throw new RegionOperationException("Can't change a TransformedRegion"); } @Override - public boolean contains(Vector position) { - return region.contains(transform.inverse().apply(position)); + public boolean contains(BlockVector3 position) { + return region.contains(transform.inverse().apply(position.toVector3()).toBlockPoint()); } @Override - public List polygonize(int maxPoints) { - List origPoints = region.polygonize(maxPoints); - List transformedPoints = new ArrayList<>(); - for (BlockVector2D vector : origPoints) { - transformedPoints.add(transform.apply(vector.toVector(0)).toVector2D().toBlockVector2D()); + public List polygonize(int maxPoints) { + List origPoints = region.polygonize(maxPoints); + List transformedPoints = new ArrayList<>(); + for (BlockVector2 vector : origPoints) { + transformedPoints.add(transform.apply(vector.toVector3(0)).toVector2().toBlockPoint()); } return transformedPoints; } @Override - public Iterator iterator() { - final Iterator it = region.iterator(); + public Iterator iterator() { + final Iterator it = region.iterator(); - return new Iterator() { + return new Iterator() { @Override public boolean hasNext() { return it.hasNext(); } @Override - public BlockVector next() { - BlockVector next = it.next(); + public BlockVector3 next() { + BlockVector3 next = it.next(); if (next != null) { - return transform.apply(next).toBlockVector(); + return transform.apply(next.toVector3()).toBlockPoint(); } else { return null; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/CuboidRegionFactory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/CuboidRegionFactory.java index 2f533f9fe..24be870a0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/CuboidRegionFactory.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/CuboidRegionFactory.java @@ -19,14 +19,14 @@ package com.sk89q.worldedit.regions.factory; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; public class CuboidRegionFactory implements RegionFactory { @Override - public Region createCenteredAt(Vector position, double size) { + public Region createCenteredAt(BlockVector3 position, double size) { return CuboidRegion.fromCenter(position, (int) size); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/CylinderRegionFactory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/CylinderRegionFactory.java index aa2c83cdd..cf55d2fa9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/CylinderRegionFactory.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/CylinderRegionFactory.java @@ -19,8 +19,8 @@ package com.sk89q.worldedit.regions.factory; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector2; import com.sk89q.worldedit.regions.CylinderRegion; import com.sk89q.worldedit.regions.Region; @@ -33,8 +33,8 @@ public class CylinderRegionFactory implements RegionFactory { } @Override - public Region createCenteredAt(Vector position, double size) { - return new CylinderRegion(position, new Vector2D(size, size), position.getBlockY() - (int) (height / 2), position.getBlockY() + (int) (height / 2)); + public Region createCenteredAt(BlockVector3 position, double size) { + return new CylinderRegion(position, Vector2.at(size, size), position.getBlockY() - (int) (height / 2), position.getBlockY() + (int) (height / 2)); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/RegionFactory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/RegionFactory.java index 51cf3bc1f..8294b0c11 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/RegionFactory.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/RegionFactory.java @@ -19,11 +19,11 @@ package com.sk89q.worldedit.regions.factory; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; public interface RegionFactory { - Region createCenteredAt(Vector position, double size); + Region createCenteredAt(BlockVector3 position, double size); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/SphereRegionFactory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/SphereRegionFactory.java index cf0f488f8..f30611b0f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/SphereRegionFactory.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/factory/SphereRegionFactory.java @@ -19,15 +19,16 @@ package com.sk89q.worldedit.regions.factory; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.EllipsoidRegion; import com.sk89q.worldedit.regions.Region; public class SphereRegionFactory implements RegionFactory { @Override - public Region createCenteredAt(Vector position, double size) { - return new EllipsoidRegion(position, new Vector(size, size, size)); + public Region createCenteredAt(BlockVector3 position, double size) { + return new EllipsoidRegion(position, Vector3.at(size, size, size)); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/FlatRegion3DIterator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/FlatRegion3DIterator.java index 8c6628616..0a61610b3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/FlatRegion3DIterator.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/FlatRegion3DIterator.java @@ -21,23 +21,23 @@ package com.sk89q.worldedit.regions.iterator; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.regions.FlatRegion; import java.util.Iterator; import java.util.NoSuchElementException; -public class FlatRegion3DIterator implements Iterator { +public class FlatRegion3DIterator implements Iterator { - private Iterator flatIterator; + private Iterator flatIterator; private int minY; private int maxY; - private Vector2D next2D; + private BlockVector2 next2D; private int nextY; - public FlatRegion3DIterator(FlatRegion region, Iterator flatIterator) { + public FlatRegion3DIterator(FlatRegion region, Iterator flatIterator) { checkNotNull(region); checkNotNull(flatIterator); @@ -63,12 +63,12 @@ public class FlatRegion3DIterator implements Iterator { } @Override - public BlockVector next() { + public BlockVector3 next() { if (!hasNext()) { throw new NoSuchElementException(); } - BlockVector current = new BlockVector(next2D.getBlockX(), nextY, next2D.getBlockZ()); + BlockVector3 current = BlockVector3.at(next2D.getBlockX(), nextY, next2D.getBlockZ()); if (nextY < maxY) { nextY++; } else if (flatIterator.hasNext()) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/FlatRegionIterator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/FlatRegionIterator.java index c798e82a7..1c28566f4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/FlatRegionIterator.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/FlatRegionIterator.java @@ -21,13 +21,13 @@ package com.sk89q.worldedit.regions.iterator; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.regions.Region; import java.util.Iterator; -public class FlatRegionIterator implements Iterator { +public class FlatRegionIterator implements Iterator { private Region region; private int y; @@ -42,8 +42,8 @@ public class FlatRegionIterator implements Iterator { this.region = region; - Vector min = region.getMinimumPoint(); - Vector max = region.getMaximumPoint(); + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); this.y = min.getBlockY(); @@ -64,18 +64,18 @@ public class FlatRegionIterator implements Iterator { } private void forward() { - while (hasNext() && !region.contains(nextX, y, nextZ)) { + while (hasNext() && !region.contains(BlockVector3.at(nextX, y, nextZ))) { forwardOne(); } } @Override - public Vector2D next() { + public BlockVector2 next() { if (!hasNext()) { throw new java.util.NoSuchElementException(); } - Vector2D answer = new Vector2D(nextX, nextZ); + BlockVector2 answer = BlockVector2.at(nextX, nextZ); forwardOne(); forward(); @@ -95,9 +95,4 @@ public class FlatRegionIterator implements Iterator { nextX = Integer.MIN_VALUE; } - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/RegionIterator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/RegionIterator.java index 35700595c..c01dfe213 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/RegionIterator.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/iterator/RegionIterator.java @@ -21,19 +21,18 @@ package com.sk89q.worldedit.regions.iterator; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import java.util.Iterator; -public class RegionIterator implements Iterator { +public class RegionIterator implements Iterator { private final Region region; private final int maxX; private final int maxY; private final int maxZ; - private final Vector min; + private final BlockVector3 min; private int nextX; private int nextY; private int nextZ; @@ -43,7 +42,7 @@ public class RegionIterator implements Iterator { this.region = region; - Vector max = region.getMaximumPoint(); + BlockVector3 max = region.getMaximumPoint(); this.maxX = max.getBlockX(); this.maxY = max.getBlockY(); this.maxZ = max.getBlockZ(); @@ -62,16 +61,16 @@ public class RegionIterator implements Iterator { } private void forward() { - while (hasNext() && !region.contains(new BlockVector(nextX, nextY, nextZ))) { + while (hasNext() && !region.contains(BlockVector3.at(nextX, nextY, nextZ))) { forwardOne(); } } @Override - public BlockVector next() { + public BlockVector3 next() { if (!hasNext()) throw new java.util.NoSuchElementException(); - BlockVector answer = new BlockVector(nextX, nextY, nextZ); + BlockVector3 answer = BlockVector3.at(nextX, nextY, nextZ); forwardOne(); forward(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/polyhedron/Edge.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/polyhedron/Edge.java index 3495fee83..dcf098d3c 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/polyhedron/Edge.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/polyhedron/Edge.java @@ -21,14 +21,14 @@ package com.sk89q.worldedit.regions.polyhedron; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; public class Edge { - private final Vector start; - private final Vector end; + private final Vector3 start; + private final Vector3 end; - public Edge(Vector start, Vector end) { + public Edge(Vector3 start, Vector3 end) { checkNotNull(start); checkNotNull(end); @@ -71,7 +71,7 @@ public class Edge { * @param vertex the 3rd vertex for the triangle * @return a triangle */ - public Triangle createTriangle(Vector vertex) { + public Triangle createTriangle(Vector3 vertex) { checkNotNull(vertex); return new Triangle(this.start, this.end, vertex); } @@ -82,7 +82,7 @@ public class Edge { * @param vertex the second vertex * @return a new triangle */ - public Triangle createTriangle2(Vector vertex) { + public Triangle createTriangle2(Vector3 vertex) { checkNotNull(vertex); return new Triangle(this.start, vertex, this.end); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/polyhedron/Triangle.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/polyhedron/Triangle.java index 01bd7f8ae..5e5f7a770 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/polyhedron/Triangle.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/polyhedron/Triangle.java @@ -21,13 +21,13 @@ package com.sk89q.worldedit.regions.polyhedron; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; public class Triangle { private String tag = "Triangle"; - private final Vector[] vertices; - private final Vector normal; + private final Vector3[] vertices; + private final Vector3 normal; private final double b; /** @@ -37,12 +37,12 @@ public class Triangle { * @param v1 second vertex * @param v2 third vertex */ - public Triangle(Vector v0, Vector v1, Vector v2) { + public Triangle(Vector3 v0, Vector3 v1, Vector3 v2) { checkNotNull(v0); checkNotNull(v1); checkNotNull(v2); - vertices = new Vector[] { v0, v1, v2 }; + vertices = new Vector3[] { v0, v1, v2 }; this.normal = v1.subtract(v0).cross(v2.subtract(v0)).normalize(); this.b = Math.max(Math.max(normal.dot(v0), normal.dot(v1)), normal.dot(v2)); @@ -54,7 +54,7 @@ public class Triangle { * @param index Vertex index. Valid input: 0..2 * @return a vertex */ - public Vector getVertex(int index) { + public Vector3 getVertex(int index) { return vertices[index]; } @@ -77,7 +77,7 @@ public class Triangle { * @param pt the point to test * @return true if the point is below */ - public boolean below(Vector pt) { + public boolean below(Vector3 pt) { checkNotNull(pt); return normal.dot(pt) < b; } @@ -88,7 +88,7 @@ public class Triangle { * @param pt the point to test * @return true if the point is above */ - public boolean above(Vector pt) { + public boolean above(Vector3 pt) { checkNotNull(pt); return normal.dot(pt) > b; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/ConvexPolyhedralRegionSelector.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/ConvexPolyhedralRegionSelector.java index c60313581..92242baa0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/ConvexPolyhedralRegionSelector.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/ConvexPolyhedralRegionSelector.java @@ -20,15 +20,16 @@ package com.sk89q.worldedit.regions.selector; import com.boydti.fawe.config.BBC; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.BlockVector2D; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.internal.cui.CUIRegion; import com.sk89q.worldedit.internal.cui.SelectionPointEvent; import com.sk89q.worldedit.internal.cui.SelectionPolygonEvent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.ConvexPolyhedralRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionSelector; @@ -48,7 +49,7 @@ import static com.google.common.base.Preconditions.checkNotNull; public class ConvexPolyhedralRegionSelector implements RegionSelector, CUIRegion { private final transient ConvexPolyhedralRegion region; - private transient BlockVector pos1; + private transient BlockVector3 pos1; /** * Create a new selector with a {@code null} world. @@ -98,9 +99,9 @@ public class ConvexPolyhedralRegionSelector implements RegionSelector, CUIRegion region = new ConvexPolyhedralRegion(oldRegion.getWorld()); - for (final BlockVector2D pt : new ArrayList(oldRegion.polygonize(Integer.MAX_VALUE))) { - region.addVertex(pt.toVector(minY)); - region.addVertex(pt.toVector(maxY)); + for (final BlockVector2 pt : new ArrayList<>(oldRegion.polygonize(Integer.MAX_VALUE))) { + region.addVertex(pt.toBlockVector3(minY)); + region.addVertex(pt.toBlockVector3(maxY)); } learnChanges(); @@ -108,7 +109,7 @@ public class ConvexPolyhedralRegionSelector implements RegionSelector, CUIRegion } @Override - public List getVerticies() { + public List getVerticies() { return new ArrayList<>(region.getVertices()); } @@ -124,15 +125,15 @@ public class ConvexPolyhedralRegionSelector implements RegionSelector, CUIRegion } @Override - public boolean selectPrimary(Vector position, SelectorLimits limits) { + public boolean selectPrimary(BlockVector3 position, SelectorLimits limits) { checkNotNull(position); clear(); - pos1 = position.toBlockVector(); + pos1 = position; return region.addVertex(position); } @Override - public boolean selectSecondary(Vector position, SelectorLimits limits) { + public boolean selectSecondary(BlockVector3 position, SelectorLimits limits) { checkNotNull(position); Optional vertexLimit = limits.getPolyhedronVertexLimit(); @@ -145,7 +146,7 @@ public class ConvexPolyhedralRegionSelector implements RegionSelector, CUIRegion } @Override - public BlockVector getPrimaryPosition() throws IncompleteRegionException { + public BlockVector3 getPrimaryPosition() throws IncompleteRegionException { return pos1; } @@ -175,7 +176,7 @@ public class ConvexPolyhedralRegionSelector implements RegionSelector, CUIRegion @Override public void learnChanges() { - pos1 = region.getVertices().iterator().next().toBlockVector(); + pos1 = region.getVertices().iterator().next(); } @Override @@ -190,7 +191,7 @@ public class ConvexPolyhedralRegionSelector implements RegionSelector, CUIRegion @Override public List getInformationLines() { - List ret = new ArrayList(); + List ret = new ArrayList<>(); ret.add("Vertices: "+region.getVertices().size()); ret.add("Triangles: "+region.getTriangles().size()); @@ -200,7 +201,7 @@ public class ConvexPolyhedralRegionSelector implements RegionSelector, CUIRegion @Override - public void explainPrimarySelection(Actor player, LocalSession session, Vector pos) { + public void explainPrimarySelection(Actor player, LocalSession session, BlockVector3 pos) { checkNotNull(player); checkNotNull(session); checkNotNull(pos); @@ -211,7 +212,7 @@ public class ConvexPolyhedralRegionSelector implements RegionSelector, CUIRegion } @Override - public void explainSecondarySelection(Actor player, LocalSession session, Vector pos) { + public void explainSecondarySelection(Actor player, LocalSession session, BlockVector3 pos) { checkNotNull(player); checkNotNull(session); checkNotNull(pos); @@ -243,12 +244,12 @@ public class ConvexPolyhedralRegionSelector implements RegionSelector, CUIRegion checkNotNull(player); checkNotNull(session); - Collection vertices = region.getVertices(); + Collection vertices = region.getVertices(); Collection triangles = region.getTriangles(); - Map vertexIds = new HashMap(vertices.size()); + Map vertexIds = new HashMap<>(vertices.size()); int lastVertexId = -1; - for (Vector vertex : vertices) { + for (BlockVector3 vertex : vertices) { vertexIds.put(vertex, ++lastVertexId); session.dispatchCUIEvent(player, new SelectionPointEvent(lastVertexId, vertex, getArea())); } @@ -256,7 +257,7 @@ public class ConvexPolyhedralRegionSelector implements RegionSelector, CUIRegion for (Triangle triangle : triangles) { final int[] v = new int[3]; for (int i = 0; i < 3; ++i) { - v[i] = vertexIds.get(triangle.getVertex(i)); + v[i] = vertexIds.get(triangle.getVertex(i).toBlockPoint()); } session.dispatchCUIEvent(player, new SelectionPolygonEvent(v)); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/CuboidRegionSelector.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/CuboidRegionSelector.java index c595bc335..c98a118c0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/CuboidRegionSelector.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/CuboidRegionSelector.java @@ -22,15 +22,18 @@ package com.sk89q.worldedit.regions.selector; import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.Commands; import com.boydti.fawe.util.chat.Message; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.command.SelectionCommands; +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.IncompleteRegionException; +import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.internal.cui.CUIRegion; import com.sk89q.worldedit.internal.cui.SelectionPointEvent; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionSelector; @@ -49,9 +52,9 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class CuboidRegionSelector implements RegionSelector, CUIRegion { - public transient BlockVector position1; - public transient BlockVector position2; - public transient CuboidRegion region; + protected transient BlockVector3 position1; + protected transient BlockVector3 position2; + protected transient CuboidRegion region; /** * Create a new region selector with a {@code null} world. @@ -66,7 +69,7 @@ public class CuboidRegionSelector implements RegionSelector, CUIRegion { * @param world the world, which may be {@code null} */ public CuboidRegionSelector(@Nullable World world) { - region = new CuboidRegion(world, new Vector(), new Vector()); + region = new CuboidRegion(world, BlockVector3.ZERO, BlockVector3.ZERO); } /** @@ -90,8 +93,8 @@ public class CuboidRegionSelector implements RegionSelector, CUIRegion { return; } - position1 = oldRegion.getMinimumPoint().toBlockVector(); - position2 = oldRegion.getMaximumPoint().toBlockVector(); + position1 = oldRegion.getMinimumPoint(); + position2 = oldRegion.getMaximumPoint(); } region.setPos1(position1); region.setPos2(position2); @@ -104,18 +107,18 @@ public class CuboidRegionSelector implements RegionSelector, CUIRegion { * @param position1 position 1 * @param position2 position 2 */ - public CuboidRegionSelector(@Nullable World world, Vector position1, Vector position2) { + public CuboidRegionSelector(@Nullable World world, BlockVector3 position1, BlockVector3 position2) { this(world); checkNotNull(position1); checkNotNull(position2); - this.position1 = position1.toBlockVector(); - this.position2 = position2.toBlockVector(); + this.position1 = position1; + this.position2 = position2; region.setPos1(position1); region.setPos2(position2); } @Override - public List getVerticies() { + public List getVerticies() { return Arrays.asList(position1, position2); } @@ -131,33 +134,33 @@ public class CuboidRegionSelector implements RegionSelector, CUIRegion { } @Override - public boolean selectPrimary(Vector position, SelectorLimits limits) { + public boolean selectPrimary(BlockVector3 position, SelectorLimits limits) { checkNotNull(position); - if (position1 != null && (position.compareTo(position1) == 0)) { + if (position1 != null && position1.equals(position)) { return false; } - position1 = position.toBlockVector(); + position1 = position; region.setPos1(position1); return true; } @Override - public boolean selectSecondary(Vector position, SelectorLimits limits) { + public boolean selectSecondary(BlockVector3 position, SelectorLimits limits) { checkNotNull(position); - if (position2 != null && (position.compareTo(position2)) == 0) { + if (position2 != null && position2.equals(position)) { return false; } - position2 = position.toBlockVector(); + position2 = position; region.setPos2(position2); return true; } @Override - public void explainPrimarySelection(Actor player, LocalSession session, Vector pos) { + public void explainPrimarySelection(Actor player, LocalSession session, BlockVector3 pos) { checkNotNull(player); checkNotNull(session); checkNotNull(pos); @@ -176,7 +179,7 @@ public class CuboidRegionSelector implements RegionSelector, CUIRegion { } @Override - public void explainSecondarySelection(Actor player, LocalSession session, Vector pos) { + public void explainSecondarySelection(Actor player, LocalSession session, BlockVector3 pos) { checkNotNull(player); checkNotNull(session); checkNotNull(pos); @@ -209,7 +212,7 @@ public class CuboidRegionSelector implements RegionSelector, CUIRegion { } @Override - public BlockVector getPrimaryPosition() throws IncompleteRegionException { + public BlockVector3 getPrimaryPosition() throws IncompleteRegionException { if (position1 == null) { throw new IncompleteRegionException(); } @@ -238,14 +241,16 @@ public class CuboidRegionSelector implements RegionSelector, CUIRegion { @Override public void learnChanges() { - position1 = region.getPos1().toBlockVector(); - position2 = region.getPos2().toBlockVector(); + position1 = region.getPos1(); + position2 = region.getPos2(); } @Override public void clear() { position1 = null; position2 = null; + region.setPos1(BlockVector3.ZERO); + region.setPos2(BlockVector3.ZERO); } @Override @@ -255,7 +260,7 @@ public class CuboidRegionSelector implements RegionSelector, CUIRegion { @Override public List getInformationLines() { - final List lines = new ArrayList(); + final List lines = new ArrayList<>(); if (position1 != null) { lines.add("Position 1: " + position1); @@ -313,4 +318,4 @@ public class CuboidRegionSelector implements RegionSelector, CUIRegion { } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/CylinderRegionSelector.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/CylinderRegionSelector.java index 8c4fef073..afe54c996 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/CylinderRegionSelector.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/CylinderRegionSelector.java @@ -20,16 +20,19 @@ package com.sk89q.worldedit.regions.selector; import com.boydti.fawe.config.BBC; -import com.sk89q.worldedit.BlockVector; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.internal.cui.CUIRegion; import com.sk89q.worldedit.internal.cui.SelectionCylinderEvent; import com.sk89q.worldedit.internal.cui.SelectionMinMaxEvent; import com.sk89q.worldedit.internal.cui.SelectionPointEvent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector2; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.CylinderRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionSelector; @@ -97,12 +100,12 @@ public class CylinderRegionSelector implements RegionSelector, CUIRegion { return; } - Vector pos1 = oldRegion.getMinimumPoint(); - Vector pos2 = oldRegion.getMaximumPoint(); + BlockVector3 pos1 = oldRegion.getMinimumPoint(); + BlockVector3 pos2 = oldRegion.getMaximumPoint(); - Vector center = pos1.add(pos2).divide(2).floor(); - region.setCenter(center.toVector2D()); - region.setRadius(pos2.toVector2D().subtract(center.toVector2D())); + BlockVector3 center = pos1.add(pos2).divide(2).floor(); + region.setCenter(center.toBlockVector2()); + region.setRadius(pos2.toBlockVector2().subtract(center.toBlockVector2()).toVector2()); region.setMaximumY(Math.max(pos1.getBlockY(), pos2.getBlockY())); region.setMinimumY(Math.min(pos1.getBlockY(), pos2.getBlockY())); @@ -118,7 +121,7 @@ public class CylinderRegionSelector implements RegionSelector, CUIRegion { * @param minY the minimum Y * @param maxY the maximum Y */ - public CylinderRegionSelector(@Nullable World world, Vector2D center, Vector2D radius, int minY, int maxY) { + public CylinderRegionSelector(@Nullable World world, BlockVector2 center, Vector2 radius, int minY, int maxY) { this(world); region.setCenter(center); @@ -140,27 +143,27 @@ public class CylinderRegionSelector implements RegionSelector, CUIRegion { } @Override - public boolean selectPrimary(Vector position, SelectorLimits limits) { - if (!region.getCenter().equals(Vector.ZERO) && position.compareTo(region.getCenter()) == 0) { + public boolean selectPrimary(BlockVector3 position, SelectorLimits limits) { + if (!region.getCenter().equals(Vector3.ZERO) && position.equals(region.getCenter().toBlockPoint())) { return false; } region = new CylinderRegion(region.getWorld()); - region.setCenter(position.toVector2D()); + region.setCenter(position.toBlockVector2()); region.setY(position.getBlockY()); return true; } @Override - public boolean selectSecondary(Vector position, SelectorLimits limits) { - Vector center = region.getCenter(); - if ((center.compareTo(Vector.ZERO)) == 0) { + public boolean selectSecondary(BlockVector3 position, SelectorLimits limits) { + Vector3 center = region.getCenter(); + if (center.equals(Vector3.ZERO)) { return true; } - final Vector2D diff = position.subtract(center).toVector2D(); - final Vector2D minRadius = Vector2D.getMaximum(diff, diff.multiply(-1.0)); + final Vector2 diff = position.toVector3().subtract(center).toVector2(); + final Vector2 minRadius = diff.getMaximum(diff.multiply(-1.0)); region.extendRadius(minRadius); region.setY(position.getBlockY()); @@ -169,17 +172,17 @@ public class CylinderRegionSelector implements RegionSelector, CUIRegion { } @Override - public void explainPrimarySelection(Actor player, LocalSession session, Vector pos) { + public void explainPrimarySelection(Actor player, LocalSession session, BlockVector3 pos) { BBC.SELECTOR_CENTER.send(player, pos, 0); session.describeCUI(player); } @Override - public void explainSecondarySelection(Actor player, LocalSession session, Vector pos) { - Vector center = region.getCenter(); + public void explainSecondarySelection(Actor player, LocalSession session, BlockVector3 pos) { + Vector3 center = region.getCenter(); - if (!center.equals(Vector.ZERO)) { + if (!center.equals(BlockVector3.ZERO)) { BBC.SELECTOR_RADIUS.send(player, NUMBER_FORMAT.format(region.getRadius().getX()) + "/" + NUMBER_FORMAT.format(region.getRadius().getZ()), region.getArea()); } else { BBC.SELECTION_WAND.send(player); @@ -195,12 +198,12 @@ public class CylinderRegionSelector implements RegionSelector, CUIRegion { } @Override - public BlockVector getPrimaryPosition() throws IncompleteRegionException { + public BlockVector3 getPrimaryPosition() throws IncompleteRegionException { if (!isDefined()) { throw new IncompleteRegionException(); } - return region.getCenter().toBlockVector(); + return region.getCenter().toBlockPoint(); } @Override @@ -219,7 +222,7 @@ public class CylinderRegionSelector implements RegionSelector, CUIRegion { @Override public boolean isDefined() { - return !region.getRadius().equals(Vector2D.ZERO); + return !region.getRadius().equals(Vector2.ZERO); } @Override @@ -238,12 +241,12 @@ public class CylinderRegionSelector implements RegionSelector, CUIRegion { @Override public List getInformationLines() { - final List lines = new ArrayList(); + final List lines = new ArrayList<>(); - if (!region.getCenter().equals(Vector.ZERO)) { + if (!region.getCenter().equals(Vector3.ZERO)) { lines.add("Center: " + region.getCenter()); } - if (!region.getRadius().equals(Vector2D.ZERO)) { + if (!region.getRadius().equals(Vector2.ZERO)) { lines.add("Radius: " + region.getRadius()); } @@ -257,7 +260,7 @@ public class CylinderRegionSelector implements RegionSelector, CUIRegion { @Override public void describeCUI(LocalSession session, Actor player) { - session.dispatchCUIEvent(player, new SelectionCylinderEvent(region.getCenter(), region.getRadius())); + session.dispatchCUIEvent(player, new SelectionCylinderEvent(region.getCenter().toBlockPoint(), region.getRadius())); session.dispatchCUIEvent(player, new SelectionMinMaxEvent(region.getMinimumY(), region.getMaximumY())); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/EllipsoidRegionSelector.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/EllipsoidRegionSelector.java index b15d3627d..31b7d5077 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/EllipsoidRegionSelector.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/EllipsoidRegionSelector.java @@ -20,14 +20,16 @@ package com.sk89q.worldedit.regions.selector; import com.boydti.fawe.config.BBC; -import com.sk89q.worldedit.BlockVector; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.internal.cui.CUIRegion; import com.sk89q.worldedit.internal.cui.SelectionEllipsoidPointEvent; import com.sk89q.worldedit.internal.cui.SelectionPointEvent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.EllipsoidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionSelector; @@ -61,7 +63,7 @@ public class EllipsoidRegionSelector implements RegionSelector, CUIRegion { * @param world the world, which may be {@code null} */ public EllipsoidRegionSelector(@Nullable World world) { - region = new EllipsoidRegion(world, new Vector(), new Vector()); + region = new EllipsoidRegion(world, BlockVector3.ZERO, Vector3.ZERO); } /** @@ -83,12 +85,12 @@ public class EllipsoidRegionSelector implements RegionSelector, CUIRegion { return; } - BlockVector pos1 = oldRegion.getMinimumPoint().toBlockVector(); - BlockVector pos2 = oldRegion.getMaximumPoint().toBlockVector(); + BlockVector3 pos1 = oldRegion.getMinimumPoint(); + BlockVector3 pos2 = oldRegion.getMaximumPoint(); - Vector center = pos1.add(pos2).divide(2).floor(); + BlockVector3 center = pos1.add(pos2).divide(2).floor(); region.setCenter(center); - region.setRadius(pos2.subtract(center)); + region.setRadius(pos2.subtract(center).toVector3()); } } @@ -99,7 +101,7 @@ public class EllipsoidRegionSelector implements RegionSelector, CUIRegion { * @param center the center * @param radius the radius */ - public EllipsoidRegionSelector(@Nullable World world, Vector center, Vector radius) { + public EllipsoidRegionSelector(@Nullable World world, BlockVector3 center, Vector3 radius) { this(world); region.setCenter(center); @@ -118,39 +120,39 @@ public class EllipsoidRegionSelector implements RegionSelector, CUIRegion { } @Override - public boolean selectPrimary(Vector position, SelectorLimits limits) { - if (position.equals(region.getCenter()) && region.getRadius().lengthSq() == 0) { + public boolean selectPrimary(BlockVector3 position, SelectorLimits limits) { + if (position.equals(region.getCenter().toBlockPoint()) && region.getRadius().lengthSq() == 0) { return false; } - region.setCenter(position.toBlockVector()); - region.setRadius(new Vector()); + region.setCenter(position); + region.setRadius(Vector3.ZERO); started = true; return true; } @Override - public boolean selectSecondary(Vector position, SelectorLimits limits) { + public boolean selectSecondary(BlockVector3 position, SelectorLimits limits) { if (!started) { return false; } - final Vector diff = position.subtract(region.getCenter()); - final Vector minRadius = Vector.getMaximum(diff, diff.multiply(-1.0)); + final Vector3 diff = position.toVector3().subtract(region.getCenter()); + final Vector3 minRadius = diff.getMaximum(diff.multiply(-1.0)); region.extendRadius(minRadius); return true; } @Override - public void explainPrimarySelection(Actor player, LocalSession session, Vector pos) { + public void explainPrimarySelection(Actor player, LocalSession session, BlockVector3 pos) { BBC.SELECTOR_CENTER.send(player, region.getCenter(), region.getArea()); session.describeCUI(player); } @Override - public void explainSecondarySelection(Actor player, LocalSession session, Vector pos) { + public void explainSecondarySelection(Actor player, LocalSession session, BlockVector3 pos) { BBC.SELECTOR_RADIUS.send(player, region.getRadius(), region.getArea()); session.describeCUI(player); @@ -186,8 +188,8 @@ public class EllipsoidRegionSelector implements RegionSelector, CUIRegion { @Override public void clear() { - region.setCenter(new Vector()); - region.setRadius(new Vector()); + region.setCenter(BlockVector3.ZERO); + region.setRadius(Vector3.ZERO); } @Override @@ -197,14 +199,14 @@ public class EllipsoidRegionSelector implements RegionSelector, CUIRegion { @Override public List getInformationLines() { - final List lines = new ArrayList(); + final List lines = new ArrayList<>(); - final Vector center = region.getCenter(); + final Vector3 center = region.getCenter(); if (center.lengthSq() > 0) { lines.add("Center: " + center); } - final Vector radius = region.getRadius(); + final Vector3 radius = region.getRadius(); if (radius.lengthSq() > 0) { lines.add("X/Y/Z radius: " + radius); } @@ -219,8 +221,8 @@ public class EllipsoidRegionSelector implements RegionSelector, CUIRegion { @Override public void describeCUI(LocalSession session, Actor player) { - session.dispatchCUIEvent(player, new SelectionEllipsoidPointEvent(0, region.getCenter())); - session.dispatchCUIEvent(player, new SelectionEllipsoidPointEvent(1, region.getRadius())); + session.dispatchCUIEvent(player, new SelectionEllipsoidPointEvent(0, region.getCenter().toBlockPoint())); + session.dispatchCUIEvent(player, new SelectionEllipsoidPointEvent(1, region.getRadius().toBlockPoint())); } @Override @@ -245,8 +247,8 @@ public class EllipsoidRegionSelector implements RegionSelector, CUIRegion { } @Override - public BlockVector getPrimaryPosition() throws IncompleteRegionException { - return region.getCenter().toBlockVector(); + public BlockVector3 getPrimaryPosition() throws IncompleteRegionException { + return region.getCenter().toBlockPoint(); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/ExtendingCuboidRegionSelector.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/ExtendingCuboidRegionSelector.java index 07f8c258b..79f2fcbba 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/ExtendingCuboidRegionSelector.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/ExtendingCuboidRegionSelector.java @@ -20,10 +20,9 @@ package com.sk89q.worldedit.regions.selector; import com.boydti.fawe.config.BBC; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.regions.selector.limit.SelectorLimits; import com.sk89q.worldedit.world.World; @@ -64,8 +63,8 @@ public class ExtendingCuboidRegionSelector extends CuboidRegionSelector { return; } - position1 = region.getMinimumPoint().toBlockVector(); - position2 = region.getMaximumPoint().toBlockVector(); + position1 = region.getMinimumPoint(); + position2 = region.getMaximumPoint(); region.setPos1(position1); region.setPos2(position2); } @@ -77,28 +76,28 @@ public class ExtendingCuboidRegionSelector extends CuboidRegionSelector { * @param position1 the first position * @param position2 the second position */ - public ExtendingCuboidRegionSelector(@Nullable World world, Vector position1, Vector position2) { + public ExtendingCuboidRegionSelector(@Nullable World world, BlockVector3 position1, BlockVector3 position2) { this(world); - position1 = Vector.getMinimum(position1, position2); - position2 = Vector.getMaximum(position1, position2); + position1 = position1.getMinimum(position2); + position2 = position1.getMaximum(position2); region.setPos1(position1); region.setPos2(position2); } @Override - public boolean selectPrimary(Vector position, SelectorLimits limits) { - if (position1 != null && position2 != null && position.compareTo(position1) == 0 && position.compareTo(position2) == 0) { + public boolean selectPrimary(BlockVector3 position, SelectorLimits limits) { + if (position1 != null && position2 != null && position.equals(position1) && position.equals(position2)) { return false; } - position1 = position2 = position.toBlockVector(); + position1 = position2 = position; region.setPos1(position1); region.setPos2(position2); return true; } @Override - public boolean selectSecondary(Vector position, SelectorLimits limits) { + public boolean selectSecondary(BlockVector3 position, SelectorLimits limits) { if (position1 == null || position2 == null) { return selectPrimary(position, limits); } @@ -115,10 +114,10 @@ public class ExtendingCuboidRegionSelector extends CuboidRegionSelector { double y2 = Math.max(position.getY(), position2.getY()); double z2 = Math.max(position.getZ(), position2.getZ()); - final BlockVector o1 = position1; - final BlockVector o2 = position2; - position1 = new BlockVector(x1, y1, z1); - position2 = new BlockVector(x2, y2, z2); + final BlockVector3 o1 = position1; + final BlockVector3 o2 = position2; + position1 = BlockVector3.at(x1, y1, z1); + position2 = BlockVector3.at(x2, y2, z2); region.setPos1(position1); region.setPos2(position2); @@ -130,14 +129,14 @@ public class ExtendingCuboidRegionSelector extends CuboidRegionSelector { } @Override - public void explainPrimarySelection(Actor player, LocalSession session, Vector pos) { + public void explainPrimarySelection(Actor player, LocalSession session, BlockVector3 pos) { BBC.SELECTOR_POS.send(player, 1, pos, region.getArea()); explainRegionAdjust(player, session); } @Override - public void explainSecondarySelection(Actor player, LocalSession session, Vector pos) { + public void explainSecondarySelection(Actor player, LocalSession session, BlockVector3 pos) { BBC.SELECTOR_EXPANDED.send(player, pos, region.getArea()); explainRegionAdjust(player, session); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/Polygonal2DRegionSelector.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/Polygonal2DRegionSelector.java index 2f22fdcf5..70ac199a2 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/Polygonal2DRegionSelector.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/Polygonal2DRegionSelector.java @@ -20,16 +20,17 @@ package com.sk89q.worldedit.regions.selector; import com.boydti.fawe.config.BBC; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.BlockVector2D; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.internal.cui.CUIRegion; import com.sk89q.worldedit.internal.cui.SelectionMinMaxEvent; import com.sk89q.worldedit.internal.cui.SelectionPoint2DEvent; import com.sk89q.worldedit.internal.cui.SelectionShapeEvent; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Polygonal2DRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionSelector; @@ -48,7 +49,7 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class Polygonal2DRegionSelector implements RegionSelector, CUIRegion { - private transient BlockVector pos1; + private transient BlockVector3 pos1; private transient Polygonal2DRegion region; /** @@ -96,9 +97,9 @@ public class Polygonal2DRegionSelector implements RegionSelector, CUIRegion { final int minY = oldRegion.getMinimumPoint().getBlockY(); final int maxY = oldRegion.getMaximumPoint().getBlockY(); - List points = oldRegion.polygonize(Integer.MAX_VALUE); + List points = oldRegion.polygonize(Integer.MAX_VALUE); - pos1 = points.get(0).toVector(minY).toBlockVector(); + pos1 = points.get(0).toBlockVector3(minY); region = new Polygonal2DRegion(oldRegion.getWorld(), points, minY, maxY); } } @@ -111,11 +112,11 @@ public class Polygonal2DRegionSelector implements RegionSelector, CUIRegion { * @param minY the minimum Y * @param maxY the maximum Y */ - public Polygonal2DRegionSelector(@Nullable World world, List points, int minY, int maxY) { + public Polygonal2DRegionSelector(@Nullable World world, List points, int minY, int maxY) { checkNotNull(points); - final BlockVector2D pos2D = points.get(0); - pos1 = new BlockVector(pos2D.getX(), minY, pos2D.getZ()); + final BlockVector2 pos2D = points.get(0); + pos1 = BlockVector3.at(pos2D.getX(), minY, pos2D.getZ()); region = new Polygonal2DRegion(world, points, minY, maxY); } @@ -131,12 +132,12 @@ public class Polygonal2DRegionSelector implements RegionSelector, CUIRegion { } @Override - public boolean selectPrimary(Vector position, SelectorLimits limits) { + public boolean selectPrimary(BlockVector3 position, SelectorLimits limits) { if (position.equals(pos1)) { return false; } - pos1 = position.toBlockVector(); + pos1 = position; region = new Polygonal2DRegion(region.getWorld()); region.addPoint(position); region.expandY(position.getBlockY()); @@ -145,11 +146,11 @@ public class Polygonal2DRegionSelector implements RegionSelector, CUIRegion { } @Override - public boolean selectSecondary(Vector position, SelectorLimits limits) { + public boolean selectSecondary(BlockVector3 position, SelectorLimits limits) { if (region.size() > 0) { - final List points = region.getPoints(); + final List points = region.getPoints(); - final BlockVector2D lastPoint = points.get(region.size() - 1); + final BlockVector2 lastPoint = points.get(region.size() - 1); if (lastPoint.getBlockX() == position.getBlockX() && lastPoint.getBlockZ() == position.getBlockZ()) { return false; } @@ -168,7 +169,7 @@ public class Polygonal2DRegionSelector implements RegionSelector, CUIRegion { } @Override - public void explainPrimarySelection(Actor player, LocalSession session, Vector pos) { + public void explainPrimarySelection(Actor player, LocalSession session, BlockVector3 pos) { BBC.SELECTOR_POS.send(player, 1, pos, region.getArea()); session.dispatchCUIEvent(player, new SelectionShapeEvent(getTypeID())); @@ -177,7 +178,7 @@ public class Polygonal2DRegionSelector implements RegionSelector, CUIRegion { } @Override - public void explainSecondarySelection(Actor player, LocalSession session, Vector pos) { + public void explainSecondarySelection(Actor player, LocalSession session, BlockVector3 pos) { BBC.SELECTOR_POS.send(player, region.size(), pos, region.getArea()); session.dispatchCUIEvent(player, new SelectionPoint2DEvent(region.size() - 1, pos, getArea())); @@ -191,7 +192,7 @@ public class Polygonal2DRegionSelector implements RegionSelector, CUIRegion { } @Override - public BlockVector getPrimaryPosition() throws IncompleteRegionException { + public BlockVector3 getPrimaryPosition() throws IncompleteRegionException { if (pos1 == null) { throw new IncompleteRegionException(); } @@ -220,8 +221,8 @@ public class Polygonal2DRegionSelector implements RegionSelector, CUIRegion { @Override public void learnChanges() { - BlockVector2D pt = region.getPoints().get(0); - pos1 = new BlockVector(pt.getBlockX(), region.getMinimumPoint().getBlockY(), pt.getBlockZ()); + BlockVector2 pt = region.getPoints().get(0); + pos1 = BlockVector3.at(pt.getBlockX(), region.getMinimumPoint().getBlockY(), pt.getBlockZ()); } @Override @@ -256,7 +257,7 @@ public class Polygonal2DRegionSelector implements RegionSelector, CUIRegion { @Override public void describeCUI(LocalSession session, Actor player) { - final List points = region.getPoints(); + final List points = region.getPoints(); for (int id = 0; id < points.size(); id++) { session.dispatchCUIEvent(player, new SelectionPoint2DEvent(id, points.get(id), getArea())); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/SphereRegionSelector.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/SphereRegionSelector.java index 573e35eb3..ef2a631c7 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/SphereRegionSelector.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/selector/SphereRegionSelector.java @@ -21,8 +21,9 @@ package com.sk89q.worldedit.regions.selector; import com.boydti.fawe.config.BBC; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.regions.selector.limit.SelectorLimits; import com.sk89q.worldedit.world.World; @@ -57,9 +58,9 @@ public class SphereRegionSelector extends EllipsoidRegionSelector { */ public SphereRegionSelector(RegionSelector oldSelector) { super(oldSelector); - final Vector radius = region.getRadius(); + final Vector3 radius = region.getRadius(); final double radiusScalar = Math.max(Math.max(radius.getX(), radius.getY()), radius.getZ()); - region.setRadius(new Vector(radiusScalar, radiusScalar, radiusScalar)); + region.setRadius(Vector3.at(radiusScalar, radiusScalar, radiusScalar)); } /** @@ -69,24 +70,24 @@ public class SphereRegionSelector extends EllipsoidRegionSelector { * @param center the center position * @param radius the radius */ - public SphereRegionSelector(@Nullable World world, Vector center, int radius) { - super(world, center, new Vector(radius, radius, radius)); + public SphereRegionSelector(@Nullable World world, BlockVector3 center, int radius) { + super(world, center, Vector3.at(radius, radius, radius)); } @Override - public boolean selectSecondary(Vector position, SelectorLimits limits) { + public boolean selectSecondary(BlockVector3 position, SelectorLimits limits) { if (!started) { return false; } - final double radiusScalar = Math.ceil(position.distance(region.getCenter())); - region.setRadius(new Vector(radiusScalar, radiusScalar, radiusScalar)); + final double radiusScalar = Math.ceil(position.toVector3().distance(region.getCenter())); + region.setRadius(Vector3.at(radiusScalar, radiusScalar, radiusScalar)); return true; } @Override - public void explainSecondarySelection(Actor player, LocalSession session, Vector pos) { + public void explainSecondarySelection(Actor player, LocalSession session, BlockVector3 pos) { BBC.SELECTOR_RADIUS.send(player, region.getRadius().getX(), region.getArea()); session.describeCUI(player); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/ArbitraryBiomeShape.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/ArbitraryBiomeShape.java index 942b55c6c..0ebdc7393 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/ArbitraryBiomeShape.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/ArbitraryBiomeShape.java @@ -20,7 +20,7 @@ package com.sk89q.worldedit.regions.shape; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.FlatRegion; import com.sk89q.worldedit.regions.Region; @@ -48,8 +48,8 @@ public abstract class ArbitraryBiomeShape { this.extent = new CuboidRegion(extent.getWorld(), extent.getMinimumPoint(), extent.getMaximumPoint()); } - Vector2D min = extent.getMinimumPoint().toVector2D(); - Vector2D max = extent.getMaximumPoint().toVector2D(); + BlockVector2 min = extent.getMinimumPoint().toBlockVector2(); + BlockVector2 max = extent.getMaximumPoint().toBlockVector2(); cacheOffsetX = min.getBlockX() - 1; cacheOffsetZ = min.getBlockZ() - 1; @@ -60,7 +60,7 @@ public abstract class ArbitraryBiomeShape { cache = new BaseBiome[cacheSizeX * cacheSizeZ]; } - protected Iterable getExtent() { + protected Iterable getExtent() { return extent.asFlatRegion(); } @@ -130,7 +130,7 @@ public abstract class ArbitraryBiomeShape { public int generate(EditSession editSession, BaseBiome baseBiome, boolean hollow) { int affected = 0; - for (Vector2D position : getExtent()) { + for (BlockVector2 position : getExtent()) { int x = position.getBlockX(); int z = position.getBlockZ(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/ArbitraryShape.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/ArbitraryShape.java index 7629637d4..142fbb481 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/ArbitraryShape.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/ArbitraryShape.java @@ -19,12 +19,12 @@ package com.sk89q.worldedit.regions.shape; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.function.pattern.Pattern; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BaseBlock; /** * Generates solid and hollow shapes according to materials returned by the @@ -51,7 +51,7 @@ public abstract class ArbitraryShape { * @param defaultMaterial The material returned by the pattern for the current block. * @return material to place or null to not place anything. */ - protected abstract BlockStateHolder getMaterial(int x, int y, int z, BlockStateHolder defaultMaterial); + protected abstract BaseBlock getMaterial(int x, int y, int z, BaseBlock defaultMaterial); /** * Generates the shape. @@ -65,13 +65,13 @@ public abstract class ArbitraryShape { public int generate(EditSession editSession, Pattern pattern, boolean hollow) throws MaxChangedBlocksException { int affected = 0; - for (BlockVector position : getExtent()) { + for (BlockVector3 position : getExtent()) { int x = position.getBlockX(); int y = position.getBlockY(); int z = position.getBlockZ(); if (!hollow) { - final BlockStateHolder material = getMaterial(x, y, z, pattern.apply(position)); + BaseBlock material = getMaterial(x, y, z, pattern.apply(position)); if (material != null && editSession.setBlock(position, material)) { ++affected; } @@ -79,7 +79,7 @@ public abstract class ArbitraryShape { continue; } - final BlockStateHolder material = getMaterial(x, y, z, pattern.apply(position)); + BaseBlock material = getMaterial(x, y, z, pattern.apply(position)); if (material == null) { continue; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/RegionShape.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/RegionShape.java index e8419cf00..b066b1d4b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/RegionShape.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/RegionShape.java @@ -19,9 +19,9 @@ package com.sk89q.worldedit.regions.shape; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BaseBlock; /** * Generates solid and hollow shapes according to materials returned by the @@ -34,8 +34,8 @@ public class RegionShape extends ArbitraryShape { } @Override - protected BlockStateHolder getMaterial(int x, int y, int z, BlockStateHolder defaultMaterial) { - if (!this.extent.contains(new Vector(x, y, z))) { + protected BaseBlock getMaterial(int x, int y, int z, BaseBlock defaultMaterial) { + if (!this.extent.contains(BlockVector3.at(x, y, z))) { return null; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/WorldEditExpressionEnvironment.java b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/WorldEditExpressionEnvironment.java index a889d8d88..ed3d1f6af 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/WorldEditExpressionEnvironment.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/regions/shape/WorldEditExpressionEnvironment.java @@ -19,35 +19,36 @@ package com.sk89q.worldedit.regions.shape; -import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.internal.expression.runtime.ExpressionEnvironment; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.MutableVector3; +import com.sk89q.worldedit.math.Vector3; public class WorldEditExpressionEnvironment implements ExpressionEnvironment { - - private final Vector unit; - private final Vector zero2; - private Vector current = new Vector(); + private final Vector3 unit; + private final Vector3 zero2; + private Vector3 current = new MutableVector3(Vector3.ZERO); + private EditSession editSession; private Extent extent; - public WorldEditExpressionEnvironment(EditSession editSession, Vector unit, Vector zero) { + public WorldEditExpressionEnvironment(EditSession editSession, Vector3 unit, Vector3 zero) { this((Extent) editSession, unit, zero); } - public WorldEditExpressionEnvironment(Extent extent, Vector unit, Vector zero) { + public WorldEditExpressionEnvironment(Extent extent, Vector3 unit, Vector3 zero) { this.extent = extent; this.unit = unit; this.zero2 = zero.add(0.5, 0.5, 0.5); } - public BlockVector toWorld(double x, double y, double z) { + public BlockVector3 toWorld(double x, double y, double z) { // unscale, unoffset, round-nearest - return new Vector(x, y, z).multiply(unit).add(zero2).toBlockPoint(); + return Vector3.at(x, y, z).multiply(unit).add(zero2).toBlockPoint(); } - public Vector toWorldRel(double x, double y, double z) { + public Vector3 toWorldRel(double x, double y, double z) { return current.add(x, y, z); } @@ -81,7 +82,11 @@ public class WorldEditExpressionEnvironment implements ExpressionEnvironment { return extent.getBlock(toWorld(x, y, z)).getBlockType().getLegacyCombinedId() & 0xF; } - public void setCurrentBlock(Vector current) { + public void setCurrentBlock(int x, int y, int z) { + current.setComponents(x, y, z); + } + + public void setCurrentBlock(Vector3 current) { this.current = current; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/AbstractProperty.java b/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/AbstractProperty.java index 509054bbb..3e5060d4f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/AbstractProperty.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/registry/state/AbstractProperty.java @@ -30,11 +30,13 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import static com.google.common.base.Preconditions.checkState; + public class AbstractProperty implements Property { private final PropertyKey key; - private final String name; - private final List values; + private String name; + private List values; private final int bitMask; private final int bitMaskInverse; @@ -75,6 +77,7 @@ public class AbstractProperty implements Property { return bitMask; } + //todo remove the following to allow for upstream compatibility. public > C withOffset(int bitOffset) { return (C) new AbstractProperty<>(name, values, bitOffset); } @@ -116,6 +119,14 @@ public class AbstractProperty implements Property { return this.name; } + /** + * Internal method for name setting post-deserialise. Do not use. + */ + public void setName(final String name) { + checkState(this.name == null, "name already set"); + this.name = name; + } + @Override public String toString() { return getClass().getSimpleName() + "{name=" + name + "}"; @@ -131,6 +142,6 @@ public class AbstractProperty implements Property { if (!(obj instanceof Property)) { return false; } - return getName().equals(((Property) obj).getName()); + return getName().equals(((Property) obj).getName()); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/CommandScriptLoader.java b/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/CommandScriptLoader.java index 9a69fd48c..8aca17dd3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/CommandScriptLoader.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/CommandScriptLoader.java @@ -9,8 +9,9 @@ import com.google.common.base.Charsets; import com.google.common.io.CharStreams; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.command.BrushProcessor; -import com.sk89q.worldedit.extension.factory.DefaultMaskParser; -import com.sk89q.worldedit.extension.factory.HashTagPatternParser; +import com.sk89q.worldedit.extension.factory.parser.mask.DefaultMaskParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.ClipboardPatternParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.DefaultPatternParser; import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.util.command.ProcessedCallable; import com.sk89q.worldedit.util.command.parametric.FunctionParametricCallable; @@ -75,7 +76,7 @@ public class CommandScriptLoader { } return; case "patterns": - parser = FaweAPI.getParser(HashTagPatternParser.class); + parser = FaweAPI.getParser(DefaultPatternParser.class); break; case "masks": parser = FaweAPI.getParser(DefaultMaskParser.class); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/CraftScriptContext.java b/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/CraftScriptContext.java index 515d30016..1307508f5 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/CraftScriptContext.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/scripting/CraftScriptContext.java @@ -29,6 +29,7 @@ import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.util.io.file.FilenameException; +import com.sk89q.worldedit.world.block.BaseBlock; import java.io.File; import java.util.ArrayList; @@ -153,7 +154,7 @@ public class CraftScriptContext extends CraftScriptEnvironment { * @throws UnknownItemException * @throws DisallowedItemException */ - public BlockStateHolder getBlock(String input, boolean allAllowed) throws WorldEditException { + public BaseBlock getBlock(String input, boolean allAllowed) throws WorldEditException { ParserContext context = new ParserContext(); context.setActor(player); context.setWorld(player.getWorld()); @@ -172,7 +173,7 @@ public class CraftScriptContext extends CraftScriptEnvironment { * @throws UnknownItemException * @throws DisallowedItemException */ - public BlockStateHolder getBlock(String id) throws WorldEditException { + public BaseBlock getBlock(String id) throws WorldEditException { return getBlock(id, false); } @@ -201,7 +202,7 @@ public class CraftScriptContext extends CraftScriptEnvironment { * @throws UnknownItemException * @throws DisallowedItemException */ - public Set getBlocks(String list, boolean allBlocksAllowed) throws WorldEditException { + public Set getBlocks(String list, boolean allBlocksAllowed) throws WorldEditException { ParserContext context = new ParserContext(); context.setActor(player); context.setWorld(player.getWorld()); 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 ec1aedefc..17296b717 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 @@ -19,6 +19,8 @@ package com.sk89q.worldedit.session; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; @@ -27,9 +29,6 @@ import com.sk89q.worldedit.math.transform.Transform; import java.util.Collections; import java.util.List; - -import static com.google.common.base.Preconditions.checkNotNull; - /** * Holds the clipboard and the current transform on the clipboard. */ @@ -47,8 +46,6 @@ public class ClipboardHolder { this.clipboard = clipboard; } - protected ClipboardHolder() {} - /** * Get the clipboard. *

diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/session/PasteBuilder.java b/worldedit-core/src/main/java/com/sk89q/worldedit/session/PasteBuilder.java index ee8061800..bfc82f5c6 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/session/PasteBuilder.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/session/PasteBuilder.java @@ -21,7 +21,8 @@ package com.sk89q.worldedit.session; import com.boydti.fawe.util.MaskTraverser; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; +import static com.google.common.base.Preconditions.checkNotNull; + import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; @@ -31,6 +32,7 @@ import com.sk89q.worldedit.function.mask.ExistingBlockMask; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.transform.Transform; @@ -45,7 +47,7 @@ public class PasteBuilder { private final Transform transform; private final Extent targetExtent; - private Vector to = new Vector(); + private BlockVector3 to = BlockVector3.ZERO; private boolean ignoreAirBlocks; private boolean ignoreBiomes; private boolean ignoreEntities; @@ -71,7 +73,7 @@ public class PasteBuilder { * @param to the target location * @return this builder instance */ - public PasteBuilder to(Vector to) { + public PasteBuilder to(BlockVector3 to) { this.to = to; return this; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/session/request/RequestSelection.java b/worldedit-core/src/main/java/com/sk89q/worldedit/session/request/RequestSelection.java index 72ae6ef2b..70d8d2baf 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/session/request/RequestSelection.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/session/request/RequestSelection.java @@ -19,12 +19,11 @@ package com.sk89q.worldedit.session.request; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.BlockVector2D; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.NullRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.RegionOperationException; @@ -64,17 +63,17 @@ public class RequestSelection implements Region { } @Override - public Vector getMinimumPoint() { + public BlockVector3 getMinimumPoint() { return getRegion().getMinimumPoint(); } @Override - public Vector getMaximumPoint() { + public BlockVector3 getMaximumPoint() { return getRegion().getMaximumPoint(); } @Override - public Vector getCenter() { + public Vector3 getCenter() { return getRegion().getCenter(); } @@ -99,32 +98,32 @@ public class RequestSelection implements Region { } @Override - public void expand(Vector... changes) throws RegionOperationException { + public void expand(BlockVector3... changes) throws RegionOperationException { getRegion().expand(changes); } @Override - public void contract(Vector... changes) throws RegionOperationException { + public void contract(BlockVector3... changes) throws RegionOperationException { getRegion().contract(changes); } @Override - public void shift(Vector change) throws RegionOperationException { + public void shift(BlockVector3 change) throws RegionOperationException { getRegion().shift(change); } @Override - public boolean contains(Vector position) { + public boolean contains(BlockVector3 position) { return getRegion().contains(position); } @Override - public Set getChunks() { + public Set getChunks() { return getRegion().getChunks(); } @Override - public Set getChunkCubes() { + public Set getChunkCubes() { return getRegion().getChunkCubes(); } @@ -144,12 +143,12 @@ public class RequestSelection implements Region { } @Override - public List polygonize(int maxPoints) { + public List polygonize(int maxPoints) { return getRegion().polygonize(maxPoints); } @Override - public Iterator iterator() { + public Iterator iterator() { return getRegion().iterator(); } 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 62b551bdd..4363b3c4b 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 @@ -19,48 +19,50 @@ package com.sk89q.worldedit.util; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; import javax.annotation.Nullable; -import java.util.HashMap; /** * A collection of cardinal, ordinal, and secondary-ordinal directions. */ public enum Direction { - NORTH(new Vector(0, 0, -1), Flag.CARDINAL, 3, 1), - EAST(new Vector(1, 0, 0), Flag.CARDINAL, 0, 2), - SOUTH(new Vector(0, 0, 1), Flag.CARDINAL, 1, 3), - WEST(new Vector(-1, 0, 0), Flag.CARDINAL, 2, 0), + NORTH(Vector3.at(0, 0, -1), Flag.CARDINAL, 3, 1), + EAST(Vector3.at(1, 0, 0), Flag.CARDINAL, 0, 2), + SOUTH(Vector3.at(0, 0, 1), Flag.CARDINAL, 1, 3), + WEST(Vector3.at(-1, 0, 0), Flag.CARDINAL, 2, 0), - UP(new Vector(0, 1, 0), Flag.UPRIGHT, -1, -1), - DOWN(new Vector(0, -1, 0), Flag.UPRIGHT, -1, -1), + UP(Vector3.at(0, 1, 0), Flag.UPRIGHT, -1, -1), + DOWN(Vector3.at(0, -1, 0), Flag.UPRIGHT, -1, -1), - NORTHEAST(new Vector(1, 0, -1), Flag.ORDINAL, 7, 8), - NORTHWEST(new Vector(-1, 0, -1), Flag.ORDINAL, 9, 6), - SOUTHEAST(new Vector(1, 0, 1), Flag.ORDINAL, 6, 9), - SOUTHWEST(new Vector(-1, 0, 1), Flag.ORDINAL, 8, 7), + NORTHEAST(Vector3.at(1, 0, -1), Flag.ORDINAL, 7, 8), + NORTHWEST(Vector3.at(-1, 0, -1), Flag.ORDINAL, 9, 6), + SOUTHEAST(Vector3.at(1, 0, 1), Flag.ORDINAL, 6, 9), + SOUTHWEST(Vector3.at(-1, 0, 1), Flag.ORDINAL, 8, 7), - WEST_NORTHWEST(new Vector(-Math.cos(Math.PI / 8), 0, -Math.sin(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 9, 6), - WEST_SOUTHWEST(new Vector(-Math.cos(Math.PI / 8), 0, Math.sin(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 8, 7), - NORTH_NORTHWEST(new Vector(-Math.sin(Math.PI / 8), 0, -Math.cos(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 9, 6), - NORTH_NORTHEAST(new Vector(Math.sin(Math.PI / 8), 0, -Math.cos(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 7, 8), - EAST_NORTHEAST(new Vector(Math.cos(Math.PI / 8), 0, -Math.sin(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 7, 8), - EAST_SOUTHEAST(new Vector(Math.cos(Math.PI / 8), 0, Math.sin(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 6, 9), - SOUTH_SOUTHEAST(new Vector(Math.sin(Math.PI / 8), 0, Math.cos(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 6, 9), - SOUTH_SOUTHWEST(new Vector(-Math.sin(Math.PI / 8), 0, Math.cos(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 8, 7); + WEST_NORTHWEST(Vector3.at(-Math.cos(Math.PI / 8), 0, -Math.sin(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 9, 6), + WEST_SOUTHWEST(Vector3.at(-Math.cos(Math.PI / 8), 0, Math.sin(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 8, 7), + NORTH_NORTHWEST(Vector3.at(-Math.sin(Math.PI / 8), 0, -Math.cos(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 9, 6), + NORTH_NORTHEAST(Vector3.at(Math.sin(Math.PI / 8), 0, -Math.cos(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 7, 8), + EAST_NORTHEAST(Vector3.at(Math.cos(Math.PI / 8), 0, -Math.sin(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 7, 8), + EAST_SOUTHEAST(Vector3.at(Math.cos(Math.PI / 8), 0, Math.sin(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 6, 9), + SOUTH_SOUTHEAST(Vector3.at(Math.sin(Math.PI / 8), 0, Math.cos(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 6, 9), + SOUTH_SOUTHWEST(Vector3.at(-Math.sin(Math.PI / 8), 0, Math.cos(Math.PI / 8)), Flag.SECONDARY_ORDINAL, 8, 7); - private final Vector direction; - private final BlockVector blockVector; + private final Vector3 direction; + private final BlockVector3 blockVector; private final int flags, left, right; - - + private static HashMap map = new HashMap<>(); - public static final Direction[] values = values(); - public static final Direction[] cardinal = new Direction[]{ NORTH, EAST, SOUTH, WEST }; - + static { for (Direction dir : Direction.values()) { map.put(dir.name(), dir); @@ -68,24 +70,24 @@ public enum Direction { } } - private Direction(Vector vector, int flags, int left, int right) { + Direction(Vector3 vector, int flags, int left, int right) { this.direction = vector.normalize(); - this.blockVector = new BlockVector(Math.signum(vector.getX()), Math.signum(vector.getY()), Math.signum(vector.getZ())); + this.blockVector = BlockVector3.at(Math.signum(vector.getX()), Math.signum(vector.getY()), Math.signum(vector.getZ())); this.flags = flags; this.left = left; this.right = right; } - + public static Direction get(CharSequence sequence) { return map.get(sequence); } - + public Direction getLeft() { - return left != -1 ? values[left] : null; + return left != -1 ? values()[left] : null; } public Direction getRight() { - return right != -1 ? values[right] : null; + return right != -1 ? values()[right] : null; } public double getX() { @@ -159,17 +161,17 @@ public enum Direction { * * @return the vector */ - public Vector toVector() { + public Vector3 toVector() { return direction; } - public BlockVector toBlockVector() { - return this.blockVector; - } - - @Override - public String toString() { - return name().toLowerCase(); + /** + * Get the vector. + * + * @return the vector + */ + public BlockVector3 toBlockVector() { + return direction.toBlockPoint(); } /** @@ -180,9 +182,9 @@ public enum Direction { * @return the closest direction, or null if no direction can be returned */ @Nullable - public static Direction findClosest(Vector vector, int flags) { + public static Direction findClosest(Vector3 vector, int flags) { if ((flags & Flag.UPRIGHT) == 0) { - vector = vector.setY(0); + vector = vector.withY(0); } vector = vector.normalize(); @@ -204,7 +206,111 @@ public enum Direction { } /** - * Flags to use with {@link #findClosest(Vector, int)}. + * Gets all directions with the given flags. + * + * @param flags The flags + * @return The directions that fit the flags + */ + public static List valuesOf(int flags) { + List directions = new ArrayList<>(); + for (Direction direction : values()) { + if ((~flags & direction.flags) == 0) { + directions.add(direction); + } + } + + return directions; + } + + /** + * Converts a rotation index into a Direction. + * + *

+ * Rotation indexes are used in BlockStates, such as sign posts. + *

+ * + * @param rotation The rotation index + * @return The direction, if applicable + */ + public static Optional fromRotationIndex(int rotation) { + switch (rotation) { + case 0: + return Optional.of(SOUTH); + case 1: + return Optional.of(SOUTH_SOUTHWEST); + case 2: + return Optional.of(SOUTHWEST); + case 3: + return Optional.of(WEST_SOUTHWEST); + case 4: + return Optional.of(WEST); + case 5: + return Optional.of(WEST_NORTHWEST); + case 6: + return Optional.of(NORTHWEST); + case 7: + return Optional.of(NORTH_NORTHWEST); + case 8: + return Optional.of(NORTH); + case 9: + return Optional.of(NORTH_NORTHEAST); + case 10: + return Optional.of(NORTHEAST); + case 11: + return Optional.of(EAST_NORTHEAST); + case 12: + return Optional.of(EAST); + case 13: + return Optional.of(EAST_SOUTHEAST); + case 14: + return Optional.of(SOUTHEAST); + case 15: + return Optional.of(SOUTH_SOUTHEAST); + } + + return Optional.empty(); + } + + public OptionalInt toRotationIndex() { + switch (this) { + case SOUTH: + return OptionalInt.of(0); + case SOUTH_SOUTHWEST: + return OptionalInt.of(1); + case SOUTHWEST: + return OptionalInt.of(2); + case WEST_SOUTHWEST: + return OptionalInt.of(3); + case WEST: + return OptionalInt.of(4); + case WEST_NORTHWEST: + return OptionalInt.of(5); + case NORTHWEST: + return OptionalInt.of(6); + case NORTH_NORTHWEST: + return OptionalInt.of(7); + case NORTH: + return OptionalInt.of(8); + case NORTH_NORTHEAST: + return OptionalInt.of(9); + case NORTHEAST: + return OptionalInt.of(10); + case EAST_NORTHEAST: + return OptionalInt.of(11); + case EAST: + return OptionalInt.of(12); + case EAST_SOUTHEAST: + return OptionalInt.of(13); + case SOUTHEAST: + return OptionalInt.of(14); + case SOUTH_SOUTHEAST: + return OptionalInt.of(15); + } + return OptionalInt.empty(); + } + + /** + * Flags to use with {@link #findClosest(Vector3, int)}. */ public static final class Flag { public static int CARDINAL = 0x1; @@ -219,4 +325,3 @@ public enum Direction { } } - diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/FileDialogUtil.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/FileDialogUtil.java index b44850ca7..ff3924558 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/FileDialogUtil.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/FileDialogUtil.java @@ -85,7 +85,7 @@ public final class FileDialogUtil { if (index == -1 || index == path.length() - 1) { return false; } else { - return exts.contains(path.indexOf(index + 1)); + return exts.contains(path.substring(index + 1)); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/LocatedBlock.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/LocatedBlock.java new file mode 100644 index 000000000..e2b3235f6 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/LocatedBlock.java @@ -0,0 +1,67 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; + +import java.util.Objects; + +/** + * Represents a block located at some position. + */ +public final class LocatedBlock { + + private final BlockVector3 location; + private final BaseBlock block; + + public LocatedBlock(BlockVector3 location, BaseBlock block) { + this.location = checkNotNull(location); + this.block = checkNotNull(block); + } + + public BlockVector3 getLocation() { + return location; + } + + public BaseBlock getBlock() { + return block; + } + + @Override + public int hashCode() { + return Objects.hash(location, block); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (this.getClass() != obj.getClass()) { + return false; + } + LocatedBlock lb = (LocatedBlock) obj; + return Objects.equals(location, lb.location) && Objects.equals(block, lb.block); + } + +} 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 98814eb4a..35e228b93 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 @@ -19,12 +19,11 @@ package com.sk89q.worldedit.util; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.world.NullWorld; - import static com.google.common.base.Preconditions.checkNotNull; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.Vector3; + /** * Represents a location in a world with has a direction. * @@ -35,7 +34,7 @@ import static com.google.common.base.Preconditions.checkNotNull; * {@link #equals(Object)} are subject to minor differences caused by * floating point errors.

*/ -public class Location extends Vector { +public class Location extends Vector3 { private final Extent extent; private final float pitch; @@ -48,7 +47,7 @@ public class Location extends Vector { * @param extent the extent */ public Location(Extent extent) { - this(extent, new Vector(), new Vector()); + this(extent, Vector3.ZERO, Vector3.ZERO); } /** @@ -61,7 +60,7 @@ public class Location extends Vector { * @param z the Z coordinate */ public Location(Extent extent, double x, double y, double z) { - this(extent, new Vector(x, y, z), new Vector()); + this(extent, Vector3.at(x, y, z), Vector3.ZERO); } /** @@ -71,8 +70,8 @@ public class Location extends Vector { * @param extent the extent * @param position the position vector */ - public Location(Extent extent, Vector position) { - this(extent, position, new Vector()); + public Location(Extent extent, Vector3 position) { + this(extent, position, Vector3.ZERO); } /** @@ -85,8 +84,8 @@ public class Location extends Vector { * @param z the Z coordinate * @param direction the direction vector */ - public Location(Extent extent, double x, double y, double z, Vector direction) { - this(extent, new Vector(x, y, z), direction); + public Location(Extent extent, double x, double y, double z, Vector3 direction) { + this(extent, Vector3.at(x, y, z), direction); } /** @@ -101,7 +100,7 @@ public class Location extends Vector { * @param pitch the pitch, in degrees */ public Location(Extent extent, double x, double y, double z, float yaw, float pitch) { - this(extent, new Vector(x, y, z), yaw, pitch); + this(extent, Vector3.at(x, y, z), yaw, pitch); } /** @@ -112,8 +111,8 @@ public class Location extends Vector { * @param position the position vector * @param direction the direction vector */ - public Location(Extent extent, Vector position, Vector direction) { - this(extent, position, direction.toYaw(), direction.toPitch()); + public Location(Extent extent, Vector3 position, Vector3 direction) { + this(extent, position, (float) direction.toYaw(), (float) direction.toPitch()); } /** @@ -125,9 +124,11 @@ public class Location extends Vector { * @param yaw the yaw, in degrees * @param pitch the pitch, in degrees */ - public Location(Extent extent, Vector position, float yaw, float pitch) { + + public Location(Extent extent, Vector3 position, float yaw, float pitch) { super(position); checkNotNull(extent); + checkNotNull(position); this.extent = extent; this.pitch = pitch; this.yaw = yaw; @@ -206,11 +207,11 @@ public class Location extends Vector { * * @return the direction vector */ - public Vector getDirection() { + public Vector3 getDirection() { double yaw = Math.toRadians(this.getYaw()); double pitch = Math.toRadians(this.getPitch()); double xz = Math.cos(pitch); - return new Vector( + return Vector3.at( -xz * Math.sin(yaw), -Math.sin(pitch), xz * Math.cos(yaw)); @@ -231,16 +232,16 @@ public class Location extends Vector { * @param direction the new direction * @return the new instance */ - public Location setDirection(Vector direction) { - return new Location(extent, this, direction.toYaw(), direction.toPitch()); + public Location setDirection(Vector3 direction) { + return new Location(extent, this, (float) direction.toYaw(), (float) direction.toPitch()); } /** - * Get a {@link Vector} form of this location's position. + * Get a {@link Vector3} form of this location's position. * * @return a vector */ - public Vector toVector() { + public Vector3 toVector() { return this; } @@ -252,19 +253,9 @@ public class Location extends Vector { * @return a new immutable instance */ public Location setX(double x) { - return new Location(extent, super.setX(x), yaw, pitch); + return new Location(extent, this.withX(x), yaw, pitch); } - /** - * Return a copy of this object with the X component of the new object - * set to the given value. - * - * @param x the new value for the X component - * @return a new immutable instance - */ - public Location setX(int x) { - return new Location(extent, super.setX(x), yaw, pitch); - } /** * Return a copy of this object with the Y component of the new object @@ -274,18 +265,7 @@ public class Location extends Vector { * @return a new immutable instance */ public Location setY(double y) { - return new Location(extent, super.setY(y), yaw, pitch); - } - - /** - * Return a copy of this object with the Y component of the new object - * set to the given value. - * - * @param y the new value for the Y component - * @return a new immutable instance - */ - public Location setY(int y) { - return new Location(extent, super.setY(y), yaw, pitch); + return new Location(extent, this.withY(y), yaw, pitch); } /** @@ -296,18 +276,7 @@ public class Location extends Vector { * @return a new immutable instance */ public Location setZ(double z) { - return new Location(extent, super.setZ(z), yaw, pitch); - } - - /** - * Return a copy of this object with the Z component of the new object - * set to the given value. - * - * @param z the new value for the Y component - * @return a new immutable instance - */ - public Location setZ(int z) { - return new Location(extent, super.setZ(z), yaw, pitch); + return new Location(extent, this.withZ(z), yaw, pitch); } /** @@ -316,7 +285,7 @@ public class Location extends Vector { * @param position The new position * @return a new immutable instance */ - public Location setPosition(Vector position) { + public Location setPosition(Vector3 position) { return new Location(extent, position, yaw, pitch); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/PropertiesConfiguration.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/PropertiesConfiguration.java index df235ceb9..18a8cc806 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/PropertiesConfiguration.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/PropertiesConfiguration.java @@ -81,11 +81,9 @@ public class PropertiesConfiguration extends LocalConfiguration { profile = getBool("profile", profile); disallowedBlocks = - new HashSet<>(getStringSet("limits.disallowed-blocks", defaultDisallowedBlocks)) - .stream().map(e -> BlockTypes.parse(e)).collect(Collectors.toSet()); + new HashSet<>(getStringSet("limits.disallowed-blocks", getDefaultDisallowedBlocks())); allowedDataCycleBlocks = - new HashSet<>(getStringSet("limits.allowed-data-cycle-blocks", null)) - .stream().map(e -> BlockTypes.parse(e)).collect(Collectors.toSet()); + new HashSet<>(getStringSet("limits.allowed-data-cycle-blocks", null)); defaultChangeLimit = getInt("default-max-changed-blocks", defaultChangeLimit); maxChangeLimit = getInt("max-changed-blocks", maxChangeLimit); defaultMaxPolygonalPoints = getInt("default-max-polygon-points", defaultMaxPolygonalPoints); @@ -100,14 +98,20 @@ public class PropertiesConfiguration extends LocalConfiguration { logFile = getString("log-file", logFile); logFormat = getString("log-format", logFormat); registerHelp = getBool("register-help", registerHelp); - wandItem = ItemTypes.parse(getString("wand-item", wandItem.getId())); + wandItem = getString("wand-item", wandItem); + try { + wandItem = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(wandItem)).getId(); + } catch (Throwable e) {} superPickaxeDrop = getBool("super-pickaxe-drop-items", superPickaxeDrop); superPickaxeManyDrop = getBool("super-pickaxe-many-drop-items", superPickaxeManyDrop); noDoubleSlash = getBool("no-double-slash", noDoubleSlash); useInventory = getBool("use-inventory", useInventory); useInventoryOverride = getBool("use-inventory-override", useInventoryOverride); useInventoryCreativeOverride = getBool("use-inventory-creative-override", useInventoryCreativeOverride); - navigationWand = ItemTypes.parse(getString("navigation-wand.item", navigationWand.getId())); + navigationWand = getString("nav-wand-item", navigationWand); + try { + navigationWand = LegacyMapper.getInstance().getItemFromLegacy(Integer.parseInt(navigationWand)).getId(); + } catch (Throwable e) {} navigationWandMaxDistance = getInt("nav-wand-distance", navigationWandMaxDistance); navigationUseGlass = getBool("nav-use-glass", navigationUseGlass); scriptTimeout = getInt("scripting-timeout", scriptTimeout); @@ -276,4 +280,4 @@ public class PropertiesConfiguration extends LocalConfiguration { } } -} +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/TargetBlock.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/TargetBlock.java index 2ac640d5d..3de20a41e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/TargetBlock.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/TargetBlock.java @@ -19,8 +19,9 @@ package com.sk89q.worldedit.util; -import com.sk89q.worldedit.*; import com.sk89q.worldedit.entity.Player; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.world.World; /** @@ -35,10 +36,10 @@ public class TargetBlock { private World world; private int maxDistance; private double checkDistance, curDistance; - private Vector targetPos = new Vector(); - private Vector targetPosDouble = new Vector(); - private Vector prevPos = new Vector(); - private Vector offset = new Vector(); + private BlockVector3 targetPos = BlockVector3.ZERO; + private Vector3 targetPosDouble = Vector3.ZERO; + private BlockVector3 prevPos = BlockVector3.ZERO; + private Vector3 offset = Vector3.ZERO; /** * Constructor requiring a player, uses default values @@ -47,7 +48,7 @@ public class TargetBlock { */ public TargetBlock(Player player) { this.world = player.getWorld(); - this.setValues(player.getLocation().toVector(), player.getLocation().getYaw(), player.getLocation().getPitch(), 300, 1.65, 0.2); + this.setValues(player.getLocation(), player.getLocation().getYaw(), player.getLocation().getPitch(), 300, 1.65, 0.2); } /** @@ -59,7 +60,7 @@ public class TargetBlock { */ public TargetBlock(Player player, int maxDistance, double checkDistance) { this.world = player.getWorld(); - this.setValues(player.getLocation().toVector(), player.getLocation().getYaw(), player.getLocation().getPitch(), maxDistance, 1.65, checkDistance); + this.setValues(player.getLocation(), player.getLocation().getYaw(), player.getLocation().getPitch(), maxDistance, 1.65, checkDistance); } /** @@ -72,8 +73,7 @@ public class TargetBlock { * @param viewHeight where the view is positioned in y-axis * @param checkDistance how often to check for blocks, the smaller the more precise */ - private void setValues(Vector loc, double xRotation, double yRotation, - int maxDistance, double viewHeight, double checkDistance) { + private void setValues(Vector3 loc, double xRotation, double yRotation, int maxDistance, double viewHeight, double checkDistance) { this.maxDistance = maxDistance; this.checkDistance = checkDistance; this.curDistance = 0; @@ -82,9 +82,9 @@ public class TargetBlock { double h = (checkDistance * Math.cos(Math.toRadians(yRotation))); - offset = new Vector((h * Math.cos(Math.toRadians(xRotation))), - (checkDistance * Math.sin(Math.toRadians(yRotation))), - (h * Math.sin(Math.toRadians(xRotation)))); + offset = Vector3.at((h * Math.cos(Math.toRadians(xRotation))), + (checkDistance * Math.sin(Math.toRadians(yRotation))), + (h * Math.sin(Math.toRadians(xRotation)))); targetPosDouble = loc.add(0, viewHeight, 0); targetPos = targetPosDouble.toBlockPoint(); @@ -101,7 +101,7 @@ public class TargetBlock { boolean searchForLastBlock = true; Location lastBlock = null; while (getNextBlock() != null) { - if (world.getBlockType(getCurrentBlock().toVector()).getMaterial().isAir()) { + if (world.getBlock(targetPos).getBlockType().getMaterial().isAir()) { if (searchForLastBlock) { lastBlock = getCurrentBlock(); if (lastBlock.getBlockY() <= 0 || lastBlock.getBlockY() >= world.getMaxY()) { @@ -123,7 +123,7 @@ public class TargetBlock { * @return Block */ public Location getTargetBlock() { - while (getNextBlock() != null && world.getBlockType(getCurrentBlock().toVector()).getMaterial().isAir()) ; + while (getNextBlock() != null && world.getBlock(targetPos).getBlockType().getMaterial().isAir()) ; return getCurrentBlock(); } @@ -134,7 +134,7 @@ public class TargetBlock { * @return Block */ public Location getSolidTargetBlock() { - while (getNextBlock() != null && !world.getBlockType(getCurrentBlock().toVector()).getMaterial().isMovementBlocker()) ; + while (getNextBlock() != null && !world.getBlock(targetPos).getBlockType().getMaterial().isMovementBlocker()) ; return getCurrentBlock(); } @@ -161,7 +161,7 @@ public class TargetBlock { return null; } - return new Location(world, targetPos); + return new Location(world, targetPos.toVector3()); } /** @@ -173,7 +173,7 @@ public class TargetBlock { if (curDistance > maxDistance) { return null; } else { - return new Location(world, targetPos); + return new Location(world, targetPos.toVector3()); } } @@ -183,17 +183,17 @@ public class TargetBlock { * @return block position */ public Location getPreviousBlock() { - return new Location(world, prevPos); + return new Location(world, prevPos.toVector3()); } public Location getAnyTargetBlockFace() { getAnyTargetBlock(); - return getCurrentBlock().setDirection(getCurrentBlock().toVector().subtract(getPreviousBlock().toVector())); + return getCurrentBlock().setDirection(getCurrentBlock().subtract(getPreviousBlock())); } public Location getTargetBlockFace() { getAnyTargetBlock(); - return getCurrentBlock().setDirection(getCurrentBlock().toVector().subtract(getPreviousBlock().toVector())); + return getCurrentBlock().setDirection(getCurrentBlock().subtract(getPreviousBlock())); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/TreeGenerator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/TreeGenerator.java index 13988a89a..0faf766e8 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/TreeGenerator.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/TreeGenerator.java @@ -22,7 +22,7 @@ package com.sk89q.worldedit.util; import com.google.common.collect.Sets; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; @@ -49,7 +49,7 @@ public class TreeGenerator { MEGA_REDWOOD("Large spruce tree", "largespruce", "megaredwood"), RANDOM_REDWOOD("Random spruce tree", "randspruce", "randredwood", "randomredwood", "anyredwood") { @Override - public boolean generate(EditSession editSession, Vector pos) throws MaxChangedBlocksException { + public boolean generate(EditSession editSession, BlockVector3 pos) throws MaxChangedBlocksException { TreeType[] choices = { REDWOOD, TALL_REDWOOD, MEGA_REDWOOD }; return choices[TreeGenerator.RANDOM.nextInt(choices.length)].generate(editSession, pos); } @@ -58,7 +58,7 @@ public class TreeGenerator { TALL_BIRCH("Tall birch tree", "tallbirch"), RANDOM_BIRCH("Random birch tree", "randbirch", "randombirch") { @Override - public boolean generate(EditSession editSession, Vector pos) throws MaxChangedBlocksException { + public boolean generate(EditSession editSession, BlockVector3 pos) throws MaxChangedBlocksException { TreeType[] choices = { BIRCH, TALL_BIRCH }; return choices[TreeGenerator.RANDOM.nextInt(choices.length)].generate(editSession, pos); } @@ -67,13 +67,13 @@ public class TreeGenerator { SMALL_JUNGLE("Small jungle tree", "shortjungle", "smalljungle"), SHORT_JUNGLE("Short jungle tree") { @Override - public boolean generate(EditSession editSession, Vector pos) throws MaxChangedBlocksException { + public boolean generate(EditSession editSession, BlockVector3 pos) throws MaxChangedBlocksException { return SMALL_JUNGLE.generate(editSession, pos); } }, RANDOM_JUNGLE("Random jungle tree", "randjungle", "randomjungle") { @Override - public boolean generate(EditSession editSession, Vector pos) throws MaxChangedBlocksException { + public boolean generate(EditSession editSession, BlockVector3 pos) throws MaxChangedBlocksException { TreeType[] choices = { JUNGLE, SMALL_JUNGLE }; return choices[TreeGenerator.RANDOM.nextInt(choices.length)].generate(editSession, pos); } @@ -83,7 +83,7 @@ public class TreeGenerator { BROWN_MUSHROOM("Brown mushroom", "brownmushroom", "browngiantmushroom"), RANDOM_MUSHROOM("Random mushroom", "randmushroom", "randommushroom") { @Override - public boolean generate(EditSession editSession, Vector pos) throws MaxChangedBlocksException { + public boolean generate(EditSession editSession, BlockVector3 pos) throws MaxChangedBlocksException { TreeType[] choices = { RED_MUSHROOM, BROWN_MUSHROOM }; return choices[TreeGenerator.RANDOM.nextInt(choices.length)].generate(editSession, pos); } @@ -93,14 +93,14 @@ public class TreeGenerator { DARK_OAK("Dark oak tree", "darkoak"), PINE("Pine tree", "pine") { @Override - public boolean generate(EditSession editSession, Vector pos) throws MaxChangedBlocksException { + public boolean generate(EditSession editSession, BlockVector3 pos) throws MaxChangedBlocksException { makePineTree(editSession, pos); return true; } }, RANDOM("Random tree", "rand", "random") { @Override - public boolean generate(EditSession editSession, Vector pos) throws MaxChangedBlocksException { + public boolean generate(EditSession editSession, BlockVector3 pos) throws MaxChangedBlocksException { TreeType[] choices = TreeType.values(); return choices[TreeGenerator.RANDOM.nextInt(choices.length)].generate(editSession, pos); } @@ -139,7 +139,7 @@ public class TreeGenerator { return Collections.unmodifiableSet(primaryAliases); } - public boolean generate(EditSession editSession, Vector pos) throws MaxChangedBlocksException { + public boolean generate(EditSession editSession, BlockVector3 pos) throws MaxChangedBlocksException { return editSession.getWorld().generateTree(this, editSession, pos); } @@ -174,7 +174,7 @@ public class TreeGenerator { * * @param basePosition the base position */ - private static void makePineTree(EditSession editSession, Vector basePosition) + private static void makePineTree(EditSession editSession, BlockVector3 basePosition) throws MaxChangedBlocksException { int trunkHeight = (int) Math.floor(Math.random() * 2) + 3; int height = (int) Math.floor(Math.random() * 5) + 8; @@ -250,7 +250,7 @@ public class TreeGenerator { * @return whether a block was changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - private static boolean setChanceBlockIfAir(EditSession session, Vector position, BlockStateHolder block, double probability) + private static > boolean setChanceBlockIfAir(EditSession session, BlockVector3 position, B block, double probability) throws MaxChangedBlocksException { return Math.random() <= probability && setBlockIfAir(session, position, block); } @@ -263,7 +263,7 @@ public class TreeGenerator { * @return if block was changed * @throws MaxChangedBlocksException thrown if too many blocks are changed */ - private static boolean setBlockIfAir(EditSession session, Vector position, BlockStateHolder block) throws MaxChangedBlocksException { + private static > boolean setBlockIfAir(EditSession session, BlockVector3 position, B block) throws MaxChangedBlocksException { return session.getBlock(position).getBlockType().getMaterial().isAir() && session.setBlock(position, block); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/YAMLConfiguration.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/YAMLConfiguration.java index fc7b0c860..fba4fc67e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/YAMLConfiguration.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/YAMLConfiguration.java @@ -1,136 +1,131 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit.util; - -import com.google.common.collect.Lists; -import com.sk89q.util.yaml.YAMLProcessor; -import com.sk89q.worldedit.LocalConfiguration; -import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.session.SessionManager; -import com.sk89q.worldedit.world.block.BlockTypes; -import com.sk89q.worldedit.world.item.ItemTypes; -import com.sk89q.worldedit.world.snapshot.SnapshotRepository; - -import java.io.IOException; -import java.util.HashSet; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.Collectors; - -/** - * A less simple implementation of {@link LocalConfiguration} - * using YAML configuration files. - */ -public class YAMLConfiguration extends LocalConfiguration { - - protected final YAMLProcessor config; - protected final Logger logger; - - public YAMLConfiguration(YAMLProcessor config, Logger logger) { - this.config = config; - this.logger = logger; - } - - @Override - public void load() { - try { - config.load(); - } catch (Throwable e) { - logger.log(Level.WARNING, "Error loading WorldEdit configuration", e); - } - - profile = config.getBoolean("debug", profile); - wandItem = ItemTypes.parse(config.getString("wand-item", wandItem.getId())); - - defaultChangeLimit = Math.max(-1, config.getInt( - "limits.max-blocks-changed.default", defaultChangeLimit)); - maxChangeLimit = Math.max(-1, - config.getInt("limits.max-blocks-changed.maximum", maxChangeLimit)); - - defaultMaxPolygonalPoints = Math.max(-1, - config.getInt("limits.max-polygonal-points.default", defaultMaxPolygonalPoints)); - maxPolygonalPoints = Math.max(-1, - config.getInt("limits.max-polygonal-points.maximum", maxPolygonalPoints)); - - defaultMaxPolyhedronPoints = Math.max(-1, config.getInt("limits.max-polyhedron-points.default", defaultMaxPolyhedronPoints)); - maxPolyhedronPoints = Math.max(-1, config.getInt("limits.max-polyhedron-points.maximum", maxPolyhedronPoints)); - - maxRadius = Math.max(-1, config.getInt("limits.max-radius", maxRadius)); - maxBrushRadius = config.getInt("limits.max-brush-radius", maxBrushRadius); - maxSuperPickaxeSize = Math.max(1, config.getInt( - "limits.max-super-pickaxe-size", maxSuperPickaxeSize)); - - butcherDefaultRadius = Math.max(-1, config.getInt("limits.butcher-radius.default", butcherDefaultRadius)); - butcherMaxRadius = Math.max(-1, config.getInt("limits.butcher-radius.maximum", butcherMaxRadius)); - - disallowedBlocks = - new HashSet<>(config.getStringList("limits.disallowed-blocks", Lists.newArrayList(defaultDisallowedBlocks))) - .stream().map(e -> BlockTypes.parse(e)).collect(Collectors.toSet()); - allowedDataCycleBlocks = - new HashSet<>(config.getStringList("limits.allowed-data-cycle-blocks", null)) - .stream().map(e -> BlockTypes.parse(e)).collect(Collectors.toSet()); - - registerHelp = config.getBoolean("register-help", true); - logCommands = config.getBoolean("logging.log-commands", logCommands); - logFile = config.getString("logging.file", logFile); - logFormat = config.getString("logging.format", logFormat); - - superPickaxeDrop = config.getBoolean("super-pickaxe.drop-items", - superPickaxeDrop); - superPickaxeManyDrop = config.getBoolean( - "super-pickaxe.many-drop-items", superPickaxeManyDrop); - - noDoubleSlash = config.getBoolean("no-double-slash", noDoubleSlash); - - useInventory = config.getBoolean("use-inventory.enable", useInventory); - useInventoryOverride = config.getBoolean("use-inventory.allow-override", - useInventoryOverride); - useInventoryCreativeOverride = config.getBoolean("use-inventory.creative-mode-overrides", - useInventoryCreativeOverride); - - navigationWand = ItemTypes.parse(config.getString("navigation-wand.item", navigationWand.getId())); - navigationWandMaxDistance = config.getInt("navigation-wand.max-distance", navigationWandMaxDistance); - navigationUseGlass = config.getBoolean("navigation.use-glass", navigationUseGlass); - - scriptTimeout = config.getInt("scripting.timeout", scriptTimeout); - scriptsDir = config.getString("scripting.dir", scriptsDir); - - saveDir = config.getString("saving.dir", saveDir); - - allowSymlinks = config.getBoolean("files.allow-symbolic-links", false); - LocalSession.MAX_HISTORY_SIZE = Math.max(0, config.getInt("history.size", 15)); - SessionManager.EXPIRATION_GRACE = config.getInt("history.expiration", 10) * 60 * 1000; - - showHelpInfo = config.getBoolean("show-help-on-first-use", true); - - String snapshotsDir = config.getString("snapshots.directory", ""); - if (!snapshotsDir.isEmpty()) { - snapshotRepo = new SnapshotRepository(snapshotsDir); - } - - String type = config.getString("shell-save-type", "").trim(); - shellSaveType = type.isEmpty() ? null : type; - - } - - public void unload() { - } - -} +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util; + +import com.google.common.collect.Lists; +import com.sk89q.util.yaml.YAMLProcessor; +import com.sk89q.worldedit.LocalConfiguration; +import com.sk89q.worldedit.LocalSession; +import com.sk89q.worldedit.session.SessionManager; +import com.sk89q.worldedit.util.report.Unreported; +import com.sk89q.worldedit.world.snapshot.SnapshotRepository; + +import java.io.IOException; +import java.util.HashSet; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * A less simple implementation of {@link LocalConfiguration} + * using YAML configuration files. + */ +public class YAMLConfiguration extends LocalConfiguration { + + @Unreported protected final YAMLProcessor config; + @Unreported protected final Logger logger; + + public YAMLConfiguration(YAMLProcessor config, Logger logger) { + this.config = config; + this.logger = logger; + } + + @Override + public void load() { + try { + config.load(); + } catch (IOException e) { + logger.log(Level.WARNING, "Error loading WorldEdit configuration", e); + } + + profile = config.getBoolean("debug", profile); + wandItem = convertLegacyItem(config.getString("wand-item", wandItem)); + + defaultChangeLimit = Math.max(-1, config.getInt( + "limits.max-blocks-changed.default", defaultChangeLimit)); + maxChangeLimit = Math.max(-1, + config.getInt("limits.max-blocks-changed.maximum", maxChangeLimit)); + + defaultMaxPolygonalPoints = Math.max(-1, + config.getInt("limits.max-polygonal-points.default", defaultMaxPolygonalPoints)); + maxPolygonalPoints = Math.max(-1, + config.getInt("limits.max-polygonal-points.maximum", maxPolygonalPoints)); + + defaultMaxPolyhedronPoints = Math.max(-1, config.getInt("limits.max-polyhedron-points.default", defaultMaxPolyhedronPoints)); + maxPolyhedronPoints = Math.max(-1, config.getInt("limits.max-polyhedron-points.maximum", maxPolyhedronPoints)); + + maxRadius = Math.max(-1, config.getInt("limits.max-radius", maxRadius)); + maxBrushRadius = config.getInt("limits.max-brush-radius", maxBrushRadius); + maxSuperPickaxeSize = Math.max(1, config.getInt( + "limits.max-super-pickaxe-size", maxSuperPickaxeSize)); + + butcherDefaultRadius = Math.max(-1, config.getInt("limits.butcher-radius.default", butcherDefaultRadius)); + butcherMaxRadius = Math.max(-1, config.getInt("limits.butcher-radius.maximum", butcherMaxRadius)); + + disallowedBlocks = new HashSet<>(config.getStringList("limits.disallowed-blocks", Lists.newArrayList(getDefaultDisallowedBlocks()))); + allowedDataCycleBlocks = + new HashSet<>(config.getStringList("limits.allowed-data-cycle-blocks", null)); + + registerHelp = config.getBoolean("register-help", true); + logCommands = config.getBoolean("logging.log-commands", logCommands); + logFile = config.getString("logging.file", logFile); + logFormat = config.getString("logging.format", logFormat); + + superPickaxeDrop = config.getBoolean("super-pickaxe.drop-items", + superPickaxeDrop); + superPickaxeManyDrop = config.getBoolean( + "super-pickaxe.many-drop-items", superPickaxeManyDrop); + + noDoubleSlash = config.getBoolean("no-double-slash", noDoubleSlash); + + useInventory = config.getBoolean("use-inventory.enable", useInventory); + useInventoryOverride = config.getBoolean("use-inventory.allow-override", + useInventoryOverride); + useInventoryCreativeOverride = config.getBoolean("use-inventory.creative-mode-overrides", + useInventoryCreativeOverride); + + navigationWand = convertLegacyItem(config.getString("navigation-wand.item", navigationWand)); + navigationWandMaxDistance = config.getInt("navigation-wand.max-distance", navigationWandMaxDistance); + navigationUseGlass = config.getBoolean("navigation.use-glass", navigationUseGlass); + + scriptTimeout = config.getInt("scripting.timeout", scriptTimeout); + scriptsDir = config.getString("scripting.dir", scriptsDir); + + saveDir = config.getString("saving.dir", saveDir); + + allowSymlinks = config.getBoolean("files.allow-symbolic-links", false); + LocalSession.MAX_HISTORY_SIZE = Math.max(0, config.getInt("history.size", 15)); + SessionManager.EXPIRATION_GRACE = config.getInt("history.expiration", 10) * 60 * 1000; + + showHelpInfo = config.getBoolean("show-help-on-first-use", true); + + String snapshotsDir = config.getString("snapshots.directory", ""); + if (!snapshotsDir.isEmpty()) { + snapshotRepo = new SnapshotRepository(snapshotsDir); + } + + String type = config.getString("shell-save-type", "").trim(); + shellSaveType = type.isEmpty() ? null : type; + + } + + public void unload() { + } + +} 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 new file mode 100644 index 000000000..67280031d --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/collection/LocatedBlockList.java @@ -0,0 +1,88 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.collection; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.util.LocatedBlock; +import com.sk89q.worldedit.world.block.BlockStateHolder; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +/** + * Wrapper around a list of blocks located in the world. + */ +public class LocatedBlockList implements Iterable { + + private final List list; + + public LocatedBlockList() { + list = new ArrayList<>(); + } + + public LocatedBlockList(Collection collection) { + list = new ArrayList<>(collection); + } + + public void add(LocatedBlock setBlockCall) { + checkNotNull(setBlockCall); + list.add(setBlockCall); + } + + public > void add(BlockVector3 location, B block) { + add(new LocatedBlock(location, block.toBaseBlock())); + } + + public int size() { + return list.size(); + } + + public void clear() { + list.clear(); + } + + @Override + public Iterator iterator() { + return list.iterator(); + } + + public Iterator reverseIterator() { + return new Iterator() { + + private final ListIterator backingIterator = list.listIterator(list.size()); + + @Override + public boolean hasNext() { + return backingIterator.hasPrevious(); + } + + @Override + public LocatedBlock next() { + return backingIterator.previous(); + } + }; + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/SimpleDispatcher.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/SimpleDispatcher.java index 421602563..ee89574d9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/SimpleDispatcher.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/SimpleDispatcher.java @@ -40,7 +40,7 @@ import java.util.Set; */ public class SimpleDispatcher implements Dispatcher { - private final Map commands = new HashMap(); + private final Map commands = new HashMap<>(); private final SimpleDescription description = new SimpleDescription(); /** @@ -82,7 +82,7 @@ public class SimpleDispatcher implements Dispatcher { @Override public Set getCommands() { - return Collections.unmodifiableSet(new HashSet(commands.values())); + return Collections.unmodifiableSet(new HashSet<>(commands.values())); } @Override @@ -92,7 +92,7 @@ public class SimpleDispatcher implements Dispatcher { @Override public Set getPrimaryAliases() { - Set aliases = new HashSet(); + Set aliases = new HashSet<>(); for (CommandMapping mapping : getCommands()) { aliases.add(mapping.getPrimaryAlias()); } @@ -151,7 +151,7 @@ public class SimpleDispatcher implements Dispatcher { if (split.length <= 1) { String prefix = split.length > 0 ? split[0] : ""; - List suggestions = new ArrayList(); + List suggestions = new ArrayList<>(); for (CommandMapping mapping : getCommands()) { if (mapping.getCallable().testPermission(locals)) { @@ -188,4 +188,4 @@ public class SimpleDispatcher implements Dispatcher { // Checking every perm in the class here was unnecessarily stupid return true; } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/binding/PrimitiveBindings.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/binding/PrimitiveBindings.java index 3a4d78edf..9085cf186 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/binding/PrimitiveBindings.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/binding/PrimitiveBindings.java @@ -32,12 +32,14 @@ import java.lang.annotation.Annotation; import javax.annotation.Nullable; +import static com.sk89q.worldedit.util.command.parametric.BindingHelper.validate; + /** * Handles basic Java types such as {@link String}s, {@link Byte}s, etc. * *

Handles both the object and primitive types.

*/ -public final class PrimitiveBindings extends BindingHelper { +public final class PrimitiveBindings { /** * Gets a type from a {@link ArgumentStack}. @@ -206,89 +208,4 @@ public final class PrimitiveBindings extends BindingHelper { } return null; } - - /** - * Validate a number value using relevant modifiers. - * - * @param number the number - * @param modifiers the list of modifiers to scan - * @throws ParameterException on a validation error - */ - private static void validate(double number, Annotation[] modifiers) - throws ParameterException { - for (Annotation modifier : modifiers) { - if (modifier instanceof Range) { - Range range = (Range) modifier; - if (number < range.min()) { - throw new ParameterException( - String.format( - "A valid value is greater than or equal to %s " + - "(you entered %s)", range.min(), number)); - } else if (number > range.max()) { - throw new ParameterException( - String.format( - "A valid value is less than or equal to %s " + - "(you entered %s)", range.max(), number)); - } - } - } - } - - /** - * Validate a number value using relevant modifiers. - * - * @param number the number - * @param modifiers the list of modifiers to scan - * @throws ParameterException on a validation error - */ - private static void validate(int number, Annotation[] modifiers) - throws ParameterException { - for (Annotation modifier : modifiers) { - if (modifier instanceof Range) { - Range range = (Range) modifier; - if (number < range.min()) { - throw new ParameterException( - String.format( - "A valid value is greater than or equal to %s " + - "(you entered %s)", range.min(), number)); - } else if (number > range.max()) { - throw new ParameterException( - String.format( - "A valid value is less than or equal to %s " + - "(you entered %s)", range.max(), number)); - } - } - } - } - - /** - * Validate a string value using relevant modifiers. - * - * @param string the string - * @param modifiers the list of modifiers to scan - * @throws ParameterException on a validation error - */ - private static void validate(String string, Annotation[] modifiers) - throws ParameterException { - if (string == null) { - return; - } - - for (Annotation modifier : modifiers) { - if (modifier instanceof Validate) { - Validate validate = (Validate) modifier; - - if (!validate.regex().isEmpty()) { - if (!string.matches(validate.regex())) { - throw new ParameterException( - String.format( - "The given text doesn't match the right " + - "format (technically speaking, the 'format' is %s)", - validate.regex())); - } - } - } - } - } - } \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/binding/StandardBindings.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/binding/StandardBindings.java index a5a06e5fe..1945c54d2 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/binding/StandardBindings.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/binding/StandardBindings.java @@ -24,11 +24,17 @@ import com.sk89q.worldedit.util.command.parametric.ArgumentStack; import com.sk89q.worldedit.util.command.parametric.BindingBehavior; import com.sk89q.worldedit.util.command.parametric.BindingHelper; import com.sk89q.worldedit.util.command.parametric.BindingMatch; +import com.sk89q.worldedit.util.command.parametric.ParameterException; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import static com.sk89q.worldedit.util.command.parametric.BindingHelper.validate; /** * Standard bindings that should be available to most configurations. */ -public final class StandardBindings extends BindingHelper { +public final class StandardBindings { /** * Gets a {@link CommandContext} from a {@link ArgumentStack}. @@ -42,5 +48,48 @@ public final class StandardBindings extends BindingHelper { context.markConsumed(); // Consume entire stack return context.getContext(); } + + @BindingMatch( + type = Annotation[].class, + behavior = BindingBehavior.PROVIDES, + consumedCount = 0, + provideModifiers = true, + provideType = true) + public Annotation[] getModifiers(ArgumentStack context, Annotation[] modifiers, Type type) throws ParameterException { + return modifiers; + } + + @BindingMatch( + type = Type.class, + behavior = BindingBehavior.PROVIDES, + consumedCount = 0, + provideModifiers = true, + provideType = true) + public Type getType(ArgumentStack context, Annotation[] modifiers, Type type) throws ParameterException { + return type; + } + + @BindingMatch( + type = Enum.class, + behavior = BindingBehavior.CONSUMES, + consumedCount = 1, + provideModifiers = true, + provideType = true) + public Enum getEnum(ArgumentStack context, Annotation[] modifiers, Type type) throws ParameterException { + String input = context.next(); + Enum value; + try { + value = Enum.valueOf((Class) type, input); + } catch (IllegalArgumentException ignore) { + try { + value = Enum.valueOf((Class) type, input.toUpperCase()); + } catch (IllegalArgumentException e) { + throw new ParameterException("Invalid input " + input + " for type " + type); + } + } + validate(value.ordinal(), modifiers); + validate(input, modifiers); + return value; + } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/composition/FlagParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/composition/FlagParser.java index 479a62d6f..fd64dd82d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/composition/FlagParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/composition/FlagParser.java @@ -183,7 +183,6 @@ public class FlagParser implements CommandExecutor { return (T) data.get(flag); } - @SuppressWarnings("unchecked") public T get(FlagData data, T fallback) { T value = get(data); if (value == null) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/AParametricCallable.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/AParametricCallable.java index a8c9a408e..64964d07c 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/AParametricCallable.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/AParametricCallable.java @@ -2,9 +2,7 @@ package com.sk89q.worldedit.util.command.parametric; import com.boydti.fawe.command.SuggestInputParseException; import com.boydti.fawe.config.BBC; -import com.boydti.fawe.util.chat.UsageMessage; import com.sk89q.minecraft.util.commands.*; -import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.util.command.*; import java.lang.reflect.InvocationTargetException; @@ -171,7 +169,7 @@ public abstract class AParametricCallable implements CommandCallable { if (!found) { if (unusedFlags == null) { - unusedFlags = new HashSet(); + unusedFlags = new HashSet<>(); } unusedFlags.add(flag); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/BindingHelper.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/BindingHelper.java index e5024f77b..1d45d0b32 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/BindingHelper.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/BindingHelper.java @@ -22,6 +22,7 @@ package com.sk89q.worldedit.util.command.parametric; import com.boydti.fawe.util.StringMan; import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.worldedit.util.command.binding.Range; +import com.sk89q.worldedit.util.command.binding.Validate; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; @@ -48,16 +49,17 @@ import java.util.List; *

Methods may throw any exception. Exceptions may be converted using a * {@link ExceptionConverter} registered with the {@link ParametricBuilder}.

*/ +@Deprecated public class BindingHelper implements Binding { - private final List bindings; + private final List bindings; private final Type[] types; /** * Create a new instance. */ public BindingHelper() { - List bindings = new ArrayList<>(); + List bindings = new ArrayList<>(); List types = new ArrayList<>(); for (Method method : this.getClass().getMethods()) { @@ -88,7 +90,7 @@ public class BindingHelper implements Binding { "A @BindingMatch needs either a type or classifier set"); } - BoundMethod handler = new BoundMethod(info, type, classifier, method); + BindingMap.BoundMethod handler = new BindingMap.BoundMethod(info, type, classifier, method, this); bindings.add(handler); } } @@ -110,8 +112,8 @@ public class BindingHelper implements Binding { * @param parameter the parameter * @return a binding */ - private BoundMethod match(ParameterData parameter) { - for (BoundMethod binding : bindings) { + private BindingMap.BoundMethod match(ParameterData parameter) { + for (BindingMap.BoundMethod binding : bindings) { Annotation classifer = parameter.getClassifier(); Type type = parameter.getType(); @@ -147,7 +149,7 @@ public class BindingHelper implements Binding { @Override public Object bind(ParameterData parameter, ArgumentStack scoped, boolean onlyConsume) throws ParameterException, CommandException, InvocationTargetException { - BoundMethod binding = match(parameter); + BindingMap.BoundMethod binding = match(parameter); List args = new ArrayList<>(); args.add(scoped); @@ -212,39 +214,88 @@ public class BindingHelper implements Binding { } return new ArrayList<>(); } - - private static class BoundMethod implements Comparable { - private final BindingMatch annotation; - private final Type type; - private final Class classifier; - private final Method method; - - BoundMethod(BindingMatch annotation, Type type, - Class classifier, Method method) { - this.annotation = annotation; - this.type = type; - this.classifier = classifier; - this.method = method; - } - @Override - public int compareTo(BoundMethod o) { - if (classifier != null && o.classifier == null) { - return -1; - } else if (classifier == null && o.classifier != null) { - return 1; - } else if (classifier != null && o.classifier != null) { - if (type != null && o.type == null) { - return -1; - } else if (type == null && o.type != null) { - return 1; - } else { - return 0; + /** + * Validate a number value using relevant modifiers. + * + * @param number the number + * @param modifiers the list of modifiers to scan + * @throws ParameterException on a validation error + */ + public static void validate(double number, Annotation[] modifiers) + throws ParameterException { + for (Annotation modifier : modifiers) { + if (modifier instanceof Range) { + Range range = (Range) modifier; + if (number < range.min()) { + throw new ParameterException( + String.format( + "A valid value is greater than or equal to %s " + + "(you entered %s)", range.min(), number)); + } else if (number > range.max()) { + throw new ParameterException( + String.format( + "A valid value is less than or equal to %s " + + "(you entered %s)", range.max(), number)); } - } else { - return 0; } } } + /** + * Validate a number value using relevant modifiers. + * + * @param number the number + * @param modifiers the list of modifiers to scan + * @throws ParameterException on a validation error + */ + public static void validate(int number, Annotation[] modifiers) + throws ParameterException { + for (Annotation modifier : modifiers) { + if (modifier instanceof Range) { + Range range = (Range) modifier; + if (number < range.min()) { + throw new ParameterException( + String.format( + "A valid value is greater than or equal to %s " + + "(you entered %s)", range.min(), number)); + } else if (number > range.max()) { + throw new ParameterException( + String.format( + "A valid value is less than or equal to %s " + + "(you entered %s)", range.max(), number)); + } + } + } + } + + /** + * Validate a string value using relevant modifiers. + * + * @param string the string + * @param modifiers the list of modifiers to scan + * @throws ParameterException on a validation error + */ + public static void validate(String string, Annotation[] modifiers) + throws ParameterException { + if (string == null) { + return; + } + + for (Annotation modifier : modifiers) { + if (modifier instanceof Validate) { + Validate validate = (Validate) modifier; + + if (!validate.regex().isEmpty()) { + if (!string.matches(validate.regex())) { + throw new ParameterException( + String.format( + "The given text doesn't match the right " + + "format (technically speaking, the 'format' is %s)", + validate.regex())); + } + } + } + } + } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/BindingMap.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/BindingMap.java new file mode 100644 index 000000000..de1896397 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/BindingMap.java @@ -0,0 +1,309 @@ +package com.sk89q.worldedit.util.command.parametric; + +import com.boydti.fawe.util.ArrayUtil; +import com.boydti.fawe.util.MainUtil; +import com.boydti.fawe.util.StringMan; +import com.sk89q.minecraft.util.commands.Command; +import com.sk89q.minecraft.util.commands.CommandException; +import com.sk89q.minecraft.util.commands.CommandLocals; +import com.sk89q.worldedit.util.command.CommandMapping; +import com.sk89q.worldedit.util.command.MissingParameterException; +import com.sk89q.worldedit.util.command.SimpleDispatcher; +import com.sk89q.worldedit.util.command.binding.Range; +import com.sk89q.worldedit.util.command.parametric.ArgumentStack; +import com.sk89q.worldedit.util.command.parametric.Binding; +import com.sk89q.worldedit.util.command.parametric.BindingBehavior; +import com.sk89q.worldedit.util.command.parametric.BindingMatch; +import com.sk89q.worldedit.util.command.parametric.ParameterData; +import com.sk89q.worldedit.util.command.parametric.ParameterException; +import com.sk89q.worldedit.util.command.parametric.ParametricBuilder; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * A binding helper that uses the {@link BindingMatch} annotation to make + * writing bindings extremely easy. + * + *

Methods must have the following and only the following parameters:

+ * + *
    + *
  • A {@link ArgumentStack}
  • + *
  • A {@link Annotation} if there is a classifier set
  • + *
  • A {@link Annotation}[] + * if there {@link BindingMatch#provideModifiers()} is true
  • + *
+ * + *

Methods may throw any exception. Exceptions may be converted using a + * {@link ExceptionConverter} registered with the {@link ParametricBuilder}.

+ */ +public class BindingMap implements Binding { + + private final Set types; + private final Map legacy; + private final Map> bindings; + private final Map dynamicBindings; + private final ParametricBuilder builder; + + /** + * Create a new instance. + * @param builder + */ + public BindingMap(ParametricBuilder builder) { + this.dynamicBindings = new HashMap<>(); + this.legacy = new HashMap<>(); + this.bindings = new HashMap<>(); + this.builder = builder; + this.types = new HashSet<>(); + + } + + public void add(Object object, Type... requiredTypes) { + Method[] methods = object.getClass().getDeclaredMethods(); + for (Method method : methods) { + method.setAccessible(true); + BindingMatch info = method.getAnnotation(BindingMatch.class); + if (info != null) { + Class classifier = null; + + // Set classifier + if (!info.classifier().equals(Annotation.class)) { + classifier = info.classifier(); + } + + for (Type type : info.type()) { + if (type == Void.class) { + type = method.getReturnType(); + } + BoundMethod handler = new BoundMethod(info, type, classifier, method, object); + List list = bindings.get(type); + if (list == null) bindings.put(type, list = new ArrayList<>()); + list.add(handler); + types.add(type); + } + } + Command definition = method.getAnnotation(Command.class); + Class type = method.getReturnType(); + if (definition != null && type != null) { + SimpleDispatcher dispatcher = dynamicBindings.get(type); + if (dispatcher == null) dynamicBindings.put(type, dispatcher = new SimpleDispatcher()); + builder.registerMethodAsCommands(method, dispatcher, object, null); + types.add(type); + } + } + if (requiredTypes != null && requiredTypes.length > 0) { + for (Type type : requiredTypes) { + legacy.put(type, (Binding) object); + } + } + } + + /** + * Match a {@link BindingMatch} according to the given parameter. + * + * @param pd the parameter + * @return a binding + */ + private BoundMethod match(ParameterData pd) { + Type type = pd.getType(); + BoundMethod result = null; + while (type != null) { + List methods = bindings.get(type); + if (methods != null) { + for (BoundMethod binding : methods) { + if (binding.classifier != null) { + if (pd.getClassifier() != null && pd.getClassifier().annotationType().equals(binding.classifier)) { + if (binding.type == null) { + result = binding; + } else if (binding.type.equals(type)) { + return binding; + } + + } + } else if (binding.type.equals(type)) { + if (result == null) result = binding; + } + } + } + if (result != null) return result; + type = (type instanceof Class) ? ((Class) type).getSuperclass() : null; + } + throw new RuntimeException("Unknown type " + pd.getType()); + } + + private SimpleDispatcher matchDynamic(ParameterData pd) { + return dynamicBindings.get(pd.getType()); + } + + @Override + public int getConsumedCount(ParameterData parameter) { + return match(parameter).annotation.consumedCount(); + } + + @Override + public BindingBehavior getBehavior(ParameterData parameter) { + BoundMethod matched = match(parameter); + if (matched != null) return matched.annotation.behavior(); + SimpleDispatcher dynamic = matchDynamic(parameter); + return dynamic != null ? BindingBehavior.CONSUMES : null; + } + + @Override + public Type[] getTypes() { + return types.toArray(new Type[0]); + } + + @Override + public Object bind(ParameterData parameter, ArgumentStack scoped, boolean onlyConsume) throws ParameterException, CommandException, InvocationTargetException { + BoundMethod binding = match(parameter); + List args = new ArrayList<>(); + args.add(scoped); + + if (binding.classifier != null) { + args.add(parameter.getClassifier()); + } + + if (binding.annotation.provideModifiers()) { + args.add(parameter.getModifiers()); + } + + if (binding.annotation.provideType()) { + args.add(parameter.getType()); + } + + if (onlyConsume && binding.annotation.behavior() == BindingBehavior.PROVIDES) { + return null; // Nothing to consume, nothing to do + } + + if (binding.annotation.behavior() != BindingBehavior.PROVIDES) { + SimpleDispatcher dynamic = matchDynamic(parameter); + if (dynamic != null) { + scoped.mark(); + String rest = scoped.remaining(); + scoped.reset(); + int start = rest.indexOf('{'); + if (start > 0) { + int end = StringMan.findMatchingBracket(rest, start); + if (end > start) { + String alias = rest.substring(0, start); + CommandMapping cmd = dynamic.get(alias); + if (cmd != null) { + String arguments = rest.substring(start + 1, end); + CommandLocals locals = scoped.getContext().getLocals(); + Object result = cmd.getCallable().call(arguments, locals, new String[0]); + int remaining = rest.length() - end; + while (rest.length() > remaining) { + scoped.next(); + try { + scoped.mark(); + rest = scoped.remaining(); + scoped.reset(); + } catch (MissingParameterException ignore) { rest = ""; } + } + return result; + } + } + } + } + } + Object[] argsArray = new Object[args.size()]; + args.toArray(argsArray); + + try { + return binding.method.invoke(binding.object, argsArray); + } catch (IllegalArgumentException e) { + throw new RuntimeException( + "Processing of classifier " + parameter.getClassifier() + + " and type " + parameter.getType() + " failed for method\n" + + binding.method + "\nbecause the parameters for that method are wrong", e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } catch (InvocationTargetException e) { + if (e.getCause() instanceof ParameterException) { + throw (ParameterException) e.getCause(); + } else if (e.getCause() instanceof CommandException) { + throw (CommandException) e.getCause(); + } + throw e; + } + } + + @Override + public List getSuggestions(ParameterData parameter, String prefix) { + Binding legacySuggestions = legacy.get(parameter.getType()); + if (legacySuggestions != null) { + List result = legacySuggestions.getSuggestions(parameter, prefix); + if (result != null) return result; + } + if (prefix.isEmpty()) { + char bracket = parameter.isOptional() ? '[' : '<'; + char endBracket = StringMan.getMatchingBracket(bracket); + StringBuilder result = new StringBuilder(); + result.append("\u00A75"); + result.append(bracket); + result.append("\u00A7r"); + if (parameter.getFlag() != null) { + result.append('-').append(parameter.getFlag()).append("\u00A75 \u00A7r"); + } + result.append(parameter.getName()); + if (parameter.getDefaultValue() != null) { + result.append('=').append(StringMan.join(parameter.getDefaultValue(), " ")); + } + Range range = parameter.getModifier(Range.class); + if (range != null) { + result.append('|').append(StringMan.prettyFormat(range.min())).append(",").append(StringMan.prettyFormat(range.max())); + } + result.append("\u00A75"); + result.append(endBracket); + result.append("\u00A7r"); + return Collections.singletonList(result.toString()); + } + return new ArrayList<>(); + } + + protected static class BoundMethod implements Comparable { + protected final BindingMatch annotation; + protected final Type type; + protected final Class classifier; + protected final Method method; + protected final Object object; + + BoundMethod(BindingMatch annotation, Type type, + Class classifier, Method method, Object object) { + this.annotation = annotation; + this.type = type; + this.classifier = classifier; + this.method = method; + this.object = object; + } + + @Override + public int compareTo(BoundMethod o) { + if (classifier != null && o.classifier == null) { + return -1; + } else if (classifier == null && o.classifier != null) { + return 1; + } else if (classifier != null && o.classifier != null) { + if (type != null && o.type == null) { + return -1; + } else if (type == null && o.type != null) { + return 1; + } else { + return 0; + } + } else { + return 0; + } + } + } +} + diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/BindingMatch.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/BindingMatch.java index 049d3dc4d..a76be395b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/BindingMatch.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/BindingMatch.java @@ -45,7 +45,7 @@ public @interface BindingMatch { * @return the type, or {@link Class} if not set */ Class[] type() default Class.class; - + /** * The binding behavior. * @@ -68,4 +68,9 @@ public @interface BindingMatch { */ boolean provideModifiers() default false; + /** + * If the type should be passed to the method + */ + boolean provideType() default false; + } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/FunctionParametricCallable.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/FunctionParametricCallable.java index 4ab9de23f..edcd22b21 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/FunctionParametricCallable.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/FunctionParametricCallable.java @@ -15,9 +15,9 @@ public class FunctionParametricCallable extends AParametricCallable { private final ParametricBuilder builder; private final ParameterData[] parameters; - private final Set valueFlags = new HashSet(); + private final Set valueFlags = new HashSet<>(); private final boolean anyFlags; - private final Set legacyFlags = new HashSet(); + private final Set legacyFlags = new HashSet<>(); private final SimpleDescription description = new SimpleDescription(); private final String permission; private final Command command; @@ -33,10 +33,8 @@ public class FunctionParametricCallable extends AParametricCallable { List paramParsables = new ArrayList<>(); { - Map bindings = builder.getBindings(); Map unqualified = new HashMap<>(); - for (Map.Entry entry : bindings.entrySet()) { - Type type = entry.getKey(); + for (Type type : builder.getBindings().getTypes()) { String typeStr = type.getTypeName(); unqualified.put(typeStr, type); unqualified.put(typeStr.substring(typeStr.lastIndexOf('.') + 1), type); @@ -81,7 +79,7 @@ public class FunctionParametricCallable extends AParametricCallable { } parameters = new ParameterData[paramParsables.size()]; - List userParameters = new ArrayList(); + List userParameters = new ArrayList<>(); // This helps keep tracks of @Nullables that appear in the middle of a list // of parameters @@ -117,7 +115,7 @@ public class FunctionParametricCallable extends AParametricCallable { // No special @annotation binding... let's check for the type if (parameter.getBinding() == null) { - parameter.setBinding(builder.getBindings().get(type)); + parameter.setBinding(builder.getBindings()); // Don't know how to parse for this type of value if (parameter.getBinding() == null) { @@ -325,4 +323,4 @@ public class FunctionParametricCallable extends AParametricCallable { public String toString() { return command.aliases()[0]; } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/ParametricBuilder.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/ParametricBuilder.java index 918bff40d..4d3fbd6be 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/ParametricBuilder.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/ParametricBuilder.java @@ -65,10 +65,10 @@ import static com.google.common.base.Preconditions.checkNotNull; */ public class ParametricBuilder { - private final Map bindings = new HashMap(); + private final BindingMap bindings; private final Paranamer paranamer = new FaweParanamer(); - private final List invokeListeners = new ArrayList(); - private final List exceptionConverters = new ArrayList(); + private final List invokeListeners = new ArrayList<>(); + private final List exceptionConverters = new ArrayList<>(); private Authorizer authorizer = new NullAuthorizer(); private CommandCompleter defaultCompleter = new NullCompleter(); @@ -79,8 +79,9 @@ public class ParametricBuilder { * {@link StandardBindings} and default bindings.

*/ public ParametricBuilder() { - addBinding(new FawePrimitiveBinding()); - addBinding(new StandardBindings()); + this.bindings = new BindingMap(this); + this.bindings.add(new FawePrimitiveBinding()); + this.bindings.add(new StandardBindings()); } /** @@ -103,14 +104,17 @@ public class ParametricBuilder { * @param binding the binding * @param type a list of types (if specified) to override the binding's types */ + @Deprecated public void addBinding(Binding binding, Type... type) { - if (type == null || type.length == 0) { - type = binding.getTypes(); - } + this.bindings.add(binding); + } - for (Type t : type) { - bindings.put(t, binding); - } + /** + * Add a binding (accepts @Command or @BindingMatch methods) + * @param binding + */ + public void addBinding(Object binding) { + this.bindings.add(binding); } /** @@ -175,21 +179,22 @@ public class ParametricBuilder { */ public void registerMethodsAsCommands(Dispatcher dispatcher, Object object, CallableProcessor processor) throws ParametricException { for (Method method : object.getClass().getDeclaredMethods()) { - Command definition = method.getAnnotation(Command.class); - if (definition != null) { - definition = Commands.translate(method.getDeclaringClass(), definition); - CommandCallable callable = build(object, method, definition); - if (processor != null) { - callable = new ProcessedCallable(callable, processor); - } - else if (object instanceof CallableProcessor) { - callable = new ProcessedCallable(callable, (CallableProcessor) object); - } - if (object instanceof MethodCommands) { - ((MethodCommands) object).register(method, callable, dispatcher); - } - dispatcher.registerCommand(callable, definition.aliases()); + registerMethodAsCommands(method, dispatcher, object, processor); + } + } + + public void registerMethodAsCommands(Method method, Dispatcher dispatcher, Object object, CallableProcessor processor) throws ParametricException { + Command definition = method.getAnnotation(Command.class); + if (definition != null) { + definition = Commands.translate(method.getDeclaringClass(), definition); + CommandCallable callable = build(object, method, definition); + if (processor != null) { + callable = new ProcessedCallable(callable, processor); } + else if (object instanceof CallableProcessor) { + callable = new ProcessedCallable(callable, (CallableProcessor) object); + } + dispatcher.registerCommand(callable, definition.aliases()); } } @@ -230,7 +235,7 @@ public class ParametricBuilder { * * @return the map of bindings */ - public Map getBindings() { + public BindingMap getBindings() { return bindings; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/ParametricCallable.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/ParametricCallable.java index a8ad5ab1b..9c66999db 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/ParametricCallable.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/command/parametric/ParametricCallable.java @@ -55,9 +55,9 @@ public class ParametricCallable extends AParametricCallable { private final Object object; private final Method method; private final ParameterData[] parameters; - private final Set valueFlags = new HashSet(); + private final Set valueFlags = new HashSet<>(); private final boolean anyFlags; - private final Set legacyFlags = new HashSet(); + private final Set legacyFlags = new HashSet<>(); private final SimpleDescription description = new SimpleDescription(); private final CommandPermissions commandPermissions; private final Command definition; @@ -81,7 +81,7 @@ public class ParametricCallable extends AParametricCallable { Type[] types = method.getGenericParameterTypes(); parameters = new ParameterData[types.length]; - List userParameters = new ArrayList(); + List userParameters = new ArrayList<>(); // This helps keep tracks of @Nullables that appear in the middle of a list // of parameters @@ -113,7 +113,7 @@ public class ParametricCallable extends AParametricCallable { } // Special annotation bindings } else if (parameter.getBinding() == null) { - parameter.setBinding(builder.getBindings().get(annotation.annotationType())); + parameter.setBinding(builder.getBindings()); parameter.setClassifier(annotation); } } @@ -127,7 +127,7 @@ public class ParametricCallable extends AParametricCallable { // No special @annotation binding... let's check for the type if (parameter.getBinding() == null) { - parameter.setBinding(builder.getBindings().get(type)); + parameter.setBinding(builder.getBindings()); // Don't know how to parse for this type of value if (parameter.getBinding() == null) { @@ -221,7 +221,7 @@ public class ParametricCallable extends AParametricCallable { try { // preProcess handlers - List handlers = new ArrayList(); + List handlers = new ArrayList<>(); for (InvokeListener listener : builder.getInvokeListeners()) { InvokeHandler handler = listener.createInvokeHandler(); handlers.add(handler); @@ -361,4 +361,4 @@ public class ParametricCallable extends AParametricCallable { } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/ColorCodeBuilder.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/ColorCodeBuilder.java index 0134827f5..dbaa904ce 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/ColorCodeBuilder.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/ColorCodeBuilder.java @@ -127,7 +127,7 @@ public class ColorCodeBuilder { } else if (!resetFrom.hasEqualFormatting(resetTo) || (resetFrom.getColor() != null && resetTo.getColor() == null)) { // Have to set reset code and add back all the formatting codes - return String.valueOf(Style.RESET) + getCode(resetTo); + return Style.RESET + getCode(resetTo); } else { if (resetFrom.getColor() != resetTo.getColor()) { return String.valueOf(resetTo.getColor()); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/CommandUsageBox.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/CommandUsageBox.java index 80747ab15..e4935cb16 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/CommandUsageBox.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/formatting/component/CommandUsageBox.java @@ -73,7 +73,7 @@ public class CommandUsageBox extends StyledFragment { CommandListBox box = new CommandListBox(BBC.HELP_HEADER_SUBCOMMANDS.f()); String prefix = !commandString.isEmpty() ? commandString + " " : ""; - List list = new ArrayList(dispatcher.getCommands()); + List list = new ArrayList<>(dispatcher.getCommands()); Collections.sort(list, new PrimaryAliasComparator(CommandManager.COMMAND_CLEAN_PATTERN)); for (CommandMapping mapping : list) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/gson/BlockVectorAdapter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/gson/BlockVectorAdapter.java new file mode 100644 index 000000000..8b86b7542 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/gson/BlockVectorAdapter.java @@ -0,0 +1,46 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.gson; + +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.sk89q.worldedit.math.BlockVector3; + +import java.lang.reflect.Type; + +public class BlockVectorAdapter implements JsonDeserializer { + + @Override + public BlockVector3 deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonArray jsonArray = json.getAsJsonArray(); + if (jsonArray.size() != 3) { + throw new JsonParseException("Expected array of 3 length for BlockVector3"); + } + + double x = jsonArray.get(0).getAsInt(); + double y = jsonArray.get(1).getAsInt(); + double z = jsonArray.get(2).getAsInt(); + + return BlockVector3.at(x, y, z); + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/gson/GsonUtil.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/gson/GsonUtil.java index 8d6d4dd2b..358cd143d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/gson/GsonUtil.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/gson/GsonUtil.java @@ -21,7 +21,8 @@ package com.sk89q.worldedit.util.gson; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; /** * Utility methods for Google's GSON library. @@ -38,7 +39,8 @@ public final class GsonUtil { */ public static GsonBuilder createBuilder() { GsonBuilder gsonBuilder = new GsonBuilder(); - gsonBuilder.registerTypeAdapter(Vector.class, new VectorAdapter()); + gsonBuilder.registerTypeAdapter(Vector3.class, new VectorAdapter()); + gsonBuilder.registerTypeAdapter(BlockVector3.class, new BlockVectorAdapter()); return gsonBuilder; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/gson/VectorAdapter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/gson/VectorAdapter.java index a1e876dfe..c76311299 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/gson/VectorAdapter.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/gson/VectorAdapter.java @@ -24,26 +24,26 @@ import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; import java.lang.reflect.Type; /** - * Deserializes {@code Vector}s for GSON. + * Deserializes {@code Vector3}s for GSON. */ -public class VectorAdapter implements JsonDeserializer { +public class VectorAdapter implements JsonDeserializer { @Override - public Vector deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + public Vector3 deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonArray jsonArray = json.getAsJsonArray(); if (jsonArray.size() != 3) { - throw new JsonParseException("Expected array of 3 length for Vector"); + throw new JsonParseException("Expected array of 3 length for Vector3"); } double x = jsonArray.get(0).getAsDouble(); double y = jsonArray.get(1).getAsDouble(); double z = jsonArray.get(2).getAsDouble(); - return new Vector(x, y, z); + return Vector3.at(x, y, z); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/net/HttpRequest.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/net/HttpRequest.java new file mode 100644 index 000000000..8421210e4 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/net/HttpRequest.java @@ -0,0 +1,490 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.net; + +import com.sk89q.worldedit.util.io.Closer; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class HttpRequest implements Closeable { + + private static final int CONNECT_TIMEOUT = 1000 * 5; + private static final int READ_TIMEOUT = 1000 * 5; + private static final int READ_BUFFER_SIZE = 1024 * 8; + + private final Map headers = new HashMap<>(); + private final String method; + private final URL url; + private String contentType; + private byte[] body; + private HttpURLConnection conn; + private InputStream inputStream; + + private long contentLength = -1; + private long readBytes = 0; + + /** + * Create a new HTTP request. + * + * @param method the method + * @param url the URL + */ + private HttpRequest(String method, URL url) { + this.method = method; + this.url = url; + } + + /** + * Submit data. + * + * @return this object + */ + public HttpRequest body(String data) { + body = data.getBytes(); + return this; + } + + /** + * Submit form data. + * + * @param form the form + * @return this object + */ + public HttpRequest bodyForm(Form form) { + contentType = "application/x-www-form-urlencoded"; + body = form.toString().getBytes(); + return this; + } + + /** + * Add a header. + * + * @param key the header key + * @param value the header value + * @return this object + */ + public HttpRequest header(String key, String value) { + if (key.equalsIgnoreCase("Content-Type")) { + contentType = value; + } else { + headers.put(key, value); + } + return this; + } + + /** + * Execute the request. + *

+ * After execution, {@link #close()} should be called. + * + * @return this object + * @throws java.io.IOException on I/O error + */ + public HttpRequest execute() throws IOException { + boolean successful = false; + + try { + if (conn != null) { + throw new IllegalArgumentException("Connection already executed"); + } + + conn = (HttpURLConnection) reformat(url).openConnection(); + conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Java)"); + + if (body != null) { + conn.setRequestProperty("Content-Type", contentType); + conn.setRequestProperty("Content-Length", Integer.toString(body.length)); + conn.setDoInput(true); + } + + for (Map.Entry entry : headers.entrySet()) { + conn.setRequestProperty(entry.getKey(), entry.getValue()); + } + + conn.setRequestMethod(method); + conn.setUseCaches(false); + conn.setDoOutput(true); + conn.setConnectTimeout(CONNECT_TIMEOUT); + conn.setReadTimeout(READ_TIMEOUT); + + conn.connect(); + + if (body != null) { + DataOutputStream out = new DataOutputStream(conn.getOutputStream()); + out.write(body); + out.flush(); + out.close(); + } + + inputStream = conn.getResponseCode() == HttpURLConnection.HTTP_OK ? + conn.getInputStream() : conn.getErrorStream(); + + successful = true; + } finally { + if (!successful) { + close(); + } + } + + return this; + } + + /** + * Require that the response code is one of the given response codes. + * + * @param codes a list of codes + * @return this object + * @throws java.io.IOException if there is an I/O error or the response code is not expected + */ + public HttpRequest expectResponseCode(int... codes) throws IOException { + int responseCode = getResponseCode(); + + for (int code : codes) { + if (code == responseCode) { + return this; + } + } + + close(); + throw new IOException("Did not get expected response code, got " + responseCode + " for " + url); + } + + /** + * Get the response code. + * + * @return the response code + * @throws java.io.IOException on I/O error + */ + public int getResponseCode() throws IOException { + if (conn == null) { + throw new IllegalArgumentException("No connection has been made"); + } + + return conn.getResponseCode(); + } + + /** + * Get the input stream. + * + * @return the input stream + */ + public InputStream getInputStream() { + return inputStream; + } + + /** + * Buffer the returned response. + * + * @return the buffered response + * @throws java.io.IOException on I/O error + * @throws InterruptedException on interruption + */ + public BufferedResponse returnContent() throws IOException, InterruptedException { + if (inputStream == null) { + throw new IllegalArgumentException("No input stream available"); + } + + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + int b = 0; + while ((b = inputStream.read()) != -1) { + bos.write(b); + } + return new BufferedResponse(bos.toByteArray()); + } finally { + close(); + } + } + + /** + * Save the result to a file. + * + * @param file the file + * @return this object + * @throws java.io.IOException on I/O error + * @throws InterruptedException on interruption + */ + public HttpRequest saveContent(File file) throws IOException, InterruptedException { + Closer closer = Closer.create(); + + try { + FileOutputStream fos = closer.register(new FileOutputStream(file)); + BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos)); + + saveContent(bos); + } finally { + closer.close(); + } + + return this; + } + + /** + * Save the result to an output stream. + * + * @param out the output stream + * @return this object + * @throws java.io.IOException on I/O error + * @throws InterruptedException on interruption + */ + public HttpRequest saveContent(OutputStream out) throws IOException, InterruptedException { + BufferedInputStream bis; + + try { + String field = conn.getHeaderField("Content-Length"); + if (field != null) { + long len = Long.parseLong(field); + if (len >= 0) { // Let's just not deal with really big numbers + contentLength = len; + } + } + } catch (NumberFormatException ignored) { + } + + try { + bis = new BufferedInputStream(inputStream); + + byte[] data = new byte[READ_BUFFER_SIZE]; + int len = 0; + while ((len = bis.read(data, 0, READ_BUFFER_SIZE)) >= 0) { + out.write(data, 0, len); + readBytes += len; + } + } finally { + close(); + } + + return this; + } + + @Override + public void close() throws IOException { + if (conn != null) conn.disconnect(); + } + + /** + * Perform a GET request. + * + * @param url the URL + * @return a new request object + */ + public static HttpRequest get(URL url) { + return request("GET", url); + } + + /** + * Perform a POST request. + * + * @param url the URL + * @return a new request object + */ + public static HttpRequest post(URL url) { + return request("POST", url); + } + + /** + * Perform a request. + * + * @param method the method + * @param url the URL + * @return a new request object + */ + public static HttpRequest request(String method, URL url) { + return new HttpRequest(method, url); + } + + /** + * Create a new {@link java.net.URL} and throw a {@link RuntimeException} if the URL + * is not valid. + * + * @param url the url + * @return a URL object + * @throws RuntimeException if the URL is invalid + */ + public static URL url(String url) { + try { + return new URL(url); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + + /** + * URL may contain spaces and other nasties that will cause a failure. + * + * @param existing the existing URL to transform + * @return the new URL, or old one if there was a failure + */ + private static URL reformat(URL existing) { + try { + URL url = new URL(existing.toString()); + URI uri = new URI( + url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), + url.getPath(), url.getQuery(), url.getRef()); + url = uri.toURL(); + return url; + } catch (MalformedURLException e) { + return existing; + } catch (URISyntaxException e) { + return existing; + } + } + + /** + * Used with {@link #bodyForm(Form)}. + */ + public final static class Form { + public final List elements = new ArrayList<>(); + + private Form() { + } + + /** + * Add a key/value to the form. + * + * @param key the key + * @param value the value + * @return this object + */ + public Form add(String key, String value) { + try { + elements.add(URLEncoder.encode(key, "UTF-8") + + "=" + URLEncoder.encode(value, "UTF-8")); + return this; + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + boolean first = true; + for (String element : elements) { + if (first) { + first = false; + } else { + builder.append("&"); + } + builder.append(element); + } + return builder.toString(); + } + + /** + * Create a new form. + * + * @return a new form + */ + public static Form create() { + return new Form(); + } + } + + /** + * Used to buffer the response in memory. + */ + public class BufferedResponse { + private final byte[] data; + + private BufferedResponse(byte[] data) { + this.data = data; + } + + /** + * Return the result as bytes. + * + * @return the data + */ + public byte[] asBytes() { + return data; + } + + /** + * Return the result as a string. + * + * @param encoding the encoding + * @return the string + * @throws java.io.IOException on I/O error + */ + public String asString(String encoding) throws IOException { + return new String(data, encoding); + } + + /** + * Save the result to a file. + * + * @param file the file + * @return this object + * @throws java.io.IOException on I/O error + * @throws InterruptedException on interruption + */ + public BufferedResponse saveContent(File file) throws IOException, InterruptedException { + Closer closer = Closer.create(); + file.getParentFile().mkdirs(); + + try { + FileOutputStream fos = closer.register(new FileOutputStream(file)); + BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos)); + + saveContent(bos); + } finally { + closer.close(); + } + + return this; + } + + /** + * Save the result to an output stream. + * + * @param out the output stream + * @return this object + * @throws java.io.IOException on I/O error + * @throws InterruptedException on interruption + */ + public BufferedResponse saveContent(OutputStream out) throws IOException, InterruptedException { + out.write(data); + + return this; + } + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/ActorCallbackPaste.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/ActorCallbackPaste.java new file mode 100644 index 000000000..e87e440bf --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/ActorCallbackPaste.java @@ -0,0 +1,71 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.paste; + +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.sk89q.worldedit.command.util.AsyncCommandHelper; +import com.sk89q.worldedit.extension.platform.Actor; +import com.sk89q.worldedit.util.command.parametric.ExceptionConverter; +import com.sk89q.worldedit.util.task.Supervisor; + +import java.net.URL; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ActorCallbackPaste { + + private static final Logger LOGGER = Logger.getLogger(ActorCallbackPaste.class.getSimpleName()); + + private ActorCallbackPaste() { + } + + /** + * Submit data to a pastebin service and inform the sender of + * success or failure. + * + * @param supervisor The supervisor instance + * @param sender The sender + * @param content The content + * @param successMessage The message, formatted with {@link String#format(String, Object...)} on success + */ +public static void pastebin(Supervisor supervisor, final Actor sender, String content, final String successMessage, final ExceptionConverter exceptionConverter) { + ListenableFuture future = new IncendoPaste("fastasyncworldedit").paste(content); + + AsyncCommandHelper.wrap(future, supervisor, sender, exceptionConverter) + .registerWithSupervisor("Submitting content to a pastebin service...") + .sendMessageAfterDelay("(Please wait... sending output to pastebin...)"); + + Futures.addCallback(future, new FutureCallback() { + @Override + public void onSuccess(URL url) { + sender.print(String.format(successMessage, url)); + } + + @Override + public void onFailure(Throwable throwable) { + LOGGER.log(Level.WARNING, "Failed to submit pastebin", throwable); + sender.printError("Failed to submit to a pastebin. Please see console for the error."); + } + }); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/EngineHubPaste.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/EngineHubPaste.java new file mode 100644 index 000000000..da6b701fd --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/EngineHubPaste.java @@ -0,0 +1,78 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.paste; + +import com.google.common.util.concurrent.ListenableFuture; +import com.sk89q.worldedit.util.net.HttpRequest; +import org.json.simple.JSONValue; + +import java.io.IOException; +import java.net.URL; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class EngineHubPaste implements Paster { + + private static final Pattern URL_PATTERN = Pattern.compile("https?://.+$"); + + @Override + public ListenableFuture paste(String content) { + return Pasters.getExecutor().submit(new PasteTask(content)); + } + + private final class PasteTask implements Callable { + private final String content; + + private PasteTask(String content) { + this.content = content; + } + + @Override + public URL call() throws IOException, InterruptedException { + HttpRequest.Form form = HttpRequest.Form.create(); + form.add("content", content); + form.add("from", "worldguard"); + + URL url = HttpRequest.url("http://paste.enginehub.org/paste"); + String result = HttpRequest.post(url) + .bodyForm(form) + .execute() + .expectResponseCode(200) + .returnContent() + .asString("UTF-8").trim(); + + Object object = JSONValue.parse(result); + if (object instanceof Map) { + @SuppressWarnings("unchecked") + String urlString = String.valueOf(((Map) object).get("url")); + Matcher m = URL_PATTERN.matcher(urlString); + + if (m.matches()) { + return new URL(urlString); + } + } + + throw new IOException("Failed to save paste; instead, got: " + result); + } + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/IncendoPaste.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/IncendoPaste.java new file mode 100644 index 000000000..634f77eb5 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/IncendoPaste.java @@ -0,0 +1,280 @@ +package com.sk89q.worldedit.util.paste; + +import com.boydti.fawe.Fawe; +import com.google.common.base.Charsets; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.util.*; +import java.util.concurrent.Callable; + +/** + * Single class paster for the Incendo paste service + * + * @author Sauilitired + */ +@SuppressWarnings({"unused", "WeakerAccess"}) +public final class IncendoPaste implements Paster{ + + /** + * Upload service URL + */ + public static final String UPLOAD_PATH = "https://incendo.org/paste/upload"; + /** + * Valid paste applications + */ + public static final Collection + VALID_APPLICATIONS = Arrays + .asList("plotsquared", "fastasyncworldedit", "incendopermissions", "kvantum"); + + private final Collection files = new ArrayList<>(); + private final String pasteApplication; + + /** + * Construct a new paster + * + * @param pasteApplication The application that is sending the paste + */ + public IncendoPaste(final String pasteApplication) { + if (pasteApplication == null || pasteApplication.isEmpty()) { + throw new IllegalArgumentException("paste application cannot be null, nor empty"); + } + if (!VALID_APPLICATIONS.contains(pasteApplication.toLowerCase(Locale.ENGLISH))) { + throw new IllegalArgumentException( + String.format("Unknown application name: %s", pasteApplication)); + } + this.pasteApplication = pasteApplication; + } + + @Override + public ListenableFuture paste(String content) { + return Pasters.getExecutor().submit(new PasteTask(content)); + } + + private final class PasteTask implements Callable{ + + private PasteTask(String content) {} + + @Override + public URL call() throws Exception { + return new URL(debugPaste()); + } + + } + + /** + * Get an immutable collection containing all the files that have been added to this paster + * + * @return Unmodifiable collection + */ + public final Collection getFiles() { + return Collections.unmodifiableCollection(this.files); + } + + /** + * Add a file to the paster + * + * @param file File to paste + */ + public void addFile(final PasteFile file) { + if (file == null) { + throw new IllegalArgumentException("File cannot be null"); + } + // Check to see that no duplicate files are submitted + for (final PasteFile pasteFile : this.files) { + if (pasteFile.fileName.equalsIgnoreCase(file.getFileName())) { + throw new IllegalArgumentException(String.format("Found duplicate file with name %s", + file.getFileName())); + } + } + this.files.add(file); + } + + /** + * Create a JSON string from the submitted information + * + * @return compiled JSON string + */ + private String toJsonString() { + final StringBuilder builder = new StringBuilder("{\n"); + builder.append("\"paste_application\": \"").append(this.pasteApplication).append("\",\n\"files\": \""); + Iterator fileIterator = this.files.iterator(); + while (fileIterator.hasNext()) { + final PasteFile file = fileIterator.next(); + builder.append(file.getFileName()); + if (fileIterator.hasNext()) { + builder.append(","); + } + } + builder.append("\",\n"); + fileIterator = this.files.iterator(); + while (fileIterator.hasNext()) { + final PasteFile file = fileIterator.next(); + builder.append("\"file-").append(file.getFileName()).append("\": \"") + .append(file.getContent().replaceAll("\"", "\\\\\"")).append("\""); + if (fileIterator.hasNext()) { + builder.append(",\n"); + } + } + builder.append("\n}"); + return builder.toString(); + } + + /** + * Upload the paste and return the status message + * + * @return Status message + * @throws Throwable any and all exceptions + */ + public final String upload() throws Throwable { + final URL url = new URL(UPLOAD_PATH); + final URLConnection connection = url.openConnection(); + final HttpURLConnection httpURLConnection = (HttpURLConnection) connection; + httpURLConnection.setRequestMethod("POST"); + httpURLConnection.setDoOutput(true); + final byte[] content = toJsonString().getBytes(Charsets.UTF_8); + httpURLConnection.setFixedLengthStreamingMode(content.length); + httpURLConnection.setRequestProperty("Content-Type", "application/json"); + httpURLConnection.setRequestProperty("Accept", "*/*"); + httpURLConnection.connect(); + try (final OutputStream stream = httpURLConnection.getOutputStream()) { + stream.write(content); + } + if (!httpURLConnection.getResponseMessage().contains("OK")) { + throw new IllegalStateException(String.format("Server returned status: %d %s", + httpURLConnection.getResponseCode(), httpURLConnection.getResponseMessage())); + } + final StringBuilder input = new StringBuilder(); + try (final BufferedReader inputStream = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) { + String line; + while ((line = inputStream.readLine()) != null) { + input.append(line).append("\n"); + } + } + return input.toString(); + } + + /** + * Simple class that represents a paste file + */ + public static class PasteFile { + + private final String fileName; + private final String content; + + /** + * Construct a new paste file + * + * @param fileName File name, cannot be empty, nor null + * @param content File content, cannot be empty, nor null + */ + public PasteFile(final String fileName, final String content) { + if (fileName == null || fileName.isEmpty()) { + throw new IllegalArgumentException("file name cannot be null, nor empty"); + } + if (content == null || content.isEmpty()) { + throw new IllegalArgumentException("content cannot be null, nor empty"); + } + this.fileName = fileName; + this.content = content; + } + + /** + * Get the file name + * + * @return File name + */ + public String getFileName() { + return this.fileName; + } + + /** + * Get the file content as a single string + * + * @return File content + */ + public String getContent() { + return this.content; + } + } + + public static String debugPaste() throws IOException { + final IncendoPaste incendoPaster = new IncendoPaste("fastasyncworldedit"); + + StringBuilder b = new StringBuilder(); + b.append( + "# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your " + + "problem\n"); + b.append("\n# Server Information\n"); + b.append("server.platform: ").append(Fawe.imp().getPlatform()).append('\n'); + b.append(Fawe.imp().getDebugInfo()).append('\n'); + b.append("\n\n# YAY! Now, let's see what we can find in your JVM\n"); + Runtime runtime = Runtime.getRuntime(); + b.append("memory.free: ").append(runtime.freeMemory()).append('\n'); + b.append("memory.max: ").append(runtime.maxMemory()).append('\n'); + b.append("java.specification.version: '").append(System.getProperty("java.specification.version")).append("'\n"); + b.append("java.vendor: '").append(System.getProperty("java.vendor")).append("'\n"); + b.append("java.version: '").append(System.getProperty("java.version")).append("'\n"); + b.append("os.arch: '").append(System.getProperty("os.arch")).append("'\n"); + b.append("os.name: '").append(System.getProperty("os.name")).append("'\n"); + b.append("os.version: '").append(System.getProperty("os.version")).append("'\n\n"); + b.append("# Okay :D Great. You are now ready to create your bug report!"); + b.append("\n# You can do so at https://github.com/boy0001/FastAsyncWorldedit/issues"); + b.append("\n# or via our Discord at https://discord.gg/ngZCzbU"); + incendoPaster.addFile(new IncendoPaste.PasteFile("information", b.toString())); + + try { + final File logFile = new File(Fawe.imp().getDirectory(), "../../logs/latest.log"); + final String file; + if (Files.size(logFile.toPath()) > 14_000_000) { + file = "too big :("; + } else { + file = readFile(logFile); + } + incendoPaster.addFile(new IncendoPaste.PasteFile("latest.log", file)); + } catch (IOException ignored) { + } + + incendoPaster.addFile(new PasteFile("config.yml", readFile(new File(Fawe.imp().getDirectory(), "config.yml")))); + incendoPaster.addFile(new PasteFile("message.yml", readFile(new File(Fawe.imp().getDirectory(), "message.yml")))); + incendoPaster.addFile(new PasteFile("commands.yml", readFile(new File(Fawe.imp().getDirectory(), "commands.yml")))); + + final String rawResponse; + try { + rawResponse = incendoPaster.upload(); + } catch (Throwable throwable) { + throw new IOException(String.format("Failed to upload files: %s", throwable.getMessage()), throwable); + } + final JsonObject jsonObject = new JsonParser().parse(rawResponse).getAsJsonObject(); + + if (jsonObject.has("created")) { + final String pasteId = jsonObject.get("paste_id").getAsString(); + return String.format("https://incendo.org/paste/view/%s", pasteId); + } else { + throw new IOException(String.format("Failed to upload files: %s", + jsonObject.get("response").getAsString())); + } + } + + private static String readFile(final File file) throws IOException { + final StringBuilder content = new StringBuilder(); + final List lines = new ArrayList<>(); + try (final BufferedReader reader = new BufferedReader(new FileReader(file))) { + String line; + while ((line = reader.readLine()) != null) { + lines.add(line); + } + } + for (int i = Math.max(0, lines.size() - 1000); i < lines.size(); i++) { + content.append(lines.get(i)).append("\n"); + } + return content.toString(); + } + +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/Pastebin.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/Pastebin.java new file mode 100644 index 000000000..dcbef09b0 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/Pastebin.java @@ -0,0 +1,93 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.paste; + +import com.google.common.util.concurrent.ListenableFuture; +import com.sk89q.worldedit.util.net.HttpRequest; + +import java.io.IOException; +import java.net.URL; +import java.util.concurrent.Callable; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Pastebin implements Paster { + + private static final Pattern URL_PATTERN = Pattern.compile("https?://pastebin.com/([^/]+)$"); + + private boolean mungingLinks = true; + + public boolean isMungingLinks() { + return mungingLinks; + } + + public void setMungingLinks(boolean mungingLinks) { + this.mungingLinks = mungingLinks; + } + + @Override + public ListenableFuture paste(String content) { + if (mungingLinks) { + content = content.replaceAll("http://", "http_//"); + } + + return Pasters.getExecutor().submit(new PasteTask(content)); + } + + private final class PasteTask implements Callable { + private final String content; + + private PasteTask(String content) { + this.content = content; + } + + @Override + public URL call() throws IOException, InterruptedException { + HttpRequest.Form form = HttpRequest.Form.create(); + form.add("api_option", "paste"); + form.add("api_dev_key", "4867eae74c6990dbdef07c543cf8f805"); + form.add("api_paste_code", content); + form.add("api_paste_private", "0"); + form.add("api_paste_name", ""); + form.add("api_paste_expire_date", "1W"); + form.add("api_paste_format", "text"); + form.add("api_user_key", ""); + + URL url = HttpRequest.url("http://pastebin.com/api/api_post.php"); + String result = HttpRequest.post(url) + .bodyForm(form) + .execute() + .expectResponseCode(200) + .returnContent() + .asString("UTF-8").trim(); + + Matcher m = URL_PATTERN.matcher(result); + + if (m.matches()) { + return new URL("http://pastebin.com/raw.php?i=" + m.group(1)); + } else if (result.matches("^https?://.+")) { + return new URL(result); + } else { + throw new IOException("Failed to save paste; instead, got: " + result); + } + } + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/Paster.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/Paster.java new file mode 100644 index 000000000..7a7d74cac --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/Paster.java @@ -0,0 +1,30 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.paste; + +import com.google.common.util.concurrent.ListenableFuture; + +import java.net.URL; + +public interface Paster { + + ListenableFuture paste(String content); + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/Pasters.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/Pasters.java new file mode 100644 index 000000000..b809f1836 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/paste/Pasters.java @@ -0,0 +1,44 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.paste; + +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; + +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +final class Pasters { + + private static final ListeningExecutorService executor = + MoreExecutors.listeningDecorator( + new ThreadPoolExecutor(0, Integer.MAX_VALUE, + 2L, TimeUnit.SECONDS, + new SynchronousQueue<>())); + + private Pasters() { + } + + static ListeningExecutorService getExecutor() { + return executor; + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/ConfigReport.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/ConfigReport.java new file mode 100644 index 000000000..1a4b486a0 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/ConfigReport.java @@ -0,0 +1,32 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.report; + +import com.sk89q.worldedit.WorldEdit; + +public class ConfigReport extends DataReport { + + public ConfigReport() { + super("WorldEdit Configuration"); + + append("Configuration", new HierarchyObjectReport("Configuration", WorldEdit.getInstance().getConfiguration())); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/HierarchyObjectReport.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/HierarchyObjectReport.java new file mode 100644 index 000000000..522693919 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/HierarchyObjectReport.java @@ -0,0 +1,32 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.report; + +public class HierarchyObjectReport extends ShallowObjectReport { + + public HierarchyObjectReport(String title, Object object) { + super(title, object); + + Class type = object.getClass(); + while ((type = type.getSuperclass()) != null) { + scanClass(object, type); + } + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/Report.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/Report.java index 877bf2b83..5c08e51d1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/Report.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/Report.java @@ -21,6 +21,7 @@ package com.sk89q.worldedit.util.report; public interface Report { + String getTitle(); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/ShallowObjectReport.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/ShallowObjectReport.java index b94b63e65..bb4abb1f3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/ShallowObjectReport.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/report/ShallowObjectReport.java @@ -34,8 +34,10 @@ public class ShallowObjectReport extends DataReport { super(title); checkNotNull(object, "object"); - Class type = object.getClass(); + scanClass(object, object.getClass()); + } + void scanClass(Object object, Class type) { for (Field field : type.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers())) { continue; @@ -54,5 +56,4 @@ public class ShallowObjectReport extends DataReport { } } } - } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/AbstractTask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/AbstractTask.java new file mode 100644 index 000000000..e81e2bf22 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/AbstractTask.java @@ -0,0 +1,74 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.task; + +import com.google.common.util.concurrent.AbstractFuture; + +import javax.annotation.Nullable; +import java.util.Date; +import java.util.UUID; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * An abstract task that stores a name and owner. + * + * @param the type returned + */ +public abstract class AbstractTask extends AbstractFuture implements Task { + + private final UUID uniqueId = UUID.randomUUID(); + private final String name; + private final Object owner; + private final Date creationDate = new Date(); + + /** + * Create a new instance. + * + * @param name the name + * @param owner the owner + */ + protected AbstractTask(String name, @Nullable Object owner) { + checkNotNull(name); + this.name = name; + this.owner = owner; + } + + @Override + public UUID getUniqueId() { + return uniqueId; + } + + @Override + public String getName() { + return name; + } + + @Nullable + @Override + public Object getOwner() { + return owner; + } + + @Override + public Date getCreationDate() { + return creationDate; + } +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/FutureForwardingTask.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/FutureForwardingTask.java new file mode 100644 index 000000000..61f5d75a9 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/FutureForwardingTask.java @@ -0,0 +1,121 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.task; + +import com.google.common.util.concurrent.ListenableFuture; +import com.sk89q.worldedit.util.task.progress.Progress; + +import javax.annotation.Nullable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * A task that wraps a {@code ListenableFuture}. + * + *

{@link Task.State#SCHEDULED} is never returned because it is not possible + * to test whether the future has "started," so {@link Task.State#RUNNING} is + * returned in its place.

+ * + *

Use {@link #create(ListenableFuture, String, Object)} to create a new + * instance.

+ * + * @param the type returned + */ +public class FutureForwardingTask extends AbstractTask { + + private final ListenableFuture future; + + private FutureForwardingTask(ListenableFuture future, String name, @Nullable Object owner) { + super(name, owner); + checkNotNull(future); + this.future = future; + } + + @Override + public void addListener(Runnable listener, Executor executor) { + future.addListener(listener, executor); + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return future.cancel(mayInterruptIfRunning); + } + + @Override + public boolean isCancelled() { + return future.isCancelled(); + } + + @Override + public boolean isDone() { + return future.isDone(); + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return future.get(); + } + + @Override + public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return future.get(timeout, unit); + } + + @Override + public State getState() { + if (isCancelled()) { + return State.CANCELLED; + } else if (isDone()) { + try { + get(); + return State.SUCCEEDED; + } catch (InterruptedException e) { + return State.CANCELLED; + } catch (ExecutionException e) { + return State.FAILED; + } + } else { + return State.RUNNING; + } + } + + @Override + public Progress getProgress() { + return Progress.indeterminate(); + } + + /** + * Create a new instance. + * + * @param future the future + * @param name the name of the task + * @param owner the owner of the task, or {@code null} + * @param the type returned by the future + * @return a new instance + */ + public static FutureForwardingTask create(ListenableFuture future, String name, @Nullable Object owner) { + return new FutureForwardingTask<>(future, name, owner); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/SimpleSupervisor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/SimpleSupervisor.java new file mode 100644 index 000000000..0712cc5dd --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/SimpleSupervisor.java @@ -0,0 +1,59 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.task; + +import com.google.common.util.concurrent.MoreExecutors; + +import java.util.ArrayList; +import java.util.List; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * An implementation of a {@code Supervisor}. + */ +public class SimpleSupervisor implements Supervisor { + + private final List> monitored = new ArrayList<>(); + private final Object lock = new Object(); + + @Override + public List> getTasks() { + synchronized (lock) { + return new ArrayList<>(monitored); + } + } + + @Override + public void monitor(final Task task) { + checkNotNull(task); + + synchronized (lock) { + monitored.add(task); + } + + task.addListener(() -> { + synchronized (lock) { + monitored.remove(task); + } + }, MoreExecutors.directExecutor()); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/Supervisor.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/Supervisor.java new file mode 100644 index 000000000..9b470700e --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/Supervisor.java @@ -0,0 +1,44 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.task; + +import java.util.List; + +/** + * Manages running tasks and informs users of their progress, but does not + * execute the task. + */ +public interface Supervisor { + + /** + * Get a list of running or queued tasks. + * + * @return a list of tasks + */ + List> getTasks(); + + /** + * Monitor the given task. + * + * @param task the task + */ + void monitor(Task task); + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/Task.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/Task.java new file mode 100644 index 000000000..169cf1718 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/Task.java @@ -0,0 +1,97 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.task; + +import com.google.common.util.concurrent.ListenableFuture; +import com.sk89q.worldedit.util.task.progress.ProgressObservable; + +import javax.annotation.Nullable; +import java.util.Date; +import java.util.UUID; + +/** + * A task is a job that can be scheduled, run, or cancelled. Tasks can report + * on their own status. Tasks have owners. + */ +public interface Task extends ListenableFuture, ProgressObservable { + + /** + * Get the unique ID of this task. + * + * @return this task's unique ID + */ + UUID getUniqueId(); + + /** + * Get the name of the task so it can be printed to the user. + * + * @return the name of the task + */ + String getName(); + + /** + * Get the owner of the task. + * + * @return an owner object, if one is known or valid, otherwise {@code null} + */ + @Nullable + Object getOwner(); + + /** + * Get the state of the task. + * + * @return the state of the task + */ + State getState(); + + /** + * Get the time at which the task was created. + * + * @return a date + */ + Date getCreationDate(); + + /** + * Represents the state of a task. + */ + enum State { + /** + * The task has been scheduled to run but is not running yet. + */ + SCHEDULED, + /** + * The task has been cancelled and may be stopped or will stop. + */ + CANCELLED, + /** + * The task is currently running. + */ + RUNNING, + /** + * The task has failed. + */ + FAILED, + /** + * The task has succeeded. + */ + SUCCEEDED + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/TaskStateComparator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/TaskStateComparator.java new file mode 100644 index 000000000..38b77e73e --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/TaskStateComparator.java @@ -0,0 +1,43 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.task; + +import java.util.Comparator; + +/** + * Compares task states according to the order of the {@link Task.State} + * enumeration. + */ +public class TaskStateComparator implements Comparator> { + + @Override + public int compare(com.sk89q.worldedit.util.task.Task o1, Task o2) { + int ordinal1 = o1.getState().ordinal(); + int ordinal2 = o2.getState().ordinal(); + if (ordinal1 < ordinal2) { + return -1; + } else if (ordinal1 > ordinal2) { + return 1; + } else { + return 0; + } + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/progress/Progress.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/progress/Progress.java new file mode 100644 index 000000000..d3d0571ae --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/progress/Progress.java @@ -0,0 +1,183 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.task.progress; + +import java.util.Arrays; +import java.util.Collection; + +/** + * A progress object describes the progress of an operation, specifying + * either a percentage of completion or a status of indeterminacy. + * + *

Progress objects are immutable.

+ * + *

To create a new instance, use one of the static constructors + * on this class.

+ */ +public abstract class Progress { + + /** + * Create a new instance. + */ + private Progress() { + } + + /** + * Return whether the current progress is indeterminate. + * + * @return true if indeterminate + */ + public abstract boolean isIndeterminate(); + + /** + * Get the progress percentage. + * + *

If {@link #isIndeterminate()} returns {@code true}, the behavior + * of this method is undefined.

+ * + * @return a number in the range [0, 1] + */ + public abstract double getProgress(); + + /** + * Get a static progress object that is indeterminate. + * + * @return a progress object + */ + public static Progress indeterminate() { + return INDETERMINATE; + } + + /** + * Get a static progress object that is complete. + * + * @return a progress object + */ + public static Progress completed() { + return COMPLETED; + } + + /** + * Create a new progress object with the given percentage. + * + * @param value the percentage, which will be clamped to [0, 1] + * @return a progress object + */ + public static Progress of(double value) { + if (value < 0) { + value = 0; + } else if (value > 1) { + value = 1; + } + + final double finalValue = value; + return new Progress() { + @Override + public boolean isIndeterminate() { + return false; + } + + @Override + public double getProgress() { + return finalValue; + } + }; + } + + /** + * Create a new progress object with progress split equally between the + * given progress objects. + * + * @param objects an array of progress objects + * @return a new progress value + */ + public static Progress split(Progress... objects) { + return split(Arrays.asList(objects)); + } + + /** + * Create a new progress object with progress split equally between the + * given progress objects. + * + * @param progress a collection of progress objects + * @return a new progress value + */ + public static Progress split(Collection progress) { + int count = 0; + double total = 0; + + for (Progress p : progress) { + if (p.isIndeterminate()) { + return indeterminate(); + } + total += p.getProgress(); + } + + return of(total / count); + } + + /** + * Create a new progress object with progress split equally between the + * given {@link ProgressObservable}s. + * + * @param observables an array of observables + * @return a new progress value + */ + public static Progress splitObservables(ProgressObservable... observables) { + return splitObservables(Arrays.asList(observables)); + } + + /** + * Create a new progress object with progress split equally between the + * given {@link ProgressObservable}s. + * + * @param observables a collection of observables + * @return a new progress value + */ + public static Progress splitObservables(Collection observables) { + int count = 0; + double total = 0; + + for (ProgressObservable observable : observables) { + Progress p = observable.getProgress(); + if (p.isIndeterminate()) { + return indeterminate(); + } + total += p.getProgress(); + } + + return of(total / count); + } + + private static final Progress COMPLETED = of(1); + + private static final Progress INDETERMINATE = new Progress() { + @Override + public boolean isIndeterminate() { + return true; + } + + @Override + public double getProgress() { + return 0; + } + }; + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/progress/ProgressIterator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/progress/ProgressIterator.java new file mode 100644 index 000000000..447838922 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/progress/ProgressIterator.java @@ -0,0 +1,100 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.task.progress; + +import java.util.Iterator; +import java.util.List; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * An iterator that keeps track of how many entries have been visited and + * calculates a "percent completed" using a provided total count. + * + *

The returned progress percentage will always be between 0 or 1 + * (inclusive). If the iterator returns more entries than the total count, + * then 100% will be returned for the progress.

+ * + * @param the type + */ +public class ProgressIterator implements Iterator, ProgressObservable { + + private final Iterator iterator; + private final int count; + private int visited = 0; + + /** + * Create a new instance. + * + * @param iterator the iterator + * @param count the count + */ + private ProgressIterator(Iterator iterator, int count) { + checkNotNull(iterator); + this.iterator = iterator; + this.count = count; + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public V next() { + V value = iterator.next(); + visited++; + return value; + } + + @Override + public void remove() { + iterator.remove(); + } + + @Override + public Progress getProgress() { + return Progress.of(count > 0 ? Math.min(1, Math.max(0, (visited / (double) count))) : 1); + } + + /** + * Create a new instance. + * + * @param iterator the iterator + * @param count the number of objects + * @param the type + * @return an instance + */ + public static ProgressIterator create(Iterator iterator, int count) { + return new ProgressIterator<>(iterator, count); + } + + /** + * Create a new instance from a list. + * + * @param list a list + * @param the type + * @return an instance + */ + public static ProgressIterator create(List list) { + return create(list.iterator(), list.size()); + } + +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/progress/ProgressObservable.java b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/progress/ProgressObservable.java new file mode 100644 index 000000000..b109e12a2 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/util/task/progress/ProgressObservable.java @@ -0,0 +1,34 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.util.task.progress; + +/** + * An object that is able to report on its progress. + */ +public interface ProgressObservable { + + /** + * Get the current percentage of completion. + * + * @return a progress object + */ + Progress getProgress(); + +} 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 fd0417f3b..80aaa726b 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 @@ -19,10 +19,8 @@ package com.sk89q.worldedit.world; -import com.sk89q.worldedit.BlockVector2D; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.blocks.BaseItemStack; @@ -30,6 +28,9 @@ import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.function.mask.BlockTypeMask; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; @@ -47,12 +48,12 @@ public abstract class AbstractWorld implements World { private int taskId = -1; @Override - public boolean useItem(Vector position, BaseItem item, Direction face) { + public boolean useItem(BlockVector3 position, BaseItem item, Direction face) { return false; } @Override - public final boolean setBlock(Vector pt, BlockStateHolder block) throws WorldEditException { + public final > boolean setBlock(BlockVector3 pt, B block) throws WorldEditException { return setBlock(pt, block, true); } @@ -67,36 +68,36 @@ public abstract class AbstractWorld implements World { } @Override - public void dropItem(Vector pt, BaseItemStack item, int times) { + public void dropItem(Vector3 pt, BaseItemStack item, int times) { for (int i = 0; i < times; ++i) { dropItem(pt, item); } } @Override - public void checkLoadedChunk(Vector pt) { + public void checkLoadedChunk(BlockVector3 pt) { } @Override - public void fixAfterFastMode(Iterable chunks) { + public void fixAfterFastMode(Iterable chunks) { } @Override - public void fixLighting(Iterable chunks) { + public void fixLighting(Iterable chunks) { } @Override - public boolean playEffect(Vector position, int type, int data) { + public boolean playEffect(Vector3 position, int type, int data) { return false; } @Override - public BlockState getLazyBlock(Vector position) { - return new BaseBlock(getBlock(position)); + public BlockState getLazyBlock(BlockVector3 position) { + return new BaseBlock(getBlock(position)).toImmutableState(); } @Override - public boolean queueBlockBreakEffect(Platform server, Vector position, BlockType blockType, double priority) { + public boolean queueBlockBreakEffect(Platform server, BlockVector3 position, BlockType blockType, double priority) { if (taskId == -1) { taskId = server.schedule(0, 1, () -> { int max = Math.max(1, Math.min(30, effectQueue.size() / 3)); @@ -112,19 +113,19 @@ public abstract class AbstractWorld implements World { return false; } - effectQueue.offer(new QueuedEffect(position, blockType, priority)); + effectQueue.offer(new QueuedEffect(position.toVector3(), blockType, priority)); return true; } @Override - public Vector getMinimumPoint() { - return new Vector(-30000000, 0, -30000000); + public BlockVector3 getMinimumPoint() { + return BlockVector3.at(-30000000, 0, -30000000); } @Override - public Vector getMaximumPoint() { - return new Vector(30000000, 255, 30000000); + public BlockVector3 getMaximumPoint() { + return BlockVector3.at(30000000, 255, 30000000); } @Override @@ -133,16 +134,17 @@ public abstract class AbstractWorld implements World { } private class QueuedEffect implements Comparable { - private final Vector position; + private final Vector3 position; private final BlockType blockType; private final double priority; - private QueuedEffect(Vector position, BlockType blockType, double priority) { + private QueuedEffect(Vector3 position, BlockType blockType, double priority) { this.position = position; this.blockType = blockType; this.priority = priority; } + @SuppressWarnings("deprecation") public void play() { playEffect(position, 2001, blockType.getLegacyCombinedId() >> 4); } 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 28b9c2a45..f21e1660f 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 @@ -20,9 +20,16 @@ package com.sk89q.worldedit.world; import com.sk89q.worldedit.*; +import com.sk89q.worldedit.EditSession; +import com.sk89q.worldedit.MaxChangedBlocksException; +import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.TreeGenerator.TreeType; @@ -53,36 +60,41 @@ public class NullWorld extends AbstractWorld { } @Override - public boolean setBlock(Vector position, BlockStateHolder block, boolean notifyAndLight) throws WorldEditException { + public > boolean setBlock(BlockVector3 position, B block, boolean notifyAndLight) throws WorldEditException { return false; } @Override - public int getBlockLightLevel(Vector position) { + public boolean notifyAndLightBlock(BlockVector3 position, BlockState previousType) throws WorldEditException { + return false; + } + + @Override + public int getBlockLightLevel(BlockVector3 position) { return 0; } @Override - public boolean clearContainerBlockContents(Vector position) { + public boolean clearContainerBlockContents(BlockVector3 position) { return false; } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { return null; } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { return false; } @Override - public void dropItem(Vector position, BaseItemStack item) { + public void dropItem(Vector3 position, BaseItemStack item) { } @Override - public void simulateBlockMine(Vector position) { + public void simulateBlockMine(BlockVector3 position) { } @Override @@ -91,7 +103,7 @@ public class NullWorld extends AbstractWorld { } @Override - public boolean generateTree(TreeType type, EditSession editSession, Vector position) throws MaxChangedBlocksException { + public boolean generateTree(TreeType type, EditSession editSession, BlockVector3 position) throws MaxChangedBlocksException { return false; } @@ -114,19 +126,29 @@ public class NullWorld extends AbstractWorld { } @Override - public BlockState getBlock(Vector position) { + public BlockVector3 getSpawnPosition() { + return BlockVector3.ZERO; + } + + @Override + public BlockState getBlock(BlockVector3 position) { return BlockTypes.AIR.getDefaultState(); } @Override - public BlockState getLazyBlock(Vector position) { +//<<<<<<< HEAD + public BlockState getLazyBlock(BlockVector3 position) { return getBlock(position); } @Override - public BlockState getFullBlock(Vector position) { - return getBlock(position); + public BaseBlock getFullBlock(BlockVector3 position) { + return getBlock(position).toBaseBlock(); } +//======= +// public BaseBlock getFullBlock(BlockVector3 position) { +// return getBlock(position).toBaseBlock(); +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner } @Override public List getEntities(Region region) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/SimpleWorld.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/SimpleWorld.java index 024621a09..d9028c95f 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/SimpleWorld.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/SimpleWorld.java @@ -32,6 +32,9 @@ import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.function.mask.BlockMask; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.Operation; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.world.weather.WeatherType; import com.sk89q.worldedit.world.weather.WeatherTypes; @@ -46,22 +49,22 @@ import javax.annotation.Nullable; */ public interface SimpleWorld extends World { @Override - default boolean useItem(Vector position, BaseItem item, Direction face) { + default boolean useItem(BlockVector3 position, BaseItem item, Direction face) { return false; } @Override - default boolean setBlock(Vector position, BlockStateHolder block, boolean notifyAndLight) throws WorldEditException { + default > boolean setBlock(BlockVector3 position, B block, boolean notifyAndLight) throws WorldEditException { return setBlock(position, block); } @Override - default BlockState getFullBlock(Vector position) { - return getLazyBlock(position); + default BaseBlock getFullBlock(BlockVector3 position) { + return getLazyBlock(position).toBaseBlock(); } @Override - boolean setBlock(Vector pt, BlockStateHolder block) throws WorldEditException; + > boolean setBlock(BlockVector3 pt, B block) throws WorldEditException; @Override default int getMaxY() { @@ -74,43 +77,43 @@ public interface SimpleWorld extends World { } @Override - default void dropItem(Vector pt, BaseItemStack item, int times) { + default void dropItem(Vector3 pt, BaseItemStack item, int times) { for (int i = 0; i < times; ++i) { dropItem(pt, item); } } @Override - default void checkLoadedChunk(Vector pt) { + default void checkLoadedChunk(BlockVector3 pt) { } @Override - default void fixAfterFastMode(Iterable chunks) { + default void fixAfterFastMode(Iterable chunks) { } @Override - default void fixLighting(Iterable chunks) { + default void fixLighting(Iterable chunks) { } - @Override - default boolean playEffect(Vector position, int type, int data) { +// @Override + default boolean playEffect(BlockVector3 position, int type, int data) { return false; } @Override - default boolean queueBlockBreakEffect(Platform server, Vector position, BlockType blockType, double priority) { + default boolean queueBlockBreakEffect(Platform server, BlockVector3 position, BlockType blockType, double priority) { SetQueue.IMP.addTask(() -> playEffect(position, 2001, blockType.getLegacyCombinedId() >> 4)); return true; } @Override - default Vector getMinimumPoint() { - return new Vector(-30000000, 0, -30000000); + default BlockVector3 getMinimumPoint() { + return BlockVector3.at(-30000000, 0, -30000000); } @Override - default Vector getMaximumPoint() { - return new Vector(30000000, 255, 30000000); + default BlockVector3 getMaximumPoint() { + return BlockVector3.at(30000000, 255, 30000000); } @Override @@ -120,12 +123,12 @@ public interface SimpleWorld extends World { @Override - default boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, Vector position) throws MaxChangedBlocksException { + default boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) throws MaxChangedBlocksException { return false; } @Override - default void simulateBlockMine(Vector position) { + default void simulateBlockMine(BlockVector3 position) { try { setBlock(position, BlockTypes.AIR.getDefaultState()); } catch (WorldEditException e) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/World.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/World.java index ed0234e6c..cad0be0f5 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/World.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/World.java @@ -19,19 +19,21 @@ package com.sk89q.worldedit.world; -import com.sk89q.worldedit.BlockVector2D; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.TreeGenerator; +import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.weather.WeatherType; @@ -72,10 +74,10 @@ public interface World extends Extent { * @param face The face * @return Whether it succeeded */ - boolean useItem(Vector position, BaseItem item, Direction face); + boolean useItem(BlockVector3 position, BaseItem item, Direction face); /** - * Similar to {@link Extent#setBlock(Vector, BlockStateHolder)} but a + * Similar to {@link Extent#setBlock(BlockVector3, BlockStateHolder)} but a * {@code notifyAndLight} parameter indicates whether adjacent blocks * should be notified that changes have been made and lighting operations * should be executed. @@ -92,7 +94,17 @@ public interface World extends Extent { * @param notifyAndLight true to to notify and light * @return true if the block was successfully set (return value may not be accurate) */ - boolean setBlock(Vector position, BlockStateHolder block, boolean notifyAndLight) throws WorldEditException; + > boolean setBlock(BlockVector3 position, B block, boolean notifyAndLight) throws WorldEditException; + + /** + * Notifies the simulation that the block at the given location has + * been changed and it must be re-lighted (and issue other events). + * + * @param position position of the block + * @param previousType the type of the previous block that was there + * @return true if the block was successfully notified + */ + boolean notifyAndLightBlock(BlockVector3 position, BlockState previousType) throws WorldEditException; /** * Get the light level at the given block. @@ -100,7 +112,7 @@ public interface World extends Extent { * @param position the position * @return the light level (0-15) */ - int getBlockLightLevel(Vector position); + int getBlockLightLevel(BlockVector3 position); /** * Clear a chest's contents. @@ -108,7 +120,7 @@ public interface World extends Extent { * @param position the position * @return true if the container was cleared */ - boolean clearContainerBlockContents(Vector position); + boolean clearContainerBlockContents(BlockVector3 position); /** * Drop an item at the given position. @@ -117,23 +129,23 @@ public interface World extends Extent { * @param item the item to drop * @param count the number of individual stacks to drop (number of item entities) */ - void dropItem(Vector position, BaseItemStack item, int count); + void dropItem(Vector3 position, BaseItemStack item, int count); /** * Drop one stack of the item at the given position. * * @param position the position * @param item the item to drop - * @see #dropItem(Vector, BaseItemStack, int) shortcut method to specify the number of stacks + * @see #dropItem(Vector3, BaseItemStack, int) shortcut method to specify the number of stacks */ - void dropItem(Vector position, BaseItemStack item); + void dropItem(Vector3 position, BaseItemStack item); /** * Simulate a block being mined at the given position. * * @param position the position */ - void simulateBlockMine(Vector position); + void simulateBlockMine(BlockVector3 position); /** * Regenerate an area. @@ -153,19 +165,19 @@ public interface World extends Extent { * @return true if generation was successful * @throws MaxChangedBlocksException thrown if too many blocks were changed */ - boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, Vector position) throws MaxChangedBlocksException; + boolean generateTree(TreeGenerator.TreeType type, EditSession editSession, BlockVector3 position) throws MaxChangedBlocksException; /** * Load the chunk at the given position if it isn't loaded. * * @param position the position */ - void checkLoadedChunk(Vector position); + void checkLoadedChunk(BlockVector3 position); /** * Fix the given chunks after fast mode was used. * - *

Fast mode makes calls to {@link #setBlock(Vector, BlockStateHolder, boolean)} + *

Fast mode makes calls to {@link #setBlock(BlockVector3, BlockStateHolder, boolean)} * with {@code false} for the {@code notifyAndLight} parameter, which * may causes lighting errors to accumulate. Use of this method, if * it is implemented by the underlying world, corrects those lighting @@ -173,14 +185,14 @@ public interface World extends Extent { * * @param chunks a list of chunk coordinates to fix */ - void fixAfterFastMode(Iterable chunks); + void fixAfterFastMode(Iterable chunks); /** * Relight the given chunks if possible. * * @param chunks a list of chunk coordinates to fix */ - void fixLighting(Iterable chunks); + void fixLighting(Iterable chunks); /** * Play the given effect. @@ -190,7 +202,7 @@ public interface World extends Extent { * @param data the effect data * @return true if the effect was played */ - boolean playEffect(Vector position, int type, int data); + boolean playEffect(Vector3 position, int type, int data); /** * Queue a block break effect. @@ -201,7 +213,7 @@ public interface World extends Extent { * @param priority the priority * @return true if the effect was played */ - boolean queueBlockBreakEffect(Platform server, Vector position, BlockType blockType, double priority); + boolean queueBlockBreakEffect(Platform server, BlockVector3 position, BlockType blockType, double priority); /** * Gets the weather type of the world. @@ -232,6 +244,13 @@ public interface World extends Extent { */ void setWeather(WeatherType weatherType, long duration); + /** + * Gets the spawn position of this world. + * + * @return The spawn position + */ + BlockVector3 getSpawnPosition(); + @Override boolean equals(Object other); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BaseBlock.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BaseBlock.java similarity index 57% rename from worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BaseBlock.java rename to worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BaseBlock.java index 9d2644734..31b424422 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BaseBlock.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BaseBlock.java @@ -17,18 +17,25 @@ * along with this program. If not, see . */ -package com.sk89q.worldedit.blocks; +package com.sk89q.worldedit.world.block; + +import static com.google.common.base.Preconditions.checkNotNull; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.world.block.BlockState; -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.WorldEditException; +import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.world.registry.BlockMaterial; import com.sk89q.worldedit.world.registry.LegacyMapper; +import com.sk89q.worldedit.blocks.TileEntityBlock; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.registry.state.Property; +import com.sk89q.worldedit.registry.state.PropertyKey; import javax.annotation.Nullable; + +import java.util.Map; import java.util.Objects; /** @@ -40,7 +47,7 @@ import java.util.Objects; * snapshot of blocks correctly, so, for example, the NBT data for a block * may be missing.

*/ -public class BaseBlock extends BlockState { +public class BaseBlock implements BlockStateHolder, TileEntityBlock { private final BlockState blockState; @Nullable @@ -51,20 +58,15 @@ public class BaseBlock extends BlockState { this(BlockTypes.AIR.getDefaultState()); } - /** - * Construct a block with a state. - * @deprecated Just use the BlockStateHolder instead - * @param blockState The blockstate - */ - @Deprecated - public BaseBlock(BlockStateHolder blockState) { - this(blockState, blockState.getNbtData()); - } - - @Deprecated - public BaseBlock(BlockTypes id) { - this(id.getDefaultState()); - } +// /** +// * Construct a block with a state. +// * @deprecated Just use the BlockStateHolder instead +// * @param blockState The blockstate +// */ +// @Deprecated +// public BaseBlock(BlockStateHolder blockState) { +// this(blockState, blockState.getNbtData()); +// } /** * Construct a block with the given type and default data. @@ -75,16 +77,26 @@ public class BaseBlock extends BlockState { public BaseBlock(BlockType blockType) { this(blockType.getDefaultState()); } + /** + * Construct a block with a state. + * + * @param blockState The blockstate + */ + + public BaseBlock(BlockState blockState) { +// this(blockState, blockState.getNbtData()); + this.blockState = blockState; + } /** * Construct a block with the given ID, data value and NBT data structure. * * @param state The block state - * @param nbtData NBT data, which may be null + * @param nbtData NBT data, which must be provided */ - public BaseBlock(BlockStateHolder state, @Nullable CompoundTag nbtData) { - super(); - this.blockState = state.toImmutableState(); + public BaseBlock(BlockState state, CompoundTag nbtData) { + checkNotNull(nbtData); + this.blockState = state; this.nbtData = nbtData; } @@ -126,11 +138,6 @@ public class BaseBlock extends BlockState { this(other.toImmutableState(), other.getNbtData()); } - @Override - public BlockState toFuzzy() { - return blockState; - } - @Override public String getNbtId() { CompoundTag nbtData = getNbtData(); @@ -162,19 +169,22 @@ public class BaseBlock extends BlockState { @Override public boolean equals(Object o) { if (!(o instanceof BaseBlock)) { + if (!hasNbtData() && o instanceof BlockStateHolder) { + return Objects.equals(toImmutableState(), ((BlockStateHolder) o).toImmutableState()); + } return false; } final BaseBlock otherBlock = (BaseBlock) o; - return this.equals(otherBlock) && Objects.equals(getNbtData(), otherBlock.getNbtData()); + return this.blockState.equalsFuzzy(otherBlock.blockState) && Objects.equals(getNbtData(), otherBlock.getNbtData()); } @Override public final BlockState toImmutableState() { return blockState; } - + @Override public int getInternalId() { return blockState.getInternalId(); @@ -186,8 +196,8 @@ public class BaseBlock extends BlockState { } @Override - public BlockTypes getBlockType() { - return blockState.getBlockType(); + public BlockType getBlockType() { + return blockState.getBlockType(); } @Override @@ -195,9 +205,29 @@ public class BaseBlock extends BlockState { return blockState.getOrdinal(); } + @Override + public BaseBlock toBaseBlock() { + return this; + } + + @Override + public BaseBlock toBaseBlock(CompoundTag compoundTag) { + if (compoundTag == null) { + return this.blockState.toBaseBlock(); + } else if (compoundTag == this.nbtData) { + return this; + } else { + return new BaseBlock(this.blockState, compoundTag); + } + } + @Override public int hashCode() { - return getOrdinal(); + int ret = toImmutableState().hashCode() << 3; + if (hasNbtData()) { + ret += getNbtData().hashCode(); + } + return ret; } @Override @@ -208,4 +238,60 @@ public class BaseBlock extends BlockState { return getAsString(); } } + + @Override + public boolean apply(Extent extent, BlockVector3 get, BlockVector3 set) throws WorldEditException { + return extent.setBlock(set, this); + } + + @Override + public boolean hasNbtData() { + return this.nbtData != null; + } + + @Override + public BaseBlock withPropertyId(int propertyId) { + return getBlockType().withPropertyId(propertyId).toBaseBlock(getNbtData()); + } + + @Override + public int getInternalBlockTypeId() { + return toImmutableState().getInternalBlockTypeId(); + } + + @Override + public int getInternalPropertiesId() { + return toImmutableState().getInternalPropertiesId(); + } + + @Override + public BaseBlock with(Property property, V value) { + return toImmutableState().with(property, value).toBaseBlock(getNbtData()); + } + + @Override + public BaseBlock with(PropertyKey property, V value) { + return toImmutableState().with(property, value).toBaseBlock(getNbtData()); + } + + @Override + public V getState(Property property) { + return toImmutableState().getState(property); + } + + @Override + public V getState(PropertyKey property) { + return toImmutableState().getState(property); + } + + @Override + public Map, Object> getStates() { + return toImmutableState().getStates(); + } + + @Override + public boolean equalsFuzzy(BlockStateHolder o) { + return toImmutableState().equalsFuzzy(o); + } + } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockCategory.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockCategory.java index 8debc2c47..161b1c304 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockCategory.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockCategory.java @@ -52,7 +52,7 @@ public class BlockCategory extends Category { * @param blockStateHolder The blockstateholder * @return If it's a part of this category */ - public boolean contains(BlockStateHolder blockStateHolder) { + public > boolean contains(B blockStateHolder) { return this.getAll().contains(blockStateHolder.getBlockType()); } } 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 017c988cc..f007ad5db 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 @@ -19,43 +19,67 @@ package com.sk89q.worldedit.world.block; -import com.boydti.fawe.Fawe; import com.boydti.fawe.command.SuggestInputParseException; import com.boydti.fawe.object.string.MutableCharSequence; import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; import com.google.common.collect.Maps; import com.sk89q.jnbt.CompoundTag; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BlockMaterial; import com.sk89q.worldedit.extension.input.InputParseException; -import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.function.mask.Mask; -import com.sk89q.worldedit.function.mask.SingleBlockStateMask; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.registry.state.AbstractProperty; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.registry.state.PropertyKey; +import com.sk89q.worldedit.world.registry.BlockMaterial; import javax.annotation.Nullable; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; /** * An immutable class that represents the state a block can be in. */ @SuppressWarnings("unchecked") -public abstract class BlockState implements BlockStateHolder { +public class BlockState implements BlockStateHolder { + private final BlockType blockType; + private BaseBlock emptyBaseBlock; + + BlockState(BlockType blockType) { + this.blockType = blockType; + this.emptyBaseBlock = new BaseBlock(this); + } + + BlockState(BlockType blockType, BaseBlock baseBlock){ + this.blockType = blockType; + this.emptyBaseBlock = baseBlock; + } + + /** + * Creates a fuzzy BlockState. This can be used for partial matching. + * + * @param blockType The block type + * @param values The block state values + */ + private BlockState(BlockType blockType, Map, Object> values) { + this.blockType = blockType; +// this.values = values; +// this.fuzzy = true; + } + /** * Returns a temporary BlockState for a given internal id * @param combinedId * @deprecated magic number * @return BlockState */ + @Deprecated public static BlockState getFromInternalId(int combinedId) throws InputParseException { return BlockTypes.getFromStateId(combinedId).withStateId(combinedId); @@ -200,39 +224,13 @@ public abstract class BlockState implements BlockStateHolder { } @Override - public Mask toMask(Extent extent) { - return new SingleBlockStateMask(extent, this); - } - - @Override - public boolean apply(Extent extent, Vector get, Vector set) throws WorldEditException { + public boolean apply(Extent extent, BlockVector3 get, BlockVector3 set) throws WorldEditException { return extent.setBlock(set, this); } @Override - public BlockState apply(Vector position) { - return this; - } - - @Override - public boolean hasNbtData() { - return getNbtData() != null; - } - - @Override - public String getNbtId() { - return ""; - } - - @Nullable - @Override - public CompoundTag getNbtData() { - return null; - } - - @Override - public void setNbtData(@Nullable CompoundTag nbtData) { - throw new UnsupportedOperationException("This class is immutable."); + public BaseBlock apply(BlockVector3 position) { + return this.toBaseBlock(); } /** @@ -254,7 +252,7 @@ public abstract class BlockState implements BlockStateHolder { @Override public BlockState with(final Property property, final V value) { try { - BlockTypes type = getBlockType(); + BlockType type = getBlockType(); int newState = ((AbstractProperty) property).modify(this.getInternalId(), value); return newState != this.getInternalId() ? type.withStateId(newState) : this; } catch (ClassCastException e) { @@ -265,7 +263,7 @@ public abstract class BlockState implements BlockStateHolder { @Override public BlockState with(final PropertyKey property, final V value) { try { - BlockTypes type = getBlockType(); + BlockType type = getBlockType(); int newState = ((AbstractProperty) type.getProperty(property)).modify(this.getInternalId(), value); return newState != this.getInternalId() ? type.withStateId(newState) : this; } catch (ClassCastException e) { @@ -298,13 +296,22 @@ public abstract class BlockState implements BlockStateHolder { return (Map, Object>) map; } - /** - * Deprecated, use masks - not try to this fuzzy/non fuzzy state nonsense - * @return - */ - @Deprecated - public BlockState toFuzzy() { - return this; + @Override + public BaseBlock toBaseBlock() { + return this.emptyBaseBlock; + } + + @Override + public BaseBlock toBaseBlock(CompoundTag compoundTag) { + if (compoundTag == null) { + return toBaseBlock(); + } + return new BaseBlock(this, compoundTag); + } + + @Override + public BlockType getBlockType() { + return this.blockType; } @Override @@ -313,14 +320,37 @@ public abstract class BlockState implements BlockStateHolder { } @Override - public boolean equals(Object obj) { - return this == obj; - } + public boolean equalsFuzzy(BlockStateHolder o) { + if (this == o) { + // Added a reference equality check for + return true; + } + if (!getBlockType().equals(o.getBlockType())) { + return false; + } - @Override - @Deprecated - public boolean equalsFuzzy(BlockStateHolder o) { - return o.getOrdinal() == this.getOrdinal(); + Set> differingProperties = new HashSet<>(); + for (Object state : o.getStates().keySet()) { + if (getState((Property) state) == null) { + differingProperties.add((Property) state); + } + } + for (Property property : getStates().keySet()) { + if (o.getState(property) == null) { + differingProperties.add(property); + } + } + + for (Property property : getStates().keySet()) { + if (differingProperties.contains(property)) { + continue; + } + if (!Objects.equals(getState(property), o.getState(property))) { + return false; + } + } + + return true; } @Override @@ -332,4 +362,28 @@ public abstract class BlockState implements BlockStateHolder { public String toString() { return getAsString(); } + + @Override + public int getInternalId() { + return blockType.getInternalId(); + } + + @Override + public BlockMaterial getMaterial() { + return blockType.getMaterial(); + } + + @Override + public int getOrdinal() { + //? + return 0; + } + @Override + public boolean equals(Object obj) { + if (!(obj instanceof BlockState)) { + return false; + } + + return equalsFuzzy((BlockState) obj); + } } 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 a3db4e02f..598cdba5a 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 @@ -19,25 +19,23 @@ package com.sk89q.worldedit.world.block; -import com.sk89q.worldedit.blocks.BlockMaterial; -import com.sk89q.worldedit.blocks.TileEntityBlock; -import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.pattern.FawePattern; +import com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.registry.state.PropertyKey; +import com.sk89q.worldedit.world.registry.BlockMaterial; import java.util.Map; import java.util.stream.Collectors; -public interface BlockStateHolder extends FawePattern, TileEntityBlock { +public interface BlockStateHolder> extends FawePattern { /** * Get the block type * * @return The type */ - BlockTypes getBlockType(); + BlockType getBlockType(); /** * Magic number (legacy uses) @@ -45,9 +43,7 @@ public interface BlockStateHolder extends FawePatter * @return */ @Deprecated - default BlockStateHolder withPropertyId(int propertyId) { - return getBlockType().withPropertyId(propertyId); - } + B withPropertyId(int propertyId); /** * Get combined id (legacy uses) @@ -59,18 +55,13 @@ public interface BlockStateHolder extends FawePatter @Deprecated int getOrdinal(); - default BlockMaterial getMaterial() { - return getBlockType().getMaterial(); - } - + BlockMaterial getMaterial(); /** * Get type id (legacy uses) * @return */ @Deprecated - default int getInternalBlockTypeId() { - return getBlockType().getInternalId(); - } + int getInternalBlockTypeId(); /** * Get the block data (legacy uses) @@ -79,16 +70,14 @@ public interface BlockStateHolder extends FawePatter @Deprecated int getInternalPropertiesId(); - Mask toMask(Extent extent); - /** - * Returns a BlockStateHolder with the given state and value applied. + * Returns a BlockState with the given state and value applied. * * @param property The state * @param value The value * @return The modified state, or same if could not be applied */ - T with(final Property property, final V value); + B with(final Property property, final V value); /** * Returns a BlockStateHolder with the given state and value applied. @@ -97,7 +86,7 @@ public interface BlockStateHolder extends FawePatter * @param value The value * @return The modified state, or same if could not be applied */ - BlockStateHolder with(final PropertyKey property, final V value); + B with(final PropertyKey property, final V value); /** * Gets the value at the given state @@ -123,25 +112,42 @@ public interface BlockStateHolder extends FawePatter Map, Object> getStates(); /** - * @deprecated use masks - not try to this fuzzy/non fuzzy state nonsense + * Checks if the type is the same, and if the matched states are the same. + * * @param o other block * @return true if equal */ - @Deprecated - boolean equalsFuzzy(BlockStateHolder o); + boolean equalsFuzzy(BlockStateHolder o); /** - * Returns an immutable BlockStateHolder from this BlockStateHolder. + * Returns an immutable {@link BlockState} from this BlockStateHolder. * * @return A BlockState */ BlockState toImmutableState(); + /** + * Gets a {@link BaseBlock} from this BlockStateHolder. + * + * @return The BaseBlock + */ + BaseBlock toBaseBlock(); + + /** + * Gets a {@link BaseBlock} from this BlockStateHolder. + * + * @param compoundTag The NBT Data to apply + * @return The BaseBlock + */ + BaseBlock toBaseBlock(CompoundTag compoundTag); + default String getAsString() { if (getStates().isEmpty()) { return this.getBlockType().getId(); } else { - String properties = getStates().entrySet().stream().map(entry -> entry.getKey().getName() + "=" + entry.getValue().toString().toLowerCase()).collect(Collectors.joining(",")); + String properties = + getStates().entrySet().stream().map(entry -> entry.getKey().getName() + "=" + entry.getValue().toString().toLowerCase()).collect(Collectors.joining( + ",")); return this.getBlockType().getId() + "[" + properties + "]"; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockStateImpl.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockStateImpl.java index f79df990e..6569d1666 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockStateImpl.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockStateImpl.java @@ -1,19 +1,22 @@ package com.sk89q.worldedit.world.block; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.blocks.BlockMaterial; import com.sk89q.worldedit.extension.platform.Capability; +import com.sk89q.worldedit.world.registry.BlockMaterial; public class BlockStateImpl extends BlockState { private final int internalId; private final int ordinal; - private final BlockTypes type; + private final BlockType type; private BlockMaterial material; + private BaseBlock baseBlock; - protected BlockStateImpl(BlockTypes type, int internalId, int ordinal) { + protected BlockStateImpl(BlockType type, int internalId, int ordinal) { + super(type); this.type = type; this.internalId = internalId; this.ordinal = ordinal; + this.baseBlock = new BaseBlock(this); } public BlockMaterial getMaterial() { @@ -41,7 +44,12 @@ public class BlockStateImpl extends BlockState { } @Override - public final BlockTypes getBlockType() { + public final BlockType getBlockType() { return type; } + + @Override + public BaseBlock toBaseBlock() { + return this.baseBlock; + } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockStateRegistry.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockStateRegistry.java deleted file mode 100644 index b1009a612..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockStateRegistry.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.sk89q.worldedit.world.block; - -public class BlockStateRegistry { - -} 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 f0674a5b1..b87acf092 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 @@ -22,13 +22,18 @@ package com.sk89q.worldedit.world.block; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.ImmutableList; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BlockMaterial; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.SingleBlockTypeMask; import com.sk89q.worldedit.function.pattern.FawePattern; +import com.sk89q.worldedit.math.BlockVector3; +import com.google.common.collect.ImmutableMap; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.world.registry.BlockMaterial; +import com.sk89q.worldedit.extension.platform.Capability; +import com.sk89q.worldedit.registry.NamespacedRegistry; +import com.sk89q.worldedit.registry.state.AbstractProperty; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.registry.state.PropertyKey; import com.sk89q.worldedit.world.item.ItemType; @@ -36,30 +41,56 @@ import com.sk89q.worldedit.world.item.ItemTypes; import com.sk89q.worldedit.world.registry.BundledBlockData; import com.sk89q.worldedit.world.registry.LegacyMapper; +import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; -public interface BlockType extends FawePattern, Comparable { - - default BlockTypes getTypeEnum() { - return (BlockTypes) this; - } +public class BlockType implements FawePattern { + + public static final NamespacedRegistry REGISTRY = new NamespacedRegistry<>("block type"); + + private final @Nonnull String id; + private ArrayList states; + public final Function defaultValue; + private BlockTypes.Settings settings; + private BlockMaterial material; + public BlockType(@Nonnull String id) { + this(id, null); + } + + public BlockType(@Nonnull String id, Function defaultValue) { + this.id = id; + this.defaultValue = defaultValue; + } + + public void setStates(ArrayList states) { + this.states = states; + } + + public void setSettings(BlockTypes.Settings settings) { + this.settings = settings; + } + + public BlockTypes.Settings getSettings(){ + return settings; + } + + public ArrayList updateStates(){ + if(settings != null) { + return settings.localStates = new ArrayList<>(settings.localStates.stream() + .map(state -> new BlockStateImpl(this, state.getInternalId(), state.getOrdinal())).collect(Collectors.toList())); + }else { + return null; + } + } + @Deprecated - int getMaxStateId(); - - @Override - default boolean apply(Extent extent, Vector get, Vector set) throws WorldEditException { - return extent.setBlock(set, this.getDefaultState()); - } - - @Override - default BlockStateHolder apply(Vector position) { - return this.getDefaultState(); - } - - default Mask toMask(Extent extent) { - return new SingleBlockTypeMask(extent, this); + public int getMaxStateId() { + return settings.permutations; } /** @@ -67,15 +98,17 @@ public interface BlockType extends FawePattern, Comparable { * * @return The id */ - String getId(); + public String getId() { + return this.id; + } - default String getNamespace() { + public String getNamespace() { String id = getId(); int i = id.indexOf(':'); return i == -1 ? "minecraft" : id.substring(0, i); } - default String getResource() { + public String getResource() { String id = getId(); return id.substring(id.indexOf(':') + 1); } @@ -85,38 +118,51 @@ public interface BlockType extends FawePattern, Comparable { * * @return The name, or ID */ - default String getName() { - BundledBlockData.BlockEntry entry = BundledBlockData.getInstance().findById(this.getId()); - if (entry == null) { + public String getName() { + String name = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBlockRegistry().getName(this); + if (name == null) { return getId(); } else { - return entry.localizedName; + return name; } } @Deprecated - default BlockState withPropertyId(int internalPropertiesId) { - if (internalPropertiesId == 0) return getDefaultState(); - return BlockState.getFromInternalId(getInternalId() + (internalPropertiesId << BlockTypes.BIT_OFFSET)); + public BlockState withPropertyId(int propertyId) { + if (settings.stateOrdinals == null) return settings.defaultState; + return states.get(settings.stateOrdinals[propertyId]); + } + + @Deprecated + public BlockState withStateId(int internalStateId) { + return this.withPropertyId(internalStateId >> BlockTypes.BIT_OFFSET); } /** - * Gets the properties of this BlockType in a {@code key->property} mapping. + * Properties string in the form property1=foo,prop2=bar + * @param properties + * @return + */ + public BlockState withProperties(String properties) { + int id = getInternalId(); + for (String keyPair : properties.split(",")) { + String[] split = keyPair.split("="); + String name = split[0]; + String value = split[1]; + AbstractProperty btp = settings.propertiesMap.get(name); + id = btp.modify(id, btp.getValueFor(value)); + } + return withStateId(id); + } + + /** + * Gets the properties of this BlockType in a key->property mapping. * * @return The properties map */ @Deprecated - default Map getPropertyMap() { - List properties = getProperties(); - if (properties.isEmpty()) { - return Collections.emptyMap(); - } - - Map map = new HashMap<>(properties.size()); - for (Property property : properties) { - map.put(property.getName(), property); - } - return map; + public Map> getPropertyMap() { + return this.settings.propertiesMap; } /** @@ -125,11 +171,13 @@ public interface BlockType extends FawePattern, Comparable { * @return the properties */ @Deprecated - List getProperties(); + public List> getProperties() { + return this.settings.propertiesList; + } @Deprecated - default Set getPropertiesSet() { - return new HashSet<>(getProperties()); + public Set> getPropertiesSet() { + return this.settings.propertiesSet; } /** @@ -139,20 +187,22 @@ public interface BlockType extends FawePattern, Comparable { * @return The property */ @Deprecated - default Property getProperty(String name) { - Property property = getPropertyMap().get(name); - checkArgument(property != null, "%s has no property named %s", this, name); - return property; + public Property getProperty(String name) { + checkArgument(this.settings.propertiesMap.get(name) != null, "%s has no property named %s", this, name); + return (Property) this.settings.propertiesMap.get(name); } - default boolean hasProperty(PropertyKey key) { - return getPropertyMap().containsKey(key.getId()); + public boolean hasProperty(PropertyKey key) { + int ordinal = key.ordinal(); + return this.settings.propertiesMapArr.length > ordinal ? this.settings.propertiesMapArr[ordinal] != null : false; } - - default Property getProperty(PropertyKey key) { - Property property = getPropertyMap().get(key.getId()); - checkArgument(property != null, "%s has no property named %s", this, key.getId()); - return property; + + public Property getProperty(PropertyKey key) { + try { + return (Property) this.settings.propertiesMapArr[key.ordinal()]; + } catch (IndexOutOfBoundsException ignore) { + return null; + } } /** @@ -160,28 +210,58 @@ public interface BlockType extends FawePattern, Comparable { * * @return The default state */ - BlockState getDefaultState(); + public BlockState getDefaultState() { + BlockState defaultState = this.settings.defaultState; + if (defaultValue != null) { + defaultState = defaultValue.apply(defaultState); + } + return defaultState; + } + + public FuzzyBlockState getFuzzyMatcher() { + return new FuzzyBlockState(this); + } /** - * Gets a list of all possible states for this BlockType. - * - * @return All possible states + * Slow + * @return collection of states */ - List getAllStates(); + @Deprecated + public List getAllStates() { + if (settings.stateOrdinals == null) return Collections.singletonList(getDefaultState()); + return IntStream.of(settings.stateOrdinals).filter(i -> i != -1).mapToObj(i -> states.get(i)).collect(Collectors.toList()); + } /** * Gets a state of this BlockType with the given properties. * * @return The state, if it exists */ - BlockState getState(Map, Object> key); + public BlockState getState(Map, Object> key) { + int id = getInternalId(); + for (Map.Entry, Object> iter : key.entrySet()) { + Property prop = iter.getKey(); + Object value = iter.getValue(); + + /* + * TODO: + * This is likely wrong. The only place this seems to currently (Dec 23 2018) + * be invoked is via ForgeWorld, and value is a String when invoked there... + */ + AbstractProperty btp = this.settings.propertiesMap.get(prop.getName()); + checkArgument(btp != null, "%s has no property named %s", this, prop.getName()); + id = btp.modify(id, btp.getValueFor((String)value)); + } + return withStateId(id); + } + /** * Gets whether this block type has an item representation. * * @return If it has an item */ - default boolean hasItemType() { + public boolean hasItemType() { return getItemType() != null; } @@ -191,8 +271,8 @@ public interface BlockType extends FawePattern, Comparable { * @return The item representation */ @Nullable - default ItemType getItemType() { - return ItemTypes.get(this.getTypeEnum()); + public ItemType getItemType() { + return ItemTypes.get(this); } /** @@ -200,7 +280,11 @@ public interface BlockType extends FawePattern, Comparable { * * @return The material */ - BlockMaterial getMaterial(); + public BlockMaterial getMaterial() { + return this.material == null ? + WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBlockRegistry().getMaterial(this) + : this.material; + } /** * Gets the legacy ID. Needed for legacy reasons. @@ -209,7 +293,7 @@ public interface BlockType extends FawePattern, Comparable { * * @return legacy id or 0, if unknown */ - default int getLegacyCombinedId() { + public int getLegacyCombinedId() { Integer combinedId = LegacyMapper.getInstance().getLegacyCombined(this); return combinedId == null ? 0 : combinedId; } @@ -221,16 +305,43 @@ public interface BlockType extends FawePattern, Comparable { * * @return internal id */ - int getInternalId(); + public int getInternalId() { + return this.settings.internalId; + } @Override - boolean equals(Object obj); + public int hashCode() { + return this.id.hashCode(); + } @Override - int hashCode(); + public boolean equals(Object obj) { + return obj instanceof BlockType && this.id.equals(((BlockType) obj).id); + } + + @Override + public String toString() { + return getId(); + } + + + @Override + public boolean apply(Extent extent, BlockVector3 get, BlockVector3 set) throws WorldEditException { + return extent.setBlock(set, this.getDefaultState()); + } + + @Override + public BaseBlock apply(BlockVector3 position) { + return this.getDefaultState().toBaseBlock(); + } + + public Mask toMask(Extent extent) { + return new SingleBlockTypeMask(extent, this); + } + @Deprecated - default int getLegacyId() { + public int getLegacyId() { Integer id = LegacyMapper.getInstance().getLegacyCombined(this.getDefaultState()); if (id != null) { return id >> 4; 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 4a7a9efbf..4d385e0b3 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 @@ -17,7 +17,7 @@ public class BlockTypeSwitchBuilder { } public BlockTypeSwitchBuilder add(Predicate predicate, T task) { - for (BlockTypes type : BlockTypes.values) { + for (BlockType type : BlockTypes.values) { if (predicate.test(type)) { this.runnables[type.getInternalId()] = task; } 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 new file mode 100644 index 000000000..864a53bcb --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypeUtil.java @@ -0,0 +1,214 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.world.block; + +import com.sk89q.worldedit.registry.state.PropertyGroup; +import com.sk89q.worldedit.registry.state.PropertyKey; +import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BlockTypes; + +import static com.google.common.base.Preconditions.checkNotNull; + +public class BlockTypeUtil { + + public static double centralTopLimit(com.sk89q.worldedit.world.block.BlockType type) { + checkNotNull(type); + return centralTopLimit(type.getDefaultState()); + } + + public static double centralBottomLimit(BlockStateHolder block) { + checkNotNull(block); + BlockType type = block.getBlockType(); + switch (type.getResource().toUpperCase()) { + case "CREEPER_WALL_HEAD": + case "DRAGON_WALL_HEAD": + case "PLAYER_WALL_HEAD": + case "ZOMBIE_WALL_HEAD": return 0.25; + case "ACACIA_SLAB": + case "BIRCH_SLAB": + case "BRICK_SLAB": + case "COBBLESTONE_SLAB": + case "DARK_OAK_SLAB": + case "DARK_PRISMARINE_SLAB": + case "JUNGLE_SLAB": + case "NETHER_BRICK_SLAB": + case "OAK_SLAB": + case "PETRIFIED_OAK_SLAB": + case "PRISMARINE_BRICK_SLAB": + case "PRISMARINE_SLAB": + case "PURPUR_SLAB": + case "QUARTZ_SLAB": + case "RED_SANDSTONE_SLAB": + case "SANDSTONE_SLAB": + case "SPRUCE_SLAB": + case "STONE_BRICK_SLAB": + case "STONE_SLAB": { + String state = (String) block.getState(PropertyKey.TYPE); + if (state == null) return 0; + switch (state) { + case "double": + case "bottom": + return 0; + case "top": + return 0.5; + } + } + case "ACACIA_TRAPDOOR": + case "BIRCH_TRAPDOOR": + case "DARK_OAK_TRAPDOOR": + case "IRON_TRAPDOOR": + case "JUNGLE_TRAPDOOR": + case "OAK_TRAPDOOR": + case "SPRUCE_TRAPDOOR": + if (block.getState(PropertyKey.OPEN) == Boolean.TRUE) { + return 1; + } else if ("bottom".equals(block.getState(PropertyKey.HALF))) { + return 0.8125; + } else { + return 0; + } + case "ACACIA_FENCE_GATE": + case "BIRCH_FENCE_GATE": + case "DARK_OAK_FENCE_GATE": + case "JUNGLE_FENCE_GATE": + case "OAK_FENCE_GATE": + case "SPRUCE_FENCE_GATE": return block.getState(PropertyKey.OPEN) == Boolean.TRUE ? 1 : 0; + default: + if (type.getMaterial().isMovementBlocker()) return 0; + return 1; + } + } + + /** + * Returns the y offset a player falls to when falling onto the top of a block at xp+0.5/zp+0.5. + * + * @param block the block + * @return the y offset + */ + public static double centralTopLimit(BlockStateHolder block) { + checkNotNull(block); + BlockType type = block.getBlockType(); + switch (type.getResource().toUpperCase()) { + case "BLACK_BED": + case "BLUE_BED": + case "BROWN_BED": + case "CYAN_BED": + case "GRAY_BED": + case "GREEN_BED": + case "LIGHT_BLUE_BED": + case "LIGHT_GRAY_BED": + case "LIME_BED": + case "MAGENTA_BED": + case "ORANGE_BED": + case "PINK_BED": + case "PURPLE_BED": + case "RED_BED": + case "WHITE_BED": + case "YELLOW_BED": return 0.5625; + case "BREWING_STAND": return 0.875; + case "CAKE": return (block.getState(PropertyKey.BITES) == (Integer) 6) ? 0 : 0.4375; + case "CAULDRON": return 0.3125; + case "COCOA": return 0.750; + case "ENCHANTING_TABLE": return 0.75; + case "END_PORTAL_FRAME": return block.getState(PropertyKey.EYE) == Boolean.TRUE ? 1 : 0.8125; + case "CREEPER_HEAD": + case "DRAGON_HEAD": + case "PISTON_HEAD": + case "PLAYER_HEAD": + case "ZOMBIE_HEAD": return 0.5; + case "CREEPER_WALL_HEAD": + case "DRAGON_WALL_HEAD": + case "PLAYER_WALL_HEAD": + case "ZOMBIE_WALL_HEAD": return 0.75; + case "ACACIA_FENCE": + case "BIRCH_FENCE": + case "DARK_OAK_FENCE": + case "JUNGLE_FENCE": + case "NETHER_BRICK_FENCE": + case "OAK_FENCE": + case "SPRUCE_FENCE": return 1.5; + case "ACACIA_SLAB": + case "BIRCH_SLAB": + case "BRICK_SLAB": + case "COBBLESTONE_SLAB": + case "DARK_OAK_SLAB": + case "DARK_PRISMARINE_SLAB": + case "JUNGLE_SLAB": + case "NETHER_BRICK_SLAB": + case "OAK_SLAB": + case "PETRIFIED_OAK_SLAB": + case "PRISMARINE_BRICK_SLAB": + case "PRISMARINE_SLAB": + case "PURPUR_SLAB": + case "QUARTZ_SLAB": + case "RED_SANDSTONE_SLAB": + case "SANDSTONE_SLAB": + case "SPRUCE_SLAB": + case "STONE_BRICK_SLAB": + case "STONE_SLAB": { + String state = (String) block.getState(PropertyKey.TYPE); + if (state == null) return 0.5; + switch (state) { + case "bottom": + return 0.5; + case "top": + case "double": + return 1; + } + } + case "LILY_PAD": return 0.015625; + case "REPEATER": return 0.125; + case "SOUL_SAND": return 0.875; + case "COBBLESTONE_WALL": + case "MOSSY_COBBLESTONE_WALL": return 1.5; + case "FLOWER_POT": return 0.375; + case "COMPARATOR": return 0.125; + case "DAYLIGHT_DETECTOR": return 0.375; + case "HOPPER": return 0.625; + case "ACACIA_TRAPDOOR": + case "BIRCH_TRAPDOOR": + case "DARK_OAK_TRAPDOOR": + case "IRON_TRAPDOOR": + case "JUNGLE_TRAPDOOR": + case "OAK_TRAPDOOR": + case "SPRUCE_TRAPDOOR": + if (block.getState(PropertyKey.OPEN) == Boolean.TRUE) { + return 0; + } else if ("top".equals(block.getState(PropertyKey.HALF))) { + return 1; + } else { + return 0.1875; + } + case "ACACIA_FENCE_GATE": + case "BIRCH_FENCE_GATE": + case "DARK_OAK_FENCE_GATE": + case "JUNGLE_FENCE_GATE": + case "OAK_FENCE_GATE": + case "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; + return 1; + + } + } +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypes.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypes.java index b9c378d53..57ae659ec 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypes.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/BlockTypes.java @@ -28,26 +28,28 @@ import com.boydti.fawe.util.ReflectionUtils; import com.boydti.fawe.util.StringMan; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.blocks.BlockMaterial; import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.SingleBlockTypeMask; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.registry.state.AbstractProperty; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.registry.state.PropertyKey; +import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemTypes; +import com.sk89q.worldedit.world.registry.BlockMaterial; import com.sk89q.worldedit.world.registry.BundledBlockData; import com.sk89q.worldedit.world.registry.LegacyMapper; import it.unimi.dsi.fastutil.ints.IntCollections; import javax.annotation.Nullable; import java.util.*; +import java.util.function.Function; import java.util.function.IntPredicate; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -56,642 +58,686 @@ import java.util.stream.Stream; /** * Stores a list of common Block String IDs. */ -public enum BlockTypes implements BlockType { +@SuppressWarnings("deprecation") +public class BlockTypes{ /* ----------------------------------------------------- Replaced at runtime by the block registry ----------------------------------------------------- */ - __RESERVED__, - ACACIA_BUTTON, - ACACIA_DOOR, - ACACIA_FENCE, - ACACIA_FENCE_GATE, - ACACIA_LEAVES, - ACACIA_LOG, - ACACIA_PLANKS, - ACACIA_PRESSURE_PLATE, - ACACIA_SAPLING, - ACACIA_SLAB, - ACACIA_STAIRS, - ACACIA_TRAPDOOR, - ACACIA_WOOD, - ACTIVATOR_RAIL, - AIR, - ALLIUM, - ANDESITE, - ANVIL, - ATTACHED_MELON_STEM, - ATTACHED_PUMPKIN_STEM, - AZURE_BLUET, - BARRIER, - BEACON, - BEDROCK, - BEETROOTS, - BIRCH_BUTTON, - BIRCH_DOOR, - BIRCH_FENCE, - BIRCH_FENCE_GATE, - BIRCH_LEAVES, - BIRCH_LOG, - BIRCH_PLANKS, - BIRCH_PRESSURE_PLATE, - BIRCH_SAPLING, - BIRCH_SLAB, - BIRCH_STAIRS, - BIRCH_TRAPDOOR, - BIRCH_WOOD, - BLACK_BANNER, - BLACK_BED, - BLACK_CARPET, - BLACK_CONCRETE, - BLACK_CONCRETE_POWDER, - BLACK_GLAZED_TERRACOTTA, - BLACK_SHULKER_BOX, - BLACK_STAINED_GLASS, - BLACK_STAINED_GLASS_PANE, - BLACK_TERRACOTTA, - BLACK_WALL_BANNER, - BLACK_WOOL, - BLUE_BANNER, - BLUE_BED, - BLUE_CARPET, - BLUE_CONCRETE, - BLUE_CONCRETE_POWDER, - BLUE_GLAZED_TERRACOTTA, - BLUE_ICE, - BLUE_ORCHID, - BLUE_SHULKER_BOX, - BLUE_STAINED_GLASS, - BLUE_STAINED_GLASS_PANE, - BLUE_TERRACOTTA, - BLUE_WALL_BANNER, - BLUE_WOOL, - BONE_BLOCK, - BOOKSHELF, - BRAIN_CORAL, - BRAIN_CORAL_BLOCK, - BRAIN_CORAL_FAN, - BRAIN_CORAL_WALL_FAN, - BREWING_STAND, - BRICK_SLAB, - BRICK_STAIRS, - BRICKS, - BROWN_BANNER, - BROWN_BED, - BROWN_CARPET, - BROWN_CONCRETE, - BROWN_CONCRETE_POWDER, - BROWN_GLAZED_TERRACOTTA, - BROWN_MUSHROOM, - BROWN_MUSHROOM_BLOCK, - BROWN_SHULKER_BOX, - BROWN_STAINED_GLASS, - BROWN_STAINED_GLASS_PANE, - BROWN_TERRACOTTA, - BROWN_WALL_BANNER, - BROWN_WOOL, - BUBBLE_COLUMN, - BUBBLE_CORAL, - BUBBLE_CORAL_BLOCK, - BUBBLE_CORAL_FAN, - BUBBLE_CORAL_WALL_FAN, - CACTUS, - CAKE, - CARROTS, - CARVED_PUMPKIN, - CAULDRON, - CAVE_AIR, - CHAIN_COMMAND_BLOCK, - CHEST, - CHIPPED_ANVIL, - CHISELED_QUARTZ_BLOCK, - CHISELED_RED_SANDSTONE, - CHISELED_SANDSTONE, - CHISELED_STONE_BRICKS, - CHORUS_FLOWER, - CHORUS_PLANT, - CLAY, - COAL_BLOCK, - COAL_ORE, - COARSE_DIRT, - COBBLESTONE, - COBBLESTONE_SLAB, - COBBLESTONE_STAIRS, - COBBLESTONE_WALL, - COBWEB, - COCOA, - COMMAND_BLOCK, - COMPARATOR, - CONDUIT, - CRACKED_STONE_BRICKS, - CRAFTING_TABLE, - CREEPER_HEAD, - CREEPER_WALL_HEAD, - CUT_RED_SANDSTONE, - CUT_SANDSTONE, - CYAN_BANNER, - CYAN_BED, - CYAN_CARPET, - CYAN_CONCRETE, - CYAN_CONCRETE_POWDER, - CYAN_GLAZED_TERRACOTTA, - CYAN_SHULKER_BOX, - CYAN_STAINED_GLASS, - CYAN_STAINED_GLASS_PANE, - CYAN_TERRACOTTA, - CYAN_WALL_BANNER, - CYAN_WOOL, - DAMAGED_ANVIL, - DANDELION, - DARK_OAK_BUTTON, - DARK_OAK_DOOR, - DARK_OAK_FENCE, - DARK_OAK_FENCE_GATE, - DARK_OAK_LEAVES, - DARK_OAK_LOG, - DARK_OAK_PLANKS, - DARK_OAK_PRESSURE_PLATE, - DARK_OAK_SAPLING, - DARK_OAK_SLAB, - DARK_OAK_STAIRS, - DARK_OAK_TRAPDOOR, - DARK_OAK_WOOD, - DARK_PRISMARINE, - DARK_PRISMARINE_SLAB, - DARK_PRISMARINE_STAIRS, - DAYLIGHT_DETECTOR, - DEAD_BRAIN_CORAL, - DEAD_BRAIN_CORAL_BLOCK, - DEAD_BRAIN_CORAL_FAN, - DEAD_BRAIN_CORAL_WALL_FAN, - DEAD_BUBBLE_CORAL, - DEAD_BUBBLE_CORAL_BLOCK, - DEAD_BUBBLE_CORAL_FAN, - DEAD_BUBBLE_CORAL_WALL_FAN, - DEAD_BUSH, - DEAD_FIRE_CORAL, - DEAD_FIRE_CORAL_BLOCK, - DEAD_FIRE_CORAL_FAN, - DEAD_FIRE_CORAL_WALL_FAN, - DEAD_HORN_CORAL, - DEAD_HORN_CORAL_BLOCK, - DEAD_HORN_CORAL_FAN, - DEAD_HORN_CORAL_WALL_FAN, - DEAD_TUBE_CORAL, - DEAD_TUBE_CORAL_BLOCK, - DEAD_TUBE_CORAL_FAN, - DEAD_TUBE_CORAL_WALL_FAN, - DETECTOR_RAIL, - DIAMOND_BLOCK, - DIAMOND_ORE, - DIORITE, - DIRT, - DISPENSER, - DRAGON_EGG, - DRAGON_HEAD, - DRAGON_WALL_HEAD, - DRIED_KELP_BLOCK, - DROPPER, - EMERALD_BLOCK, - EMERALD_ORE, - ENCHANTING_TABLE, - END_GATEWAY, - END_PORTAL, - END_PORTAL_FRAME, - END_ROD, - END_STONE, - END_STONE_BRICKS, - ENDER_CHEST, - FARMLAND, - FERN, - FIRE, - FIRE_CORAL, - FIRE_CORAL_BLOCK, - FIRE_CORAL_FAN, - FIRE_CORAL_WALL_FAN, - FLOWER_POT, - FROSTED_ICE, - FURNACE, - GLASS, - GLASS_PANE, - GLOWSTONE, - GOLD_BLOCK, - GOLD_ORE, - GRANITE, - GRASS, - GRASS_BLOCK, - GRASS_PATH, - GRAVEL, - GRAY_BANNER, - GRAY_BED, - GRAY_CARPET, - GRAY_CONCRETE, - GRAY_CONCRETE_POWDER, - GRAY_GLAZED_TERRACOTTA, - GRAY_SHULKER_BOX, - GRAY_STAINED_GLASS, - GRAY_STAINED_GLASS_PANE, - GRAY_TERRACOTTA, - GRAY_WALL_BANNER, - GRAY_WOOL, - GREEN_BANNER, - GREEN_BED, - GREEN_CARPET, - GREEN_CONCRETE, - GREEN_CONCRETE_POWDER, - GREEN_GLAZED_TERRACOTTA, - GREEN_SHULKER_BOX, - GREEN_STAINED_GLASS, - GREEN_STAINED_GLASS_PANE, - GREEN_TERRACOTTA, - GREEN_WALL_BANNER, - GREEN_WOOL, - HAY_BLOCK, - HEAVY_WEIGHTED_PRESSURE_PLATE, - HOPPER, - HORN_CORAL, - HORN_CORAL_BLOCK, - HORN_CORAL_FAN, - HORN_CORAL_WALL_FAN, - ICE, - INFESTED_CHISELED_STONE_BRICKS, - INFESTED_COBBLESTONE, - INFESTED_CRACKED_STONE_BRICKS, - INFESTED_MOSSY_STONE_BRICKS, - INFESTED_STONE, - INFESTED_STONE_BRICKS, - IRON_BARS, - IRON_BLOCK, - IRON_DOOR, - IRON_ORE, - IRON_TRAPDOOR, - JACK_O_LANTERN, - JUKEBOX, - JUNGLE_BUTTON, - JUNGLE_DOOR, - JUNGLE_FENCE, - JUNGLE_FENCE_GATE, - JUNGLE_LEAVES, - JUNGLE_LOG, - JUNGLE_PLANKS, - JUNGLE_PRESSURE_PLATE, - JUNGLE_SAPLING, - JUNGLE_SLAB, - JUNGLE_STAIRS, - JUNGLE_TRAPDOOR, - JUNGLE_WOOD, - KELP, - KELP_PLANT, - LADDER, - LAPIS_BLOCK, - LAPIS_ORE, - LARGE_FERN, - LAVA, - LEVER, - LIGHT_BLUE_BANNER, - LIGHT_BLUE_BED, - LIGHT_BLUE_CARPET, - LIGHT_BLUE_CONCRETE, - LIGHT_BLUE_CONCRETE_POWDER, - LIGHT_BLUE_GLAZED_TERRACOTTA, - LIGHT_BLUE_SHULKER_BOX, - LIGHT_BLUE_STAINED_GLASS, - LIGHT_BLUE_STAINED_GLASS_PANE, - LIGHT_BLUE_TERRACOTTA, - LIGHT_BLUE_WALL_BANNER, - LIGHT_BLUE_WOOL, - LIGHT_GRAY_BANNER, - LIGHT_GRAY_BED, - LIGHT_GRAY_CARPET, - LIGHT_GRAY_CONCRETE, - LIGHT_GRAY_CONCRETE_POWDER, - LIGHT_GRAY_GLAZED_TERRACOTTA, - LIGHT_GRAY_SHULKER_BOX, - LIGHT_GRAY_STAINED_GLASS, - LIGHT_GRAY_STAINED_GLASS_PANE, - LIGHT_GRAY_TERRACOTTA, - LIGHT_GRAY_WALL_BANNER, - LIGHT_GRAY_WOOL, - LIGHT_WEIGHTED_PRESSURE_PLATE, - LILAC, - LILY_PAD, - LIME_BANNER, - LIME_BED, - LIME_CARPET, - LIME_CONCRETE, - LIME_CONCRETE_POWDER, - LIME_GLAZED_TERRACOTTA, - LIME_SHULKER_BOX, - LIME_STAINED_GLASS, - LIME_STAINED_GLASS_PANE, - LIME_TERRACOTTA, - LIME_WALL_BANNER, - LIME_WOOL, - MAGENTA_BANNER, - MAGENTA_BED, - MAGENTA_CARPET, - MAGENTA_CONCRETE, - MAGENTA_CONCRETE_POWDER, - MAGENTA_GLAZED_TERRACOTTA, - MAGENTA_SHULKER_BOX, - MAGENTA_STAINED_GLASS, - MAGENTA_STAINED_GLASS_PANE, - MAGENTA_TERRACOTTA, - MAGENTA_WALL_BANNER, - MAGENTA_WOOL, - MAGMA_BLOCK, - MELON, - MELON_STEM, - MOSSY_COBBLESTONE, - MOSSY_COBBLESTONE_WALL, - MOSSY_STONE_BRICKS, - MOVING_PISTON, - MUSHROOM_STEM, - MYCELIUM, - NETHER_BRICK_FENCE, - NETHER_BRICK_SLAB, - NETHER_BRICK_STAIRS, - NETHER_BRICKS, - NETHER_PORTAL, - NETHER_QUARTZ_ORE, - NETHER_WART, - NETHER_WART_BLOCK, - NETHERRACK, - NOTE_BLOCK, - OAK_BUTTON, - OAK_DOOR, - OAK_FENCE, - OAK_FENCE_GATE, - OAK_LEAVES, - OAK_LOG, - OAK_PLANKS, - OAK_PRESSURE_PLATE, - OAK_SAPLING, - OAK_SLAB, - OAK_STAIRS, - OAK_TRAPDOOR, - OAK_WOOD, - OBSERVER, - OBSIDIAN, - ORANGE_BANNER, - ORANGE_BED, - ORANGE_CARPET, - ORANGE_CONCRETE, - ORANGE_CONCRETE_POWDER, - ORANGE_GLAZED_TERRACOTTA, - ORANGE_SHULKER_BOX, - ORANGE_STAINED_GLASS, - ORANGE_STAINED_GLASS_PANE, - ORANGE_TERRACOTTA, - ORANGE_TULIP, - ORANGE_WALL_BANNER, - ORANGE_WOOL, - OXEYE_DAISY, - PACKED_ICE, - PEONY, - PETRIFIED_OAK_SLAB, - PINK_BANNER, - PINK_BED, - PINK_CARPET, - PINK_CONCRETE, - PINK_CONCRETE_POWDER, - PINK_GLAZED_TERRACOTTA, - PINK_SHULKER_BOX, - PINK_STAINED_GLASS, - PINK_STAINED_GLASS_PANE, - PINK_TERRACOTTA, - PINK_TULIP, - PINK_WALL_BANNER, - PINK_WOOL, - PISTON, - PISTON_HEAD, - PLAYER_HEAD, - PLAYER_WALL_HEAD, - PODZOL, - POLISHED_ANDESITE, - POLISHED_DIORITE, - POLISHED_GRANITE, - POPPY, - POTATOES, - POTTED_ACACIA_SAPLING, - POTTED_ALLIUM, - POTTED_AZURE_BLUET, - POTTED_BIRCH_SAPLING, - POTTED_BLUE_ORCHID, - POTTED_BROWN_MUSHROOM, - POTTED_CACTUS, - POTTED_DANDELION, - POTTED_DARK_OAK_SAPLING, - POTTED_DEAD_BUSH, - POTTED_FERN, - POTTED_JUNGLE_SAPLING, - POTTED_OAK_SAPLING, - POTTED_ORANGE_TULIP, - POTTED_OXEYE_DAISY, - POTTED_PINK_TULIP, - POTTED_POPPY, - POTTED_RED_MUSHROOM, - POTTED_RED_TULIP, - POTTED_SPRUCE_SAPLING, - POTTED_WHITE_TULIP, - POWERED_RAIL, - PRISMARINE, - PRISMARINE_BRICK_SLAB, - PRISMARINE_BRICK_STAIRS, - PRISMARINE_BRICKS, - PRISMARINE_SLAB, - PRISMARINE_STAIRS, - PUMPKIN, - PUMPKIN_STEM, - PURPLE_BANNER, - PURPLE_BED, - PURPLE_CARPET, - PURPLE_CONCRETE, - PURPLE_CONCRETE_POWDER, - PURPLE_GLAZED_TERRACOTTA, - PURPLE_SHULKER_BOX, - PURPLE_STAINED_GLASS, - PURPLE_STAINED_GLASS_PANE, - PURPLE_TERRACOTTA, - PURPLE_WALL_BANNER, - PURPLE_WOOL, - PURPUR_BLOCK, - PURPUR_PILLAR, - PURPUR_SLAB, - PURPUR_STAIRS, - QUARTZ_BLOCK, - QUARTZ_PILLAR, - QUARTZ_SLAB, - QUARTZ_STAIRS, - RAIL, - RED_BANNER, - RED_BED, - RED_CARPET, - RED_CONCRETE, - RED_CONCRETE_POWDER, - RED_GLAZED_TERRACOTTA, - RED_MUSHROOM, - RED_MUSHROOM_BLOCK, - RED_NETHER_BRICKS, - RED_SAND, - RED_SANDSTONE, - RED_SANDSTONE_SLAB, - RED_SANDSTONE_STAIRS, - RED_SHULKER_BOX, - RED_STAINED_GLASS, - RED_STAINED_GLASS_PANE, - RED_TERRACOTTA, - RED_TULIP, - RED_WALL_BANNER, - RED_WOOL, - REDSTONE_BLOCK, - REDSTONE_LAMP, - REDSTONE_ORE, - REDSTONE_TORCH, - REDSTONE_WALL_TORCH, - REDSTONE_WIRE, - REPEATER, - REPEATING_COMMAND_BLOCK, - ROSE_BUSH, - SAND, - SANDSTONE, - SANDSTONE_SLAB, - SANDSTONE_STAIRS, - SEA_LANTERN, - SEA_PICKLE, - SEAGRASS, - SHULKER_BOX, - SIGN, - SKELETON_SKULL, - SKELETON_WALL_SKULL, - SLIME_BLOCK, - SMOOTH_QUARTZ, - SMOOTH_RED_SANDSTONE, - SMOOTH_SANDSTONE, - SMOOTH_STONE, - SNOW, - SNOW_BLOCK, - SOUL_SAND, - SPAWNER, - SPONGE, - SPRUCE_BUTTON, - SPRUCE_DOOR, - SPRUCE_FENCE, - SPRUCE_FENCE_GATE, - SPRUCE_LEAVES, - SPRUCE_LOG, - SPRUCE_PLANKS, - SPRUCE_PRESSURE_PLATE, - SPRUCE_SAPLING, - SPRUCE_SLAB, - SPRUCE_STAIRS, - SPRUCE_TRAPDOOR, - SPRUCE_WOOD, - STICKY_PISTON, - STONE, - STONE_BRICK_SLAB, - STONE_BRICK_STAIRS, - STONE_BRICKS, - STONE_BUTTON, - STONE_PRESSURE_PLATE, - STONE_SLAB, - STRIPPED_ACACIA_LOG, - STRIPPED_ACACIA_WOOD, - STRIPPED_BIRCH_LOG, - STRIPPED_BIRCH_WOOD, - STRIPPED_DARK_OAK_LOG, - STRIPPED_DARK_OAK_WOOD, - STRIPPED_JUNGLE_LOG, - STRIPPED_JUNGLE_WOOD, - STRIPPED_OAK_LOG, - STRIPPED_OAK_WOOD, - STRIPPED_SPRUCE_LOG, - STRIPPED_SPRUCE_WOOD, - STRUCTURE_BLOCK, - STRUCTURE_VOID, - SUGAR_CANE, - SUNFLOWER, - TALL_GRASS, - TALL_SEAGRASS, - TERRACOTTA, - TNT, - TORCH, - TRAPPED_CHEST, - TRIPWIRE, - TRIPWIRE_HOOK, - TUBE_CORAL, - TUBE_CORAL_BLOCK, - TUBE_CORAL_FAN, - TUBE_CORAL_WALL_FAN, - TURTLE_EGG, - VINE, - VOID_AIR, - WALL_SIGN, - WALL_TORCH, - WATER, - WET_SPONGE, - WHEAT, - WHITE_BANNER, - WHITE_BED, - WHITE_CARPET, - WHITE_CONCRETE, - WHITE_CONCRETE_POWDER, - WHITE_GLAZED_TERRACOTTA, - WHITE_SHULKER_BOX, - WHITE_STAINED_GLASS, - WHITE_STAINED_GLASS_PANE, - WHITE_TERRACOTTA, - WHITE_TULIP, - WHITE_WALL_BANNER, - WHITE_WOOL, - WITHER_SKELETON_SKULL, - WITHER_SKELETON_WALL_SKULL, - YELLOW_BANNER, - YELLOW_BED, - YELLOW_CARPET, - YELLOW_CONCRETE, - YELLOW_CONCRETE_POWDER, - YELLOW_GLAZED_TERRACOTTA, - YELLOW_SHULKER_BOX, - YELLOW_STAINED_GLASS, - YELLOW_STAINED_GLASS_PANE, - YELLOW_TERRACOTTA, - YELLOW_WALL_BANNER, - YELLOW_WOOL, - ZOMBIE_HEAD, - ZOMBIE_WALL_HEAD, + public static final BlockType __RESERVED__ = register("minecraft:__reserved__"); + public static final BlockType ACACIA_BUTTON = register("minecraft:acacia_button", state -> state.with(state.getBlockType().getProperty("face"), "WALL").with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType ACACIA_DOOR = register("minecraft:acacia_door", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "lower").with(state.getBlockType().getProperty("hinge"), "left").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType ACACIA_FENCE = register("minecraft:acacia_fence", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType ACACIA_FENCE_GATE = register("minecraft:acacia_fence_gate", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("in_wall"), false).with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType ACACIA_LEAVES = register("minecraft:acacia_leaves", state -> state.with(state.getBlockType().getProperty("distance"), 7).with(state.getBlockType().getProperty("persistent"), false)); + public static final BlockType ACACIA_LOG = register("minecraft:acacia_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType ACACIA_PLANKS = register("minecraft:acacia_planks"); + public static final BlockType ACACIA_PRESSURE_PLATE = register("minecraft:acacia_pressure_plate", state -> state.with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType ACACIA_SAPLING = register("minecraft:acacia_sapling", state -> state.with(state.getBlockType().getProperty("stage"), 0)); + public static final BlockType ACACIA_SLAB = register("minecraft:acacia_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType ACACIA_STAIRS = register("minecraft:acacia_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType ACACIA_TRAPDOOR = register("minecraft:acacia_trapdoor", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false).with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType ACACIA_WOOD = register("minecraft:acacia_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType ACTIVATOR_RAIL = register("minecraft:activator_rail", state -> state.with(state.getBlockType().getProperty("powered"), false).with(state.getBlockType().getProperty("shape"), "north_south")); + public static final BlockType AIR = register("minecraft:air"); + public static final BlockType ALLIUM = register("minecraft:allium"); + public static final BlockType ANDESITE = register("minecraft:andesite"); + public static final BlockType ANVIL = register("minecraft:anvil", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType ATTACHED_MELON_STEM = register("minecraft:attached_melon_stem", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType ATTACHED_PUMPKIN_STEM = register("minecraft:attached_pumpkin_stem", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType AZURE_BLUET = register("minecraft:azure_bluet"); + public static final BlockType BARRIER = register("minecraft:barrier"); + public static final BlockType BEACON = register("minecraft:beacon"); + public static final BlockType BEDROCK = register("minecraft:bedrock"); + public static final BlockType BEETROOTS = register("minecraft:beetroots", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType BIRCH_BUTTON = register("minecraft:birch_button", state -> state.with(state.getBlockType().getProperty("face"), "WALL").with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType BIRCH_DOOR = register("minecraft:birch_door", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "lower").with(state.getBlockType().getProperty("hinge"), "left").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType BIRCH_FENCE = register("minecraft:birch_fence", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType BIRCH_FENCE_GATE = register("minecraft:birch_fence_gate", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("in_wall"), false).with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType BIRCH_LEAVES = register("minecraft:birch_leaves", state -> state.with(state.getBlockType().getProperty("distance"), 7).with(state.getBlockType().getProperty("persistent"), false)); + public static final BlockType BIRCH_LOG = register("minecraft:birch_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType BIRCH_PLANKS = register("minecraft:birch_planks"); + public static final BlockType BIRCH_PRESSURE_PLATE = register("minecraft:birch_pressure_plate", state -> state.with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType BIRCH_SAPLING = register("minecraft:birch_sapling", state -> state.with(state.getBlockType().getProperty("stage"), 0)); + public static final BlockType BIRCH_SLAB = register("minecraft:birch_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType BIRCH_STAIRS = register("minecraft:birch_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType BIRCH_TRAPDOOR = register("minecraft:birch_trapdoor", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false).with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType BIRCH_WOOD = register("minecraft:birch_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType BLACK_BANNER = register("minecraft:black_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType BLACK_BED = register("minecraft:black_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType BLACK_CARPET = register("minecraft:black_carpet"); + public static final BlockType BLACK_CONCRETE = register("minecraft:black_concrete"); + public static final BlockType BLACK_CONCRETE_POWDER = register("minecraft:black_concrete_powder"); + public static final BlockType BLACK_GLAZED_TERRACOTTA = register("minecraft:black_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType BLACK_SHULKER_BOX = register("minecraft:black_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType BLACK_STAINED_GLASS = register("minecraft:black_stained_glass"); + public static final BlockType BLACK_STAINED_GLASS_PANE = register("minecraft:black_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType BLACK_TERRACOTTA = register("minecraft:black_terracotta"); + public static final BlockType BLACK_WALL_BANNER = register("minecraft:black_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType BLACK_WOOL = register("minecraft:black_wool"); + public static final BlockType BLUE_BANNER = register("minecraft:blue_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType BLUE_BED = register("minecraft:blue_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType BLUE_CARPET = register("minecraft:blue_carpet"); + public static final BlockType BLUE_CONCRETE = register("minecraft:blue_concrete"); + public static final BlockType BLUE_CONCRETE_POWDER = register("minecraft:blue_concrete_powder"); + public static final BlockType BLUE_GLAZED_TERRACOTTA = register("minecraft:blue_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType BLUE_ICE = register("minecraft:blue_ice"); + public static final BlockType BLUE_ORCHID = register("minecraft:blue_orchid"); + public static final BlockType BLUE_SHULKER_BOX = register("minecraft:blue_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType BLUE_STAINED_GLASS = register("minecraft:blue_stained_glass"); + public static final BlockType BLUE_STAINED_GLASS_PANE = register("minecraft:blue_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType BLUE_TERRACOTTA = register("minecraft:blue_terracotta"); + public static final BlockType BLUE_WALL_BANNER = register("minecraft:blue_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType BLUE_WOOL = register("minecraft:blue_wool"); + public static final BlockType BONE_BLOCK = register("minecraft:bone_block", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType BOOKSHELF = register("minecraft:bookshelf"); + public static final BlockType BRAIN_CORAL = register("minecraft:brain_coral", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType BRAIN_CORAL_BLOCK = register("minecraft:brain_coral_block"); + public static final BlockType BRAIN_CORAL_FAN = register("minecraft:brain_coral_fan", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType BRAIN_CORAL_WALL_FAN = register("minecraft:brain_coral_wall_fan", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType BREWING_STAND = register("minecraft:brewing_stand", state -> state.with(state.getBlockType().getProperty("has_bottle_0"), false).with(state.getBlockType().getProperty("has_bottle_1"), false).with(state.getBlockType().getProperty("has_bottle_2"), false)); + public static final BlockType BRICK_SLAB = register("minecraft:brick_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType BRICK_STAIRS = register("minecraft:brick_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType BRICKS = register("minecraft:bricks"); + public static final BlockType BROWN_BANNER = register("minecraft:brown_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType BROWN_BED = register("minecraft:brown_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType BROWN_CARPET = register("minecraft:brown_carpet"); + public static final BlockType BROWN_CONCRETE = register("minecraft:brown_concrete"); + public static final BlockType BROWN_CONCRETE_POWDER = register("minecraft:brown_concrete_powder"); + public static final BlockType BROWN_GLAZED_TERRACOTTA = register("minecraft:brown_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType BROWN_MUSHROOM = register("minecraft:brown_mushroom"); + public static final BlockType BROWN_MUSHROOM_BLOCK = register("minecraft:brown_mushroom_block", state -> state.with(state.getBlockType().getProperty("down"), true).with(state.getBlockType().getProperty("east"), true).with(state.getBlockType().getProperty("north"), true).with(state.getBlockType().getProperty("south"), true).with(state.getBlockType().getProperty("up"), true).with(state.getBlockType().getProperty("west"), true)); + public static final BlockType BROWN_SHULKER_BOX = register("minecraft:brown_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType BROWN_STAINED_GLASS = register("minecraft:brown_stained_glass"); + public static final BlockType BROWN_STAINED_GLASS_PANE = register("minecraft:brown_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType BROWN_TERRACOTTA = register("minecraft:brown_terracotta"); + public static final BlockType BROWN_WALL_BANNER = register("minecraft:brown_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType BROWN_WOOL = register("minecraft:brown_wool"); + public static final BlockType BUBBLE_COLUMN = register("minecraft:bubble_column", state -> state.with(state.getBlockType().getProperty("drag"), true)); + public static final BlockType BUBBLE_CORAL = register("minecraft:bubble_coral", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType BUBBLE_CORAL_BLOCK = register("minecraft:bubble_coral_block"); + public static final BlockType BUBBLE_CORAL_FAN = register("minecraft:bubble_coral_fan", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType BUBBLE_CORAL_WALL_FAN = register("minecraft:bubble_coral_wall_fan", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType CACTUS = register("minecraft:cactus", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType CAKE = register("minecraft:cake", state -> state.with(state.getBlockType().getProperty("bites"), 0)); + public static final BlockType CARROTS = register("minecraft:carrots", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType CARVED_PUMPKIN = register("minecraft:carved_pumpkin", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType CAULDRON = register("minecraft:cauldron", state -> state.with(state.getBlockType().getProperty("level"), 0)); + public static final BlockType CAVE_AIR = register("minecraft:cave_air"); + public static final BlockType CHAIN_COMMAND_BLOCK = register("minecraft:chain_command_block", state -> state.with(state.getBlockType().getProperty("conditional"), false).with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType CHEST = register("minecraft:chest", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("type"), "SINGLE").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType CHIPPED_ANVIL = register("minecraft:chipped_anvil", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType CHISELED_QUARTZ_BLOCK = register("minecraft:chiseled_quartz_block"); + public static final BlockType CHISELED_RED_SANDSTONE = register("minecraft:chiseled_red_sandstone"); + public static final BlockType CHISELED_SANDSTONE = register("minecraft:chiseled_sandstone"); + public static final BlockType CHISELED_STONE_BRICKS = register("minecraft:chiseled_stone_bricks"); + public static final BlockType CHORUS_FLOWER = register("minecraft:chorus_flower", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType CHORUS_PLANT = register("minecraft:chorus_plant", state -> state.with(state.getBlockType().getProperty("down"), false).with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("up"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType CLAY = register("minecraft:clay"); + public static final BlockType COAL_BLOCK = register("minecraft:coal_block"); + public static final BlockType COAL_ORE = register("minecraft:coal_ore"); + public static final BlockType COARSE_DIRT = register("minecraft:coarse_dirt"); + public static final BlockType COBBLESTONE = register("minecraft:cobblestone"); + public static final BlockType COBBLESTONE_SLAB = register("minecraft:cobblestone_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType COBBLESTONE_STAIRS = register("minecraft:cobblestone_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType COBBLESTONE_WALL = register("minecraft:cobblestone_wall", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("up"), true).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType COBWEB = register("minecraft:cobweb"); + public static final BlockType COCOA = register("minecraft:cocoa", state -> state.with(state.getBlockType().getProperty("age"), 0).with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType COMMAND_BLOCK = register("minecraft:command_block", state -> state.with(state.getBlockType().getProperty("conditional"), false).with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType COMPARATOR = register("minecraft:comparator", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("mode"), "compare").with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType CONDUIT = register("minecraft:conduit", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType CRACKED_STONE_BRICKS = register("minecraft:cracked_stone_bricks"); + public static final BlockType CRAFTING_TABLE = register("minecraft:crafting_table"); + public static final BlockType CREEPER_HEAD = register("minecraft:creeper_head", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType CREEPER_WALL_HEAD = register("minecraft:creeper_wall_head", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType CUT_RED_SANDSTONE = register("minecraft:cut_red_sandstone"); + public static final BlockType CUT_SANDSTONE = register("minecraft:cut_sandstone"); + public static final BlockType CYAN_BANNER = register("minecraft:cyan_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType CYAN_BED = register("minecraft:cyan_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType CYAN_CARPET = register("minecraft:cyan_carpet"); + public static final BlockType CYAN_CONCRETE = register("minecraft:cyan_concrete"); + public static final BlockType CYAN_CONCRETE_POWDER = register("minecraft:cyan_concrete_powder"); + public static final BlockType CYAN_GLAZED_TERRACOTTA = register("minecraft:cyan_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType CYAN_SHULKER_BOX = register("minecraft:cyan_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType CYAN_STAINED_GLASS = register("minecraft:cyan_stained_glass"); + public static final BlockType CYAN_STAINED_GLASS_PANE = register("minecraft:cyan_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType CYAN_TERRACOTTA = register("minecraft:cyan_terracotta"); + public static final BlockType CYAN_WALL_BANNER = register("minecraft:cyan_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType CYAN_WOOL = register("minecraft:cyan_wool"); + public static final BlockType DAMAGED_ANVIL = register("minecraft:damaged_anvil", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType DANDELION = register("minecraft:dandelion"); + public static final BlockType DARK_OAK_BUTTON = register("minecraft:dark_oak_button", state -> state.with(state.getBlockType().getProperty("face"), "WALL").with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType DARK_OAK_DOOR = register("minecraft:dark_oak_door", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "lower").with(state.getBlockType().getProperty("hinge"), "left").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType DARK_OAK_FENCE = register("minecraft:dark_oak_fence", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType DARK_OAK_FENCE_GATE = register("minecraft:dark_oak_fence_gate", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("in_wall"), false).with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType DARK_OAK_LEAVES = register("minecraft:dark_oak_leaves", state -> state.with(state.getBlockType().getProperty("distance"), 7).with(state.getBlockType().getProperty("persistent"), false)); + public static final BlockType DARK_OAK_LOG = register("minecraft:dark_oak_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType DARK_OAK_PLANKS = register("minecraft:dark_oak_planks"); + public static final BlockType DARK_OAK_PRESSURE_PLATE = register("minecraft:dark_oak_pressure_plate", state -> state.with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType DARK_OAK_SAPLING = register("minecraft:dark_oak_sapling", state -> state.with(state.getBlockType().getProperty("stage"), 0)); + public static final BlockType DARK_OAK_SLAB = register("minecraft:dark_oak_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType DARK_OAK_STAIRS = register("minecraft:dark_oak_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType DARK_OAK_TRAPDOOR = register("minecraft:dark_oak_trapdoor", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false).with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType DARK_OAK_WOOD = register("minecraft:dark_oak_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType DARK_PRISMARINE = register("minecraft:dark_prismarine"); + public static final BlockType DARK_PRISMARINE_SLAB = register("minecraft:dark_prismarine_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType DARK_PRISMARINE_STAIRS = register("minecraft:dark_prismarine_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType DAYLIGHT_DETECTOR = register("minecraft:daylight_detector", state -> state.with(state.getBlockType().getProperty("inverted"), false).with(state.getBlockType().getProperty("power"), 0)); + public static final BlockType DEAD_BRAIN_CORAL = register("minecraft:dead_brain_coral", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_BRAIN_CORAL_BLOCK = register("minecraft:dead_brain_coral_block"); + public static final BlockType DEAD_BRAIN_CORAL_FAN = register("minecraft:dead_brain_coral_fan", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_BRAIN_CORAL_WALL_FAN = register("minecraft:dead_brain_coral_wall_fan", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_BUBBLE_CORAL = register("minecraft:dead_bubble_coral", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_BUBBLE_CORAL_BLOCK = register("minecraft:dead_bubble_coral_block"); + public static final BlockType DEAD_BUBBLE_CORAL_FAN = register("minecraft:dead_bubble_coral_fan", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_BUBBLE_CORAL_WALL_FAN = register("minecraft:dead_bubble_coral_wall_fan", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_BUSH = register("minecraft:dead_bush"); + public static final BlockType DEAD_FIRE_CORAL = register("minecraft:dead_fire_coral", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_FIRE_CORAL_BLOCK = register("minecraft:dead_fire_coral_block"); + public static final BlockType DEAD_FIRE_CORAL_FAN = register("minecraft:dead_fire_coral_fan", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_FIRE_CORAL_WALL_FAN = register("minecraft:dead_fire_coral_wall_fan", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_HORN_CORAL = register("minecraft:dead_horn_coral", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_HORN_CORAL_BLOCK = register("minecraft:dead_horn_coral_block"); + public static final BlockType DEAD_HORN_CORAL_FAN = register("minecraft:dead_horn_coral_fan", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_HORN_CORAL_WALL_FAN = register("minecraft:dead_horn_coral_wall_fan", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_TUBE_CORAL = register("minecraft:dead_tube_coral", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_TUBE_CORAL_BLOCK = register("minecraft:dead_tube_coral_block"); + public static final BlockType DEAD_TUBE_CORAL_FAN = register("minecraft:dead_tube_coral_fan", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DEAD_TUBE_CORAL_WALL_FAN = register("minecraft:dead_tube_coral_wall_fan", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType DETECTOR_RAIL = register("minecraft:detector_rail", state -> state.with(state.getBlockType().getProperty("powered"), false).with(state.getBlockType().getProperty("shape"), "north_south")); + public static final BlockType DIAMOND_BLOCK = register("minecraft:diamond_block"); + public static final BlockType DIAMOND_ORE = register("minecraft:diamond_ore"); + public static final BlockType DIORITE = register("minecraft:diorite"); + public static final BlockType DIRT = register("minecraft:dirt"); + public static final BlockType DISPENSER = register("minecraft:dispenser", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("triggered"), false)); + public static final BlockType DRAGON_EGG = register("minecraft:dragon_egg"); + public static final BlockType DRAGON_HEAD = register("minecraft:dragon_head", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType DRAGON_WALL_HEAD = register("minecraft:dragon_wall_head", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType DRIED_KELP_BLOCK = register("minecraft:dried_kelp_block"); + public static final BlockType DROPPER = register("minecraft:dropper", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("triggered"), false)); + public static final BlockType EMERALD_BLOCK = register("minecraft:emerald_block"); + public static final BlockType EMERALD_ORE = register("minecraft:emerald_ore"); + public static final BlockType ENCHANTING_TABLE = register("minecraft:enchanting_table"); + public static final BlockType END_GATEWAY = register("minecraft:end_gateway"); + public static final BlockType END_PORTAL = register("minecraft:end_portal"); + public static final BlockType END_PORTAL_FRAME = register("minecraft:end_portal_frame", state -> state.with(state.getBlockType().getProperty("eye"), false).with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType END_ROD = register("minecraft:end_rod", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType END_STONE = register("minecraft:end_stone"); + public static final BlockType END_STONE_BRICKS = register("minecraft:end_stone_bricks"); + public static final BlockType ENDER_CHEST = register("minecraft:ender_chest", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType FARMLAND = register("minecraft:farmland", state -> state.with(state.getBlockType().getProperty("moisture"), 0)); + public static final BlockType FERN = register("minecraft:fern"); + public static final BlockType FIRE = register("minecraft:fire", state -> state.with(state.getBlockType().getProperty("age"), 0).with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("up"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType FIRE_CORAL = register("minecraft:fire_coral", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType FIRE_CORAL_BLOCK = register("minecraft:fire_coral_block"); + public static final BlockType FIRE_CORAL_FAN = register("minecraft:fire_coral_fan", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType FIRE_CORAL_WALL_FAN = register("minecraft:fire_coral_wall_fan", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType FLOWER_POT = register("minecraft:flower_pot"); + public static final BlockType FROSTED_ICE = register("minecraft:frosted_ice", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType FURNACE = register("minecraft:furnace", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("lit"), false)); + public static final BlockType GLASS = register("minecraft:glass"); + public static final BlockType GLASS_PANE = register("minecraft:glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType GLOWSTONE = register("minecraft:glowstone"); + public static final BlockType GOLD_BLOCK = register("minecraft:gold_block"); + public static final BlockType GOLD_ORE = register("minecraft:gold_ore"); + public static final BlockType GRANITE = register("minecraft:granite"); + public static final BlockType GRASS = register("minecraft:grass"); + public static final BlockType GRASS_BLOCK = register("minecraft:grass_block", state -> state.with(state.getBlockType().getProperty("snowy"), false)); + public static final BlockType GRASS_PATH = register("minecraft:grass_path"); + public static final BlockType GRAVEL = register("minecraft:gravel"); + public static final BlockType GRAY_BANNER = register("minecraft:gray_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType GRAY_BED = register("minecraft:gray_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType GRAY_CARPET = register("minecraft:gray_carpet"); + public static final BlockType GRAY_CONCRETE = register("minecraft:gray_concrete"); + public static final BlockType GRAY_CONCRETE_POWDER = register("minecraft:gray_concrete_powder"); + public static final BlockType GRAY_GLAZED_TERRACOTTA = register("minecraft:gray_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType GRAY_SHULKER_BOX = register("minecraft:gray_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType GRAY_STAINED_GLASS = register("minecraft:gray_stained_glass"); + public static final BlockType GRAY_STAINED_GLASS_PANE = register("minecraft:gray_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType GRAY_TERRACOTTA = register("minecraft:gray_terracotta"); + public static final BlockType GRAY_WALL_BANNER = register("minecraft:gray_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType GRAY_WOOL = register("minecraft:gray_wool"); + public static final BlockType GREEN_BANNER = register("minecraft:green_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType GREEN_BED = register("minecraft:green_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType GREEN_CARPET = register("minecraft:green_carpet"); + public static final BlockType GREEN_CONCRETE = register("minecraft:green_concrete"); + public static final BlockType GREEN_CONCRETE_POWDER = register("minecraft:green_concrete_powder"); + public static final BlockType GREEN_GLAZED_TERRACOTTA = register("minecraft:green_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType GREEN_SHULKER_BOX = register("minecraft:green_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType GREEN_STAINED_GLASS = register("minecraft:green_stained_glass"); + public static final BlockType GREEN_STAINED_GLASS_PANE = register("minecraft:green_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType GREEN_TERRACOTTA = register("minecraft:green_terracotta"); + public static final BlockType GREEN_WALL_BANNER = register("minecraft:green_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType GREEN_WOOL = register("minecraft:green_wool"); + public static final BlockType HAY_BLOCK = register("minecraft:hay_block", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType HEAVY_WEIGHTED_PRESSURE_PLATE = register("minecraft:heavy_weighted_pressure_plate", state -> state.with(state.getBlockType().getProperty("power"), 0)); + public static final BlockType HOPPER = register("minecraft:hopper", state -> state.with(state.getBlockType().getProperty("enabled"), true).with(state.getBlockType().getProperty("facing"), Direction.DOWN)); + public static final BlockType HORN_CORAL = register("minecraft:horn_coral", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType HORN_CORAL_BLOCK = register("minecraft:horn_coral_block"); + public static final BlockType HORN_CORAL_FAN = register("minecraft:horn_coral_fan", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType HORN_CORAL_WALL_FAN = register("minecraft:horn_coral_wall_fan", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType ICE = register("minecraft:ice"); + public static final BlockType INFESTED_CHISELED_STONE_BRICKS = register("minecraft:infested_chiseled_stone_bricks"); + public static final BlockType INFESTED_COBBLESTONE = register("minecraft:infested_cobblestone"); + public static final BlockType INFESTED_CRACKED_STONE_BRICKS = register("minecraft:infested_cracked_stone_bricks"); + public static final BlockType INFESTED_MOSSY_STONE_BRICKS = register("minecraft:infested_mossy_stone_bricks"); + public static final BlockType INFESTED_STONE = register("minecraft:infested_stone"); + public static final BlockType INFESTED_STONE_BRICKS = register("minecraft:infested_stone_bricks"); + public static final BlockType IRON_BARS = register("minecraft:iron_bars", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType IRON_BLOCK = register("minecraft:iron_block"); + public static final BlockType IRON_DOOR = register("minecraft:iron_door", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "lower").with(state.getBlockType().getProperty("hinge"), "left").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType IRON_ORE = register("minecraft:iron_ore"); + public static final BlockType IRON_TRAPDOOR = register("minecraft:iron_trapdoor", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false).with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType JACK_O_LANTERN = register("minecraft:jack_o_lantern", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType JUKEBOX = register("minecraft:jukebox", state -> state.with(state.getBlockType().getProperty("has_record"), false)); + public static final BlockType JUNGLE_BUTTON = register("minecraft:jungle_button", state -> state.with(state.getBlockType().getProperty("face"), "WALL").with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType JUNGLE_DOOR = register("minecraft:jungle_door", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "lower").with(state.getBlockType().getProperty("hinge"), "left").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType JUNGLE_FENCE = register("minecraft:jungle_fence", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType JUNGLE_FENCE_GATE = register("minecraft:jungle_fence_gate", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("in_wall"), false).with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType JUNGLE_LEAVES = register("minecraft:jungle_leaves", state -> state.with(state.getBlockType().getProperty("distance"), 7).with(state.getBlockType().getProperty("persistent"), false)); + public static final BlockType JUNGLE_LOG = register("minecraft:jungle_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType JUNGLE_PLANKS = register("minecraft:jungle_planks"); + public static final BlockType JUNGLE_PRESSURE_PLATE = register("minecraft:jungle_pressure_plate", state -> state.with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType JUNGLE_SAPLING = register("minecraft:jungle_sapling", state -> state.with(state.getBlockType().getProperty("stage"), 0)); + public static final BlockType JUNGLE_SLAB = register("minecraft:jungle_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType JUNGLE_STAIRS = register("minecraft:jungle_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType JUNGLE_TRAPDOOR = register("minecraft:jungle_trapdoor", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false).with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType JUNGLE_WOOD = register("minecraft:jungle_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType KELP = register("minecraft:kelp", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType KELP_PLANT = register("minecraft:kelp_plant"); + public static final BlockType LADDER = register("minecraft:ladder", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType LAPIS_BLOCK = register("minecraft:lapis_block"); + public static final BlockType LAPIS_ORE = register("minecraft:lapis_ore"); + public static final BlockType LARGE_FERN = register("minecraft:large_fern", state -> state.with(state.getBlockType().getProperty("half"), "lower")); + public static final BlockType LAVA = register("minecraft:lava", state -> state.with(state.getBlockType().getProperty("level"), 0)); + public static final BlockType LEVER = register("minecraft:lever", state -> state.with(state.getBlockType().getProperty("face"), "WALL").with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType LIGHT_BLUE_BANNER = register("minecraft:light_blue_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType LIGHT_BLUE_BED = register("minecraft:light_blue_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType LIGHT_BLUE_CARPET = register("minecraft:light_blue_carpet"); + public static final BlockType LIGHT_BLUE_CONCRETE = register("minecraft:light_blue_concrete"); + public static final BlockType LIGHT_BLUE_CONCRETE_POWDER = register("minecraft:light_blue_concrete_powder"); + public static final BlockType LIGHT_BLUE_GLAZED_TERRACOTTA = register("minecraft:light_blue_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType LIGHT_BLUE_SHULKER_BOX = register("minecraft:light_blue_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType LIGHT_BLUE_STAINED_GLASS = register("minecraft:light_blue_stained_glass"); + public static final BlockType LIGHT_BLUE_STAINED_GLASS_PANE = register("minecraft:light_blue_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType LIGHT_BLUE_TERRACOTTA = register("minecraft:light_blue_terracotta"); + public static final BlockType LIGHT_BLUE_WALL_BANNER = register("minecraft:light_blue_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType LIGHT_BLUE_WOOL = register("minecraft:light_blue_wool"); + public static final BlockType LIGHT_GRAY_BANNER = register("minecraft:light_gray_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType LIGHT_GRAY_BED = register("minecraft:light_gray_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType LIGHT_GRAY_CARPET = register("minecraft:light_gray_carpet"); + public static final BlockType LIGHT_GRAY_CONCRETE = register("minecraft:light_gray_concrete"); + public static final BlockType LIGHT_GRAY_CONCRETE_POWDER = register("minecraft:light_gray_concrete_powder"); + public static final BlockType LIGHT_GRAY_GLAZED_TERRACOTTA = register("minecraft:light_gray_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType LIGHT_GRAY_SHULKER_BOX = register("minecraft:light_gray_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType LIGHT_GRAY_STAINED_GLASS = register("minecraft:light_gray_stained_glass"); + public static final BlockType LIGHT_GRAY_STAINED_GLASS_PANE = register("minecraft:light_gray_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType LIGHT_GRAY_TERRACOTTA = register("minecraft:light_gray_terracotta"); + public static final BlockType LIGHT_GRAY_WALL_BANNER = register("minecraft:light_gray_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType LIGHT_GRAY_WOOL = register("minecraft:light_gray_wool"); + public static final BlockType LIGHT_WEIGHTED_PRESSURE_PLATE = register("minecraft:light_weighted_pressure_plate", state -> state.with(state.getBlockType().getProperty("power"), 0)); + public static final BlockType LILAC = register("minecraft:lilac", state -> state.with(state.getBlockType().getProperty("half"), "lower")); + public static final BlockType LILY_PAD = register("minecraft:lily_pad"); + public static final BlockType LIME_BANNER = register("minecraft:lime_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType LIME_BED = register("minecraft:lime_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType LIME_CARPET = register("minecraft:lime_carpet"); + public static final BlockType LIME_CONCRETE = register("minecraft:lime_concrete"); + public static final BlockType LIME_CONCRETE_POWDER = register("minecraft:lime_concrete_powder"); + public static final BlockType LIME_GLAZED_TERRACOTTA = register("minecraft:lime_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType LIME_SHULKER_BOX = register("minecraft:lime_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType LIME_STAINED_GLASS = register("minecraft:lime_stained_glass"); + public static final BlockType LIME_STAINED_GLASS_PANE = register("minecraft:lime_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType LIME_TERRACOTTA = register("minecraft:lime_terracotta"); + public static final BlockType LIME_WALL_BANNER = register("minecraft:lime_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType LIME_WOOL = register("minecraft:lime_wool"); + public static final BlockType MAGENTA_BANNER = register("minecraft:magenta_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType MAGENTA_BED = register("minecraft:magenta_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType MAGENTA_CARPET = register("minecraft:magenta_carpet"); + public static final BlockType MAGENTA_CONCRETE = register("minecraft:magenta_concrete"); + public static final BlockType MAGENTA_CONCRETE_POWDER = register("minecraft:magenta_concrete_powder"); + public static final BlockType MAGENTA_GLAZED_TERRACOTTA = register("minecraft:magenta_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType MAGENTA_SHULKER_BOX = register("minecraft:magenta_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType MAGENTA_STAINED_GLASS = register("minecraft:magenta_stained_glass"); + public static final BlockType MAGENTA_STAINED_GLASS_PANE = register("minecraft:magenta_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType MAGENTA_TERRACOTTA = register("minecraft:magenta_terracotta"); + public static final BlockType MAGENTA_WALL_BANNER = register("minecraft:magenta_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType MAGENTA_WOOL = register("minecraft:magenta_wool"); + public static final BlockType MAGMA_BLOCK = register("minecraft:magma_block"); + public static final BlockType MELON = register("minecraft:melon"); + public static final BlockType MELON_STEM = register("minecraft:melon_stem", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType MOSSY_COBBLESTONE = register("minecraft:mossy_cobblestone"); + public static final BlockType MOSSY_COBBLESTONE_WALL = register("minecraft:mossy_cobblestone_wall", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("up"), true).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType MOSSY_STONE_BRICKS = register("minecraft:mossy_stone_bricks"); + public static final BlockType MOVING_PISTON = register("minecraft:moving_piston", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("type"), "normal")); + public static final BlockType MUSHROOM_STEM = register("minecraft:mushroom_stem", state -> state.with(state.getBlockType().getProperty("down"), true).with(state.getBlockType().getProperty("east"), true).with(state.getBlockType().getProperty("north"), true).with(state.getBlockType().getProperty("south"), true).with(state.getBlockType().getProperty("up"), true).with(state.getBlockType().getProperty("west"), true)); + public static final BlockType MYCELIUM = register("minecraft:mycelium", state -> state.with(state.getBlockType().getProperty("snowy"), false)); + public static final BlockType NETHER_BRICK_FENCE = register("minecraft:nether_brick_fence", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType NETHER_BRICK_SLAB = register("minecraft:nether_brick_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType NETHER_BRICK_STAIRS = register("minecraft:nether_brick_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType NETHER_BRICKS = register("minecraft:nether_bricks"); + public static final BlockType NETHER_PORTAL = register("minecraft:nether_portal", state -> state.with(state.getBlockType().getProperty("axis"), "x")); + public static final BlockType NETHER_QUARTZ_ORE = register("minecraft:nether_quartz_ore"); + public static final BlockType NETHER_WART = register("minecraft:nether_wart", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType NETHER_WART_BLOCK = register("minecraft:nether_wart_block"); + public static final BlockType NETHERRACK = register("minecraft:netherrack"); + public static final BlockType NOTE_BLOCK = register("minecraft:note_block", state -> state.with(state.getBlockType().getProperty("instrument"), "HARP").with(state.getBlockType().getProperty("note"), 0).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType OAK_BUTTON = register("minecraft:oak_button", state -> state.with(state.getBlockType().getProperty("face"), "WALL").with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType OAK_DOOR = register("minecraft:oak_door", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "lower").with(state.getBlockType().getProperty("hinge"), "left").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType OAK_FENCE = register("minecraft:oak_fence", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType OAK_FENCE_GATE = register("minecraft:oak_fence_gate", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("in_wall"), false).with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType OAK_LEAVES = register("minecraft:oak_leaves", state -> state.with(state.getBlockType().getProperty("distance"), 7).with(state.getBlockType().getProperty("persistent"), false)); + public static final BlockType OAK_LOG = register("minecraft:oak_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType OAK_PLANKS = register("minecraft:oak_planks"); + public static final BlockType OAK_PRESSURE_PLATE = register("minecraft:oak_pressure_plate", state -> state.with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType OAK_SAPLING = register("minecraft:oak_sapling", state -> state.with(state.getBlockType().getProperty("stage"), 0)); + public static final BlockType OAK_SLAB = register("minecraft:oak_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType OAK_STAIRS = register("minecraft:oak_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType OAK_TRAPDOOR = register("minecraft:oak_trapdoor", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false).with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType OAK_WOOD = register("minecraft:oak_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType OBSERVER = register("minecraft:observer", state -> state.with(state.getBlockType().getProperty("facing"), Direction.SOUTH).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType OBSIDIAN = register("minecraft:obsidian"); + public static final BlockType ORANGE_BANNER = register("minecraft:orange_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType ORANGE_BED = register("minecraft:orange_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType ORANGE_CARPET = register("minecraft:orange_carpet"); + public static final BlockType ORANGE_CONCRETE = register("minecraft:orange_concrete"); + public static final BlockType ORANGE_CONCRETE_POWDER = register("minecraft:orange_concrete_powder"); + public static final BlockType ORANGE_GLAZED_TERRACOTTA = register("minecraft:orange_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType ORANGE_SHULKER_BOX = register("minecraft:orange_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType ORANGE_STAINED_GLASS = register("minecraft:orange_stained_glass"); + public static final BlockType ORANGE_STAINED_GLASS_PANE = register("minecraft:orange_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType ORANGE_TERRACOTTA = register("minecraft:orange_terracotta"); + public static final BlockType ORANGE_TULIP = register("minecraft:orange_tulip"); + public static final BlockType ORANGE_WALL_BANNER = register("minecraft:orange_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType ORANGE_WOOL = register("minecraft:orange_wool"); + public static final BlockType OXEYE_DAISY = register("minecraft:oxeye_daisy"); + public static final BlockType PACKED_ICE = register("minecraft:packed_ice"); + public static final BlockType PEONY = register("minecraft:peony", state -> state.with(state.getBlockType().getProperty("half"), "lower")); + public static final BlockType PETRIFIED_OAK_SLAB = register("minecraft:petrified_oak_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType PINK_BANNER = register("minecraft:pink_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType PINK_BED = register("minecraft:pink_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType PINK_CARPET = register("minecraft:pink_carpet"); + public static final BlockType PINK_CONCRETE = register("minecraft:pink_concrete"); + public static final BlockType PINK_CONCRETE_POWDER = register("minecraft:pink_concrete_powder"); + public static final BlockType PINK_GLAZED_TERRACOTTA = register("minecraft:pink_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType PINK_SHULKER_BOX = register("minecraft:pink_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType PINK_STAINED_GLASS = register("minecraft:pink_stained_glass"); + public static final BlockType PINK_STAINED_GLASS_PANE = register("minecraft:pink_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType PINK_TERRACOTTA = register("minecraft:pink_terracotta"); + public static final BlockType PINK_TULIP = register("minecraft:pink_tulip"); + public static final BlockType PINK_WALL_BANNER = register("minecraft:pink_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType PINK_WOOL = register("minecraft:pink_wool"); + public static final BlockType PISTON = register("minecraft:piston", state -> state.with(state.getBlockType().getProperty("extended"), false).with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType PISTON_HEAD = register("minecraft:piston_head", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("short"), false).with(state.getBlockType().getProperty("type"), "normal")); + public static final BlockType PLAYER_HEAD = register("minecraft:player_head", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType PLAYER_WALL_HEAD = register("minecraft:player_wall_head", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType PODZOL = register("minecraft:podzol", state -> state.with(state.getBlockType().getProperty("snowy"), false)); + public static final BlockType POLISHED_ANDESITE = register("minecraft:polished_andesite"); + public static final BlockType POLISHED_DIORITE = register("minecraft:polished_diorite"); + public static final BlockType POLISHED_GRANITE = register("minecraft:polished_granite"); + public static final BlockType POPPY = register("minecraft:poppy"); + public static final BlockType POTATOES = register("minecraft:potatoes", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType POTTED_ACACIA_SAPLING = register("minecraft:potted_acacia_sapling"); + public static final BlockType POTTED_ALLIUM = register("minecraft:potted_allium"); + public static final BlockType POTTED_AZURE_BLUET = register("minecraft:potted_azure_bluet"); + public static final BlockType POTTED_BIRCH_SAPLING = register("minecraft:potted_birch_sapling"); + public static final BlockType POTTED_BLUE_ORCHID = register("minecraft:potted_blue_orchid"); + public static final BlockType POTTED_BROWN_MUSHROOM = register("minecraft:potted_brown_mushroom"); + public static final BlockType POTTED_CACTUS = register("minecraft:potted_cactus"); + public static final BlockType POTTED_DANDELION = register("minecraft:potted_dandelion"); + public static final BlockType POTTED_DARK_OAK_SAPLING = register("minecraft:potted_dark_oak_sapling"); + public static final BlockType POTTED_DEAD_BUSH = register("minecraft:potted_dead_bush"); + public static final BlockType POTTED_FERN = register("minecraft:potted_fern"); + public static final BlockType POTTED_JUNGLE_SAPLING = register("minecraft:potted_jungle_sapling"); + public static final BlockType POTTED_OAK_SAPLING = register("minecraft:potted_oak_sapling"); + public static final BlockType POTTED_ORANGE_TULIP = register("minecraft:potted_orange_tulip"); + public static final BlockType POTTED_OXEYE_DAISY = register("minecraft:potted_oxeye_daisy"); + public static final BlockType POTTED_PINK_TULIP = register("minecraft:potted_pink_tulip"); + public static final BlockType POTTED_POPPY = register("minecraft:potted_poppy"); + public static final BlockType POTTED_RED_MUSHROOM = register("minecraft:potted_red_mushroom"); + public static final BlockType POTTED_RED_TULIP = register("minecraft:potted_red_tulip"); + public static final BlockType POTTED_SPRUCE_SAPLING = register("minecraft:potted_spruce_sapling"); + public static final BlockType POTTED_WHITE_TULIP = register("minecraft:potted_white_tulip"); + public static final BlockType POWERED_RAIL = register("minecraft:powered_rail", state -> state.with(state.getBlockType().getProperty("powered"), false).with(state.getBlockType().getProperty("shape"), "north_south")); + public static final BlockType PRISMARINE = register("minecraft:prismarine"); + public static final BlockType PRISMARINE_BRICK_SLAB = register("minecraft:prismarine_brick_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType PRISMARINE_BRICK_STAIRS = register("minecraft:prismarine_brick_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType PRISMARINE_BRICKS = register("minecraft:prismarine_bricks"); + public static final BlockType PRISMARINE_SLAB = register("minecraft:prismarine_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType PRISMARINE_STAIRS = register("minecraft:prismarine_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType PUMPKIN = register("minecraft:pumpkin"); + public static final BlockType PUMPKIN_STEM = register("minecraft:pumpkin_stem", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType PURPLE_BANNER = register("minecraft:purple_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType PURPLE_BED = register("minecraft:purple_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType PURPLE_CARPET = register("minecraft:purple_carpet"); + public static final BlockType PURPLE_CONCRETE = register("minecraft:purple_concrete"); + public static final BlockType PURPLE_CONCRETE_POWDER = register("minecraft:purple_concrete_powder"); + public static final BlockType PURPLE_GLAZED_TERRACOTTA = register("minecraft:purple_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType PURPLE_SHULKER_BOX = register("minecraft:purple_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType PURPLE_STAINED_GLASS = register("minecraft:purple_stained_glass"); + public static final BlockType PURPLE_STAINED_GLASS_PANE = register("minecraft:purple_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType PURPLE_TERRACOTTA = register("minecraft:purple_terracotta"); + public static final BlockType PURPLE_WALL_BANNER = register("minecraft:purple_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType PURPLE_WOOL = register("minecraft:purple_wool"); + public static final BlockType PURPUR_BLOCK = register("minecraft:purpur_block"); + public static final BlockType PURPUR_PILLAR = register("minecraft:purpur_pillar", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType PURPUR_SLAB = register("minecraft:purpur_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType PURPUR_STAIRS = register("minecraft:purpur_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType QUARTZ_BLOCK = register("minecraft:quartz_block"); + public static final BlockType QUARTZ_PILLAR = register("minecraft:quartz_pillar", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType QUARTZ_SLAB = register("minecraft:quartz_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType QUARTZ_STAIRS = register("minecraft:quartz_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType RAIL = register("minecraft:rail", state -> state.with(state.getBlockType().getProperty("shape"), "north_south")); + public static final BlockType RED_BANNER = register("minecraft:red_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType RED_BED = register("minecraft:red_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType RED_CARPET = register("minecraft:red_carpet"); + public static final BlockType RED_CONCRETE = register("minecraft:red_concrete"); + public static final BlockType RED_CONCRETE_POWDER = register("minecraft:red_concrete_powder"); + public static final BlockType RED_GLAZED_TERRACOTTA = register("minecraft:red_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType RED_MUSHROOM = register("minecraft:red_mushroom"); + public static final BlockType RED_MUSHROOM_BLOCK = register("minecraft:red_mushroom_block", state -> state.with(state.getBlockType().getProperty("down"), true).with(state.getBlockType().getProperty("east"), true).with(state.getBlockType().getProperty("north"), true).with(state.getBlockType().getProperty("south"), true).with(state.getBlockType().getProperty("up"), true).with(state.getBlockType().getProperty("west"), true)); + public static final BlockType RED_NETHER_BRICKS = register("minecraft:red_nether_bricks"); + public static final BlockType RED_SAND = register("minecraft:red_sand"); + public static final BlockType RED_SANDSTONE = register("minecraft:red_sandstone"); + public static final BlockType RED_SANDSTONE_SLAB = register("minecraft:red_sandstone_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType RED_SANDSTONE_STAIRS = register("minecraft:red_sandstone_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType RED_SHULKER_BOX = register("minecraft:red_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType RED_STAINED_GLASS = register("minecraft:red_stained_glass"); + public static final BlockType RED_STAINED_GLASS_PANE = register("minecraft:red_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType RED_TERRACOTTA = register("minecraft:red_terracotta"); + public static final BlockType RED_TULIP = register("minecraft:red_tulip"); + public static final BlockType RED_WALL_BANNER = register("minecraft:red_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType RED_WOOL = register("minecraft:red_wool"); + public static final BlockType REDSTONE_BLOCK = register("minecraft:redstone_block"); + public static final BlockType REDSTONE_LAMP = register("minecraft:redstone_lamp", state -> state.with(state.getBlockType().getProperty("lit"), false)); + public static final BlockType REDSTONE_ORE = register("minecraft:redstone_ore", state -> state.with(state.getBlockType().getProperty("lit"), false)); + public static final BlockType REDSTONE_TORCH = register("minecraft:redstone_torch", state -> state.with(state.getBlockType().getProperty("lit"), true)); + public static final BlockType REDSTONE_WALL_TORCH = register("minecraft:redstone_wall_torch", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("lit"), true)); + public static final BlockType REDSTONE_WIRE = register("minecraft:redstone_wire", state -> state.with(state.getBlockType().getProperty("east"), "none").with(state.getBlockType().getProperty("north"), "none").with(state.getBlockType().getProperty("power"), 0).with(state.getBlockType().getProperty("south"), "none").with(state.getBlockType().getProperty("west"), "none")); + public static final BlockType REPEATER = register("minecraft:repeater", state -> state.with(state.getBlockType().getProperty("delay"), 1).with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("locked"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType REPEATING_COMMAND_BLOCK = register("minecraft:repeating_command_block", state -> state.with(state.getBlockType().getProperty("conditional"), false).with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType ROSE_BUSH = register("minecraft:rose_bush", state -> state.with(state.getBlockType().getProperty("half"), "lower")); + public static final BlockType SAND = register("minecraft:sand"); + public static final BlockType SANDSTONE = register("minecraft:sandstone"); + public static final BlockType SANDSTONE_SLAB = register("minecraft:sandstone_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType SANDSTONE_STAIRS = register("minecraft:sandstone_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType SEA_LANTERN = register("minecraft:sea_lantern"); + public static final BlockType SEA_PICKLE = register("minecraft:sea_pickle", state -> state.with(state.getBlockType().getProperty("pickles"), 1).with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType SEAGRASS = register("minecraft:seagrass"); + public static final BlockType SHULKER_BOX = register("minecraft:shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType SIGN = register("minecraft:sign", state -> state.with(state.getBlockType().getProperty("rotation"), 0).with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType SKELETON_SKULL = register("minecraft:skeleton_skull", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType SKELETON_WALL_SKULL = register("minecraft:skeleton_wall_skull", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType SLIME_BLOCK = register("minecraft:slime_block"); + public static final BlockType SMOOTH_QUARTZ = register("minecraft:smooth_quartz"); + public static final BlockType SMOOTH_RED_SANDSTONE = register("minecraft:smooth_red_sandstone"); + public static final BlockType SMOOTH_SANDSTONE = register("minecraft:smooth_sandstone"); + public static final BlockType SMOOTH_STONE = register("minecraft:smooth_stone"); + public static final BlockType SNOW = register("minecraft:snow", state -> state.with(state.getBlockType().getProperty("layers"), 1)); + public static final BlockType SNOW_BLOCK = register("minecraft:snow_block"); + public static final BlockType SOUL_SAND = register("minecraft:soul_sand"); + public static final BlockType SPAWNER = register("minecraft:spawner"); + public static final BlockType SPONGE = register("minecraft:sponge"); + public static final BlockType SPRUCE_BUTTON = register("minecraft:spruce_button", state -> state.with(state.getBlockType().getProperty("face"), "WALL").with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType SPRUCE_DOOR = register("minecraft:spruce_door", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "lower").with(state.getBlockType().getProperty("hinge"), "left").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType SPRUCE_FENCE = register("minecraft:spruce_fence", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType SPRUCE_FENCE_GATE = register("minecraft:spruce_fence_gate", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("in_wall"), false).with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType SPRUCE_LEAVES = register("minecraft:spruce_leaves", state -> state.with(state.getBlockType().getProperty("distance"), 7).with(state.getBlockType().getProperty("persistent"), false)); + public static final BlockType SPRUCE_LOG = register("minecraft:spruce_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType SPRUCE_PLANKS = register("minecraft:spruce_planks"); + public static final BlockType SPRUCE_PRESSURE_PLATE = register("minecraft:spruce_pressure_plate", state -> state.with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType SPRUCE_SAPLING = register("minecraft:spruce_sapling", state -> state.with(state.getBlockType().getProperty("stage"), 0)); + public static final BlockType SPRUCE_SLAB = register("minecraft:spruce_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType SPRUCE_STAIRS = register("minecraft:spruce_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType SPRUCE_TRAPDOOR = register("minecraft:spruce_trapdoor", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("open"), false).with(state.getBlockType().getProperty("powered"), false).with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType SPRUCE_WOOD = register("minecraft:spruce_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STICKY_PISTON = register("minecraft:sticky_piston", state -> state.with(state.getBlockType().getProperty("extended"), false).with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType STONE = register("minecraft:stone"); + public static final BlockType STONE_BRICK_SLAB = register("minecraft:stone_brick_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType STONE_BRICK_STAIRS = register("minecraft:stone_brick_stairs", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("half"), "bottom").with(state.getBlockType().getProperty("shape"), "straight").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType STONE_BRICKS = register("minecraft:stone_bricks"); + public static final BlockType STONE_BUTTON = register("minecraft:stone_button", state -> state.with(state.getBlockType().getProperty("face"), "WALL").with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType STONE_PRESSURE_PLATE = register("minecraft:stone_pressure_plate", state -> state.with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType STONE_SLAB = register("minecraft:stone_slab", state -> state.with(state.getBlockType().getProperty("type"), "bottom").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType STRIPPED_ACACIA_LOG = register("minecraft:stripped_acacia_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRIPPED_ACACIA_WOOD = register("minecraft:stripped_acacia_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRIPPED_BIRCH_LOG = register("minecraft:stripped_birch_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRIPPED_BIRCH_WOOD = register("minecraft:stripped_birch_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRIPPED_DARK_OAK_LOG = register("minecraft:stripped_dark_oak_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRIPPED_DARK_OAK_WOOD = register("minecraft:stripped_dark_oak_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRIPPED_JUNGLE_LOG = register("minecraft:stripped_jungle_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRIPPED_JUNGLE_WOOD = register("minecraft:stripped_jungle_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRIPPED_OAK_LOG = register("minecraft:stripped_oak_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRIPPED_OAK_WOOD = register("minecraft:stripped_oak_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRIPPED_SPRUCE_LOG = register("minecraft:stripped_spruce_log", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRIPPED_SPRUCE_WOOD = register("minecraft:stripped_spruce_wood", state -> state.with(state.getBlockType().getProperty("axis"), "y")); + public static final BlockType STRUCTURE_BLOCK = register("minecraft:structure_block", state -> state.with(state.getBlockType().getProperty("mode"), "SAVE")); + public static final BlockType STRUCTURE_VOID = register("minecraft:structure_void"); + public static final BlockType SUGAR_CANE = register("minecraft:sugar_cane", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType SUNFLOWER = register("minecraft:sunflower", state -> state.with(state.getBlockType().getProperty("half"), "lower")); + public static final BlockType TALL_GRASS = register("minecraft:tall_grass", state -> state.with(state.getBlockType().getProperty("half"), "lower")); + public static final BlockType TALL_SEAGRASS = register("minecraft:tall_seagrass", state -> state.with(state.getBlockType().getProperty("half"), "lower")); + public static final BlockType TERRACOTTA = register("minecraft:terracotta"); + public static final BlockType TNT = register("minecraft:tnt", state -> state.with(state.getBlockType().getProperty("unstable"), false)); + public static final BlockType TORCH = register("minecraft:torch"); + public static final BlockType TRAPPED_CHEST = register("minecraft:trapped_chest", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("type"), "SINGLE").with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType TRIPWIRE = register("minecraft:tripwire", state -> state.with(state.getBlockType().getProperty("attached"), false).with(state.getBlockType().getProperty("disarmed"), false).with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("powered"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType TRIPWIRE_HOOK = register("minecraft:tripwire_hook", state -> state.with(state.getBlockType().getProperty("attached"), false).with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("powered"), false)); + public static final BlockType TUBE_CORAL = register("minecraft:tube_coral", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType TUBE_CORAL_BLOCK = register("minecraft:tube_coral_block"); + public static final BlockType TUBE_CORAL_FAN = register("minecraft:tube_coral_fan", state -> state.with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType TUBE_CORAL_WALL_FAN = register("minecraft:tube_coral_wall_fan", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), true)); + public static final BlockType TURTLE_EGG = register("minecraft:turtle_egg", state -> state.with(state.getBlockType().getProperty("eggs"), 1).with(state.getBlockType().getProperty("hatch"), 0)); + public static final BlockType VINE = register("minecraft:vine", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("up"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType VOID_AIR = register("minecraft:void_air"); + public static final BlockType WALL_SIGN = register("minecraft:wall_sign", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("waterlogged"), false)); + public static final BlockType WALL_TORCH = register("minecraft:wall_torch", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType WATER = register("minecraft:water", state -> state.with(state.getBlockType().getProperty("level"), 0)); + public static final BlockType WET_SPONGE = register("minecraft:wet_sponge"); + public static final BlockType WHEAT = register("minecraft:wheat", state -> state.with(state.getBlockType().getProperty("age"), 0)); + public static final BlockType WHITE_BANNER = register("minecraft:white_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType WHITE_BED = register("minecraft:white_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType WHITE_CARPET = register("minecraft:white_carpet"); + public static final BlockType WHITE_CONCRETE = register("minecraft:white_concrete"); + public static final BlockType WHITE_CONCRETE_POWDER = register("minecraft:white_concrete_powder"); + public static final BlockType WHITE_GLAZED_TERRACOTTA = register("minecraft:white_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType WHITE_SHULKER_BOX = register("minecraft:white_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType WHITE_STAINED_GLASS = register("minecraft:white_stained_glass"); + public static final BlockType WHITE_STAINED_GLASS_PANE = register("minecraft:white_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType WHITE_TERRACOTTA = register("minecraft:white_terracotta"); + public static final BlockType WHITE_TULIP = register("minecraft:white_tulip"); + public static final BlockType WHITE_WALL_BANNER = register("minecraft:white_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType WHITE_WOOL = register("minecraft:white_wool"); + public static final BlockType WITHER_SKELETON_SKULL = register("minecraft:wither_skeleton_skull", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType WITHER_SKELETON_WALL_SKULL = register("minecraft:wither_skeleton_wall_skull", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType YELLOW_BANNER = register("minecraft:yellow_banner", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType YELLOW_BED = register("minecraft:yellow_bed", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH).with(state.getBlockType().getProperty("occupied"), false).with(state.getBlockType().getProperty("part"), "foot")); + public static final BlockType YELLOW_CARPET = register("minecraft:yellow_carpet"); + public static final BlockType YELLOW_CONCRETE = register("minecraft:yellow_concrete"); + public static final BlockType YELLOW_CONCRETE_POWDER = register("minecraft:yellow_concrete_powder"); + public static final BlockType YELLOW_GLAZED_TERRACOTTA = register("minecraft:yellow_glazed_terracotta", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType YELLOW_SHULKER_BOX = register("minecraft:yellow_shulker_box", state -> state.with(state.getBlockType().getProperty("facing"), Direction.UP)); + public static final BlockType YELLOW_STAINED_GLASS = register("minecraft:yellow_stained_glass"); + public static final BlockType YELLOW_STAINED_GLASS_PANE = register("minecraft:yellow_stained_glass_pane", state -> state.with(state.getBlockType().getProperty("east"), false).with(state.getBlockType().getProperty("north"), false).with(state.getBlockType().getProperty("south"), false).with(state.getBlockType().getProperty("waterlogged"), false).with(state.getBlockType().getProperty("west"), false)); + public static final BlockType YELLOW_TERRACOTTA = register("minecraft:yellow_terracotta"); + public static final BlockType YELLOW_WALL_BANNER = register("minecraft:yellow_wall_banner", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); + public static final BlockType YELLOW_WOOL = register("minecraft:yellow_wool"); + public static final BlockType ZOMBIE_HEAD = register("minecraft:zombie_head", state -> state.with(state.getBlockType().getProperty("rotation"), 0)); + public static final BlockType ZOMBIE_WALL_HEAD = register("minecraft:zombie_wall_head", state -> state.with(state.getBlockType().getProperty("facing"), Direction.NORTH)); - ; + private static BlockType register(String id) { + return register(new BlockType(id)); + } + + private static BlockType register(String id, Function values) { + return register(new BlockType(id, values)); + } + + public static BlockType register(BlockType type) { + if(sortedRegistry == null) { + sortedRegistry = new ArrayList<>(); + stateList = new ArrayList<>(); + $NAMESPACES = new LinkedHashSet<>(); + BIT_OFFSET = MathMan.log2nlz(WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBlockRegistry().registerBlocks().size()); + BIT_MASK = ((1 << BIT_OFFSET) - 1); + } + if(!sortedRegistry.contains(type))sortedRegistry.add(type); + return internalRegister(type, sortedRegistry.indexOf(type)); + } + + private static ArrayList sortedRegistry; + private static ArrayList stateList; + public static BlockType[] values; + public static BlockState[] states; + private static Set $NAMESPACES; + @Deprecated public static int BIT_OFFSET; // Used internally + @Deprecated public static int BIT_MASK; // Used internally + + private static BlockType internalRegister(BlockType blockType, final int internalId) { + init(blockType, blockType.getId(), internalId, stateList); + if(BlockType.REGISTRY.get(blockType.getId()) == null) BlockType.REGISTRY.register(blockType.getId(), blockType); + $NAMESPACES.add(blockType.getNamespace()); + values = sortedRegistry.toArray(new BlockType[sortedRegistry.size()]); + states = stateList.toArray(new BlockState[stateList.size()]); + return blockType; + } + + private static void init(BlockType type, String id, int internalId, ArrayList states) { + try { + type.setSettings(new Settings(type, id, internalId, states)); + states.addAll(type.updateStates()); + type.setStates(states); + } catch (Throwable e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + /* ----------------------------------------------------- - Instance + Settings ----------------------------------------------------- */ - private final static class Settings { - private final int internalId; - private final ItemTypes itemType; - private final BlockState defaultState; - private final AbstractProperty[] propertiesMapArr; - private final AbstractProperty[] propertiesArr; - private final List propertiesList; - private final Map propertiesMap; - private final Set propertiesSet; - private final BlockMaterial blockMaterial; - private final int permutations; - private int[] stateOrdinals; + public final static class Settings { + protected final int internalId; + protected final ItemType itemType; + protected BlockState defaultState; + protected final AbstractProperty[] propertiesMapArr; + protected final AbstractProperty[] propertiesArr; + protected final List> propertiesList; + protected final Map> propertiesMap; + protected final Set> propertiesSet; + protected final BlockMaterial blockMaterial; + protected final int permutations; + protected int[] stateOrdinals; + protected ArrayList localStates; - Settings(BlockTypes type, String id, int internalId, List states) { + Settings(BlockType type, String id, int internalId, List states) { this.internalId = internalId; - String propertyString = null; - int propI = id.indexOf('['); - if (propI != -1) { - propertyString = id.substring(propI + 1, id.length() - 1); - } int maxInternalStateId = 0; - Map properties = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBlockRegistry().getProperties(type); + Map> properties = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBlockRegistry().getProperties(type); if (!properties.isEmpty()) { // Ensure the properties are registered int maxOrdinal = 0; @@ -701,12 +747,12 @@ public enum BlockTypes implements BlockType { this.propertiesMapArr = new AbstractProperty[maxOrdinal + 1]; int prop_arr_i = 0; this.propertiesArr = new AbstractProperty[properties.size()]; - HashMap propMap = new HashMap<>(); + HashMap> propMap = new HashMap<>(); int bitOffset = 0; - for (Map.Entry entry : properties.entrySet()) { + for (Map.Entry> entry : properties.entrySet()) { PropertyKey key = PropertyKey.getOrCreate(entry.getKey()); - AbstractProperty property = ((AbstractProperty) entry.getValue()).withOffset(bitOffset); + AbstractProperty property = ((AbstractProperty) entry.getValue()).withOffset(bitOffset); this.propertiesMapArr[key.ordinal()] = property; this.propertiesArr[prop_arr_i++] = property; propMap.put(entry.getKey(), property); @@ -725,69 +771,30 @@ public enum BlockTypes implements BlockType { this.propertiesSet = Collections.emptySet(); } this.permutations = maxInternalStateId; + this.localStates = new ArrayList<>(); this.blockMaterial = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBlockRegistry().getMaterial(type); this.itemType = ItemTypes.get(type); - + if (!propertiesList.isEmpty()) { this.stateOrdinals = generateStateOrdinals(internalId, states.size(), maxInternalStateId, propertiesList); for (int propId = 0; propId < this.stateOrdinals.length; propId++) { int ordinal = this.stateOrdinals[propId]; if (ordinal != -1) { int stateId = internalId + (propId << BlockTypes.BIT_OFFSET); - states.add(new BlockStateImpl(type, stateId, ordinal)); + this.localStates.add(new BlockStateImpl(type, stateId, ordinal)); } } - int defaultPropId = parseProperties(propertyString, propertiesMap) >> BlockTypes.BIT_OFFSET; - this.defaultState = states.get(this.stateOrdinals[defaultPropId]); + + this.defaultState = this.localStates.get(this.stateOrdinals[internalId >> BlockTypes.BIT_OFFSET] - states.size()); } else { - this.defaultState = new BlockStateImpl(type, internalId, states.size()); - states.add(this.defaultState); + this.defaultState = new BlockStateImpl(id.contains("minecraft:__reserved__") ? new BlockType("minecraft:air") : type, internalId, states.size()); + this.localStates.add(this.defaultState); } } - - private int parseProperties(String properties, Map propertyMap) { - int id = internalId; - for (String keyPair : properties.split(",")) { - String[] split = keyPair.split("="); - String name = split[0]; - String value = split[1]; - AbstractProperty btp = propertyMap.get(name); - id = btp.modify(id, btp.getValueFor(value)); - } - return id; - } } - - private final String id; - private final Settings settings; - - BlockTypes() { - if (name().indexOf(':') == -1) id = "minecraft:" + name().toLowerCase(); - else id = name().toLowerCase(); - settings = null; - } - - private void init(String id, int internalId, List states) { - try { - if (getId() == null) { - String name = (name().indexOf(':') == -1 ? "minecraft:" : "") + name().toLowerCase(); - ReflectionUtils.setFailsafeFieldValue(BlockTypes.class.getDeclaredField("id"), this, name); - } - Settings settings = new Settings(this, id, internalId, states); - ReflectionUtils.setFailsafeFieldValue(BlockTypes.class.getDeclaredField("settings"), this, settings); - } catch (Throwable e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - public BlockState withPropertyId(int propertyId) { - if (settings.stateOrdinals == null) return settings.defaultState; - return states[settings.stateOrdinals[propertyId]]; - } - - private static int[] generateStateOrdinals(int internalId, int ordinal, int maxStateId, List props) { + + private static int[] generateStateOrdinals(int internalId, int ordinal, int maxStateId, List> props) { if (props.isEmpty()) return null; int[] result = new int[maxStateId + 1]; Arrays.fill(result, -1); @@ -817,256 +824,12 @@ public enum BlockTypes implements BlockType { return result; } - /** - * Slow - * @return collection of states - */ - @Deprecated - public List getAllStates() { - if (settings.stateOrdinals == null) return Collections.singletonList(getDefaultState()); - return IntStream.of(settings.stateOrdinals).filter(i -> i != -1).mapToObj(i -> states[i]).collect(Collectors.toList()); - } - - public BlockState getState(Map, Object> key) { - int id = getInternalId(); - for (Map.Entry, Object> iter : key.entrySet()) { - Property prop = iter.getKey(); - Object value = iter.getValue(); - - /* - * TODO: - * This is likely wrong. The only place this seems to currently (Dec 23 2018) - * be invoked is via ForgeWorld, and value is a String when invoked there... - */ - AbstractProperty btp = settings.propertiesMap.get(prop.getName()); - checkArgument(btp != null, "%s has no property named %s", this, prop.getName()); - id = btp.modify(id, btp.getValueFor((String)value)); - } - return withStateId(id); - } - - @Deprecated - public int getMaxStateId() { - return settings.permutations; - } - - @Override - public boolean apply(Extent extent, Vector get, Vector set) throws WorldEditException { - return extent.setBlock(set, this.settings.defaultState); - } - - public Mask toMask(Extent extent) { - return new SingleBlockTypeMask(extent, this); - } - - /** - * Gets the ID of this block. - * - * @return The id - */ - public String getId() { - return this.id; - } - - /** - * Gets the name of this block, or the ID if the name cannot be found. - * - * @return The name, or ID - */ - public String getName() { - BundledBlockData.BlockEntry entry = BundledBlockData.getInstance().findById(this.id); - if (entry == null) { - return getId(); - } else { - return entry.localizedName; - } - } - - @Deprecated - public BlockState withStateId(int internalStateId) { - return this.withPropertyId(internalStateId >> BlockTypes.BIT_OFFSET); - } - - /** - * Properties string in the form property1=foo,prop2=bar - * @param properties - * @return - */ - public BlockState withProperties(String properties) { - int id = getInternalId(); - for (String keyPair : properties.split(",")) { - String[] split = keyPair.split("="); - String name = split[0]; - String value = split[1]; - AbstractProperty btp = settings.propertiesMap.get(name); - id = btp.modify(id, btp.getValueFor(value)); - } - return withStateId(id); - } - - /** - * Gets the properties of this BlockType in a key->property mapping. - * - * @return The properties map - */ - @Deprecated - public Map getPropertyMap() { - return this.settings.propertiesMap; - } - - /** - * Gets the properties of this BlockType. - * - * @return the properties - */ - @Deprecated - public List getProperties() { - return this.settings.propertiesList; - } - - @Deprecated - public Set getPropertiesSet() { - return this.settings.propertiesSet; - } - - /** - * Gets a property by name. - * - * @param name The name - * @return The property - */ - @Deprecated - public Property getProperty(String name) { - return this.settings.propertiesMap.get(name); - } - - public boolean hasProperty(PropertyKey key) { - int ordinal = key.ordinal(); - return this.settings.propertiesMapArr.length > ordinal ? this.settings.propertiesMapArr[ordinal] != null : false; - } - - public Property getProperty(PropertyKey key) { - try { - return this.settings.propertiesMapArr[key.ordinal()]; - } catch (IndexOutOfBoundsException ignore) { - return null; - } - } - - /** - * Gets the default state of this block type. - * - * @return The default state - */ - public BlockState getDefaultState() { - return this.settings.defaultState; - } - - /** - * Gets whether this block type has an item representation. - * - * @return If it has an item - */ - public boolean hasItemType() { - return getItemType() != null; - } - - /** - * Gets the item representation of this block type, if it exists. - * - * @return The item representation - */ - @Nullable - public ItemType getItemType() { - return settings.itemType; - } - - /** - * Get the material for this BlockType. - * - * @return The material - */ - public BlockMaterial getMaterial() { - return this.settings.blockMaterial; - } - - /** - * The internal index of this type. - * - * This number is not necessarily consistent across restarts. - * - * @return internal id - */ - public int getInternalId() { - return this.settings.internalId; - } - - @Override - public String toString() { - return getId(); - } - - /* - ----------------------------------------------------- - Static Initializer - ----------------------------------------------------- - */ - - @Deprecated public static final int BIT_OFFSET; // Used internally - @Deprecated public static final int BIT_MASK; // Used internally - - private static final Map $REGISTRY = new HashMap<>(); - private static int $LENGTH; - private static int $STATE_INDEX; - - public static final BlockTypes[] values; - public static final BlockState[] states; - - private static final Set $NAMESPACES = new LinkedHashSet(); - - static { - try { - Collection blocks = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBlockRegistry().registerBlocks(); - Map blockMap = blocks.stream().collect(Collectors.toMap(item -> item.charAt(item.length() - 1) == ']' ? item.substring(0, item.indexOf('[')) : item, item -> item)); - - BlockTypes[] oldValues = BlockTypes.values(); - $LENGTH = oldValues.length; - int size = blockMap.size(); - for (BlockTypes type : oldValues) { - if (!blockMap.containsKey(type.getId())) { - type.init(type.getId(), 0, new ArrayList<>()); - if (type != __RESERVED__) Fawe.debug("Invalid block registered " + type.getId()); - size++; - } - if (type != __RESERVED__) { - $REGISTRY.put(type.name().toLowerCase(), type); - } - } - - BIT_OFFSET = MathMan.log2nlz(size); - BIT_MASK = ((1 << BIT_OFFSET) - 1); - - LinkedHashSet newValues = new LinkedHashSet<>(Arrays.asList(oldValues)); - ArrayList stateList = new ArrayList<>(); - for (String block : blocks) { - BlockTypes registered = register(block, stateList); - if (!newValues.contains(registered)) newValues.add(registered); - } - // Cache the values - values = newValues.toArray(new BlockTypes[newValues.size()]); - states = stateList.toArray(new BlockState[stateList.size()]); - } catch (Throwable e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - public static BlockTypes parse(final String type) throws InputParseException { + public static BlockType parse(final String type) throws InputParseException { final String inputLower = type.toLowerCase(); String input = inputLower; if (!input.split("\\[", 2)[0].contains(":")) input = "minecraft:" + input; - BlockTypes result = $REGISTRY.get(input); + BlockType result = BlockType.REGISTRY.get(input); if (result != null) return result; try { @@ -1082,61 +845,35 @@ public enum BlockTypes implements BlockType { ); } - private static BlockTypes register(final String id, List states) { - // Get the enum name (remove namespace if minecraft:) - int propStart = id.indexOf('['); - String typeName = id.substring(0, propStart == -1 ? id.length() : propStart); - String enumName = (typeName.startsWith("minecraft:") ? typeName.substring(10) : typeName).toUpperCase(); - // Check existing - BlockTypes existing = null; - try { - existing = valueOf(enumName.toUpperCase()); - } catch (IllegalArgumentException ignore) {} - if (existing == null) { - Fawe.debug("Registering block " + enumName); - existing = ReflectionUtils.addEnum(BlockTypes.class, enumName); - } - int internalId = existing.ordinal(); - if (internalId == 0 && existing != __RESERVED__) { - internalId = $LENGTH++; - } - existing.init(id, internalId, states); - // register states - if (typeName.startsWith("minecraft:")) $REGISTRY.put(typeName.substring(10), existing); - $REGISTRY.put(typeName, existing); - String nameSpace = typeName.substring(0, typeName.indexOf(':')); - $NAMESPACES.add(nameSpace); - return existing; - } - public static Set getNameSpaces() { return $NAMESPACES; } - public static final @Nullable BlockTypes get(final String id) { - return $REGISTRY.get(id); - } + public static final @Nullable BlockType get(final String id) { + return BlockType.REGISTRY.get(id.toLowerCase()); + } - public static final @Nullable BlockTypes get(final CharSequence id) { - return $REGISTRY.get(id); - } + public static final @Nullable BlockType get(final CharSequence id) { + return BlockType.REGISTRY.get(id.toString().toLowerCase()); + } @Deprecated - public static final BlockTypes get(final int ordinal) { + public static final BlockType get(final int ordinal) { return values[ordinal]; } @Deprecated - public static final BlockTypes getFromStateId(final int internalStateId) { + public static final BlockType getFromStateId(final int internalStateId) { return values[internalStateId & BIT_MASK]; } @Deprecated - public static final BlockTypes getFromStateOrdinal(final int internalStateOrdinal) { + public static final BlockType getFromStateOrdinal(final int internalStateOrdinal) { return states[internalStateOrdinal].getBlockType(); } public static int size() { return values.length; } + } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/FuzzyBlockState.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/FuzzyBlockState.java new file mode 100644 index 000000000..edbd65243 --- /dev/null +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/block/FuzzyBlockState.java @@ -0,0 +1,145 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.world.block; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.sk89q.worldedit.registry.state.Property; + +import java.util.HashMap; +import java.util.Map; + +/** + * A Fuzzy BlockState. Used for partial matching. + * + * Immutable, construct with {@link FuzzyBlockState.Builder}. + */ +public class FuzzyBlockState extends BlockState { + + FuzzyBlockState(BlockType blockType) { + super(blockType); + } + + private FuzzyBlockState(BlockType blockType, Map, Object> values) { + this(blockType); + for (Map.Entry, Object> entry : values.entrySet()) { +// setState(entry.getKey(), entry.getValue()); + with((Property)entry.getKey(), entry.getValue()); + } + } + + /** + * Gets a full BlockState from this fuzzy one, filling in + * properties with default values where necessary. + * + * @return The full BlockState + */ + public BlockState getFullState() { + BlockState state = getBlockType().getDefaultState(); + for (Map.Entry, Object> entry : getStates().entrySet()) { + @SuppressWarnings("unchecked") + Property objKey = (Property) entry.getKey(); + state = state.with(objKey, entry.getValue()); + } + return getBlockType().getDefaultState(); + } + + /** + * Gets an instance of a builder. + * + * @return The builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Builder for FuzzyBlockState + */ + public static class Builder { + private BlockType type; + private Map, Object> values = new HashMap<>(); + + /** + * The type of the Fuzzy BlockState + * + * @param type The type + * @return The builder, for chaining + */ + public Builder type(BlockType type) { + checkNotNull(type); + this.type = type; + return this; + } + + /** + * The type of the Fuzzy BlockState + * + * @param state The state + * @return The builder, for chaining + */ + public Builder type(BlockState state) { + checkNotNull(state); + this.type = state.getBlockType(); + return this; + } + + /** + * Adds a property to the fuzzy BlockState + * + * @param property The property + * @param value The value + * @param The property type + * @return The builder, for chaining + */ + public Builder withProperty(Property property, V value) { + checkNotNull(property); + checkNotNull(value); + checkNotNull(type, "The type must be set before the properties!"); + type.getProperty(property.getName()); // Verify the property is valid for this type + values.put(property, value); + return this; + } + + /** + * Builds a FuzzyBlockState from this builder. + * + * @return The fuzzy BlockState + */ + public FuzzyBlockState build() { + checkNotNull(type); + if (values.isEmpty()) { + return type.getFuzzyMatcher(); + } + return new FuzzyBlockState(type, values); + } + + /** + * Resets the builder. + * + * @return The builder, for chaining + */ + public Builder reset() { + this.type = null; + this.values.clear(); + return this; + } + } +} \ 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 cfca55233..2710fddd0 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 @@ -26,14 +26,14 @@ import com.sk89q.jnbt.IntTag; import com.sk89q.jnbt.ListTag; import com.sk89q.jnbt.NBTUtils; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.blocks.BaseBlock; + +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.DataException; import com.sk89q.worldedit.world.World; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.registry.LegacyMapper; import com.sk89q.worldedit.world.storage.InvalidFormatException; @@ -52,7 +52,7 @@ public class AnvilChunk implements Chunk { private int rootX; private int rootZ; - private Map> tileEntities; + private Map> tileEntities; /** * Construct the chunk with a compound tag. @@ -119,10 +119,10 @@ public class AnvilChunk implements Chunk { } } - private int getBlockID(Vector position) throws DataException { - int x = position.getBlockX() - rootX * 16; - int y = position.getBlockY(); - int z = position.getBlockZ() - rootZ * 16; + private int getBlockID(BlockVector3 position) throws DataException { + int x = position.getX() - rootX * 16; + int y = position.getY(); + int z = position.getZ() - rootZ * 16; int section = y >> 4; if (section < 0 || section >= blocks.length) { @@ -152,10 +152,10 @@ public class AnvilChunk implements Chunk { } } - private int getBlockData(Vector position) throws DataException { - int x = position.getBlockX() - rootX * 16; - int y = position.getBlockY(); - int z = position.getBlockZ() - rootZ * 16; + private int getBlockData(BlockVector3 position) throws DataException { + int x = position.getX() - rootX * 16; + int y = position.getY(); + int z = position.getZ() - rootZ * 16; int section = y >> 4; int yIndex = y & 0x0F; @@ -225,7 +225,7 @@ public class AnvilChunk implements Chunk { values.put(entry.getKey(), entry.getValue()); } - BlockVector vec = new BlockVector(x, y, z); + BlockVector3 vec = BlockVector3.at(x, y, z); tileEntities.put(vec, values); } } @@ -240,12 +240,12 @@ public class AnvilChunk implements Chunk { * @throws DataException thrown if there is a data error */ @Nullable - private CompoundTag getBlockTileEntity(Vector position) throws DataException { + private CompoundTag getBlockTileEntity(BlockVector3 position) throws DataException { if (tileEntities == null) { populateTileEntities(); } - Map values = tileEntities.get(new BlockVector(position)); + Map values = tileEntities.get(position); if (values == null) { return null; } @@ -254,22 +254,22 @@ public class AnvilChunk implements Chunk { } @Override - public BlockStateHolder getBlock(Vector position) throws DataException { + public BaseBlock getBlock(BlockVector3 position) throws DataException { int id = getBlockID(position); int data = getBlockData(position); BlockState state = LegacyMapper.getInstance().getBlockFromLegacy(id, data); if (state == null) { WorldEdit.logger.warning("Unknown legacy block " + id + ":" + data + " found when loading legacy anvil chunk."); - return BlockTypes.AIR.getDefaultState(); + return BlockTypes.AIR.getDefaultState().toBaseBlock(); } if (state.getMaterial().hasContainer()) { CompoundTag tileEntity = getBlockTileEntity(position); if (tileEntity != null) { - return new BaseBlock(state, tileEntity); + return state.toBaseBlock(tileEntity); } } - return state; + return state.toBaseBlock(); } } 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 f5af9bf58..c4d2eb939 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 @@ -26,13 +26,12 @@ import com.sk89q.jnbt.ListTag; import com.sk89q.jnbt.LongArrayTag; import com.sk89q.jnbt.NBTUtils; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; + +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.world.DataException; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.storage.InvalidFormatException; @@ -53,7 +52,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. @@ -202,7 +201,7 @@ public class AnvilChunk13 implements Chunk { values.put(entry.getKey(), entry.getValue()); } - BlockVector vec = new BlockVector(x, y, z); + BlockVector3 vec = BlockVector3.at(x, y, z); tileEntities.put(vec, values); } } @@ -217,12 +216,12 @@ public class AnvilChunk13 implements Chunk { * @throws DataException thrown if there is a data error */ @Nullable - private CompoundTag getBlockTileEntity(Vector position) throws DataException { + private CompoundTag getBlockTileEntity(BlockVector3 position) throws DataException { if (tileEntities == null) { populateTileEntities(); } - Map values = tileEntities.get(new BlockVector(position)); + Map values = tileEntities.get(position); if (values == null) { return null; } @@ -231,10 +230,10 @@ public class AnvilChunk13 implements Chunk { } @Override - public BlockStateHolder getBlock(Vector position) throws DataException { - int x = position.getBlockX() - rootX * 16; - int y = position.getBlockY(); - int z = position.getBlockZ() - rootZ * 16; + public BaseBlock getBlock(BlockVector3 position) throws DataException { + int x = position.getX() - rootX * 16; + int y = position.getY(); + int z = position.getZ() - rootZ * 16; int section = y >> 4; int yIndex = y & 0x0F; @@ -249,7 +248,8 @@ public class AnvilChunk13 implements Chunk { CompoundTag tileEntity = getBlockTileEntity(position); if (tileEntity != null) return new BaseBlock(state, tileEntity); } - return state; + + return state.toBaseBlock(); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/Chunk.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/Chunk.java index 2f261570e..6987622d3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/Chunk.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/Chunk.java @@ -19,15 +19,16 @@ package com.sk89q.worldedit.world.chunk; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.DataException; -import com.sk89q.worldedit.world.block.BlockStateHolder; +import com.sk89q.worldedit.world.block.BaseBlock; /** * A 16 by 16 block chunk. */ public interface Chunk { - + /** * Get a block; * @@ -35,6 +36,6 @@ public interface Chunk { * @return block the block * @throws DataException thrown on data error */ - BlockStateHolder getBlock(Vector position) throws DataException; + BaseBlock getBlock(BlockVector3 position) throws DataException; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/OldChunk.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/OldChunk.java index 7e5b00e7f..add26e1c0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/OldChunk.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/OldChunk.java @@ -25,14 +25,12 @@ import com.sk89q.jnbt.IntTag; import com.sk89q.jnbt.ListTag; import com.sk89q.jnbt.NBTUtils; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.BlockVector; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.DataException; import com.sk89q.worldedit.world.World; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; -import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.registry.LegacyMapper; import com.sk89q.worldedit.world.storage.InvalidFormatException; @@ -52,7 +50,7 @@ public class OldChunk implements Chunk { private int rootX; private int rootZ; - private Map> tileEntities; + private Map> tileEntities; /** * Construct the chunk with a compound tag. @@ -128,7 +126,7 @@ public class OldChunk implements Chunk { values.put(entry.getKey(), entry.getValue()); } - BlockVector vec = new BlockVector(x, y, z); + BlockVector3 vec = BlockVector3.at(x, y, z); tileEntities.put(vec, values); } } @@ -142,12 +140,12 @@ public class OldChunk implements Chunk { * @return a tag * @throws DataException */ - private CompoundTag getBlockTileEntity(Vector position) throws DataException { + private CompoundTag getBlockTileEntity(BlockVector3 position) throws DataException { if (tileEntities == null) { populateTileEntities(); } - Map values = tileEntities.get(new BlockVector(position)); + Map values = tileEntities.get(position); if (values == null) { return null; } @@ -155,13 +153,14 @@ public class OldChunk implements Chunk { } @Override - public BlockStateHolder getBlock(Vector position) throws DataException { - if(position.getBlockY() >= 128) return BlockTypes.VOID_AIR.getDefaultState(); + + public BaseBlock getBlock(BlockVector3 position) throws DataException { + if(position.getY() >= 128) return BlockTypes.VOID_AIR.getDefaultState().toBaseBlock(); int id, dataVal; - int x = position.getBlockX() - rootX * 16; - int y = position.getBlockY(); - int z = position.getBlockZ() - rootZ * 16; + int x = position.getX() - rootX * 16; + int y = position.getY(); + int z = position.getZ() - rootZ * 16; int index = y + (z * 128 + (x * 128 * 16)); try { id = blocks[index]; @@ -185,13 +184,15 @@ public class OldChunk implements Chunk { BlockState state = LegacyMapper.getInstance().getBlockFromLegacy(id, dataVal); if (state == null) { WorldEdit.logger.warning("Unknown legacy block " + id + ":" + dataVal + " found when loading legacy anvil chunk."); - return BlockTypes.AIR.getDefaultState(); + return BlockTypes.AIR.getDefaultState().toBaseBlock(); } if (state.getBlockType().getMaterial().hasContainer()) { CompoundTag tileEntity = getBlockTileEntity(position); - if (tileEntity != null) return new BaseBlock(state, tileEntity); + if (tileEntity != null) { + return state.toBaseBlock(tileEntity); + } } - return state; + return state.toBaseBlock(); } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/entity/EntityType.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/entity/EntityType.java index fbd0d6a64..71779e953 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/entity/EntityType.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/entity/EntityType.java @@ -21,18 +21,46 @@ package com.sk89q.worldedit.world.entity; import com.sk89q.worldedit.registry.NamespacedRegistry; -public interface EntityType { - String getId(); +public class EntityType { + + public static final NamespacedRegistry REGISTRY = new NamespacedRegistry<>("entity type"); + + private String id; + + public EntityType(String id) { + // If it has no namespace, assume minecraft. + if (!id.contains(":")) { + id = "minecraft:" + id; + } + this.id = id; + } + + public String getId() { + return this.id; + } /** * Gets the name of this item, or the ID if the name cannot be found. * * @return The name, or ID */ - default String getName() { + public String getName() { return getId(); } - @Deprecated - public int getInternalId(); + @Override + public String toString() { + return getId(); + } + + @Override + public int hashCode() { + return this.id.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof EntityType && this.id.equals(((EntityType) obj).id); + } + } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/entity/EntityTypes.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/entity/EntityTypes.java index 5c94bfa18..a56cfbbfb 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/entity/EntityTypes.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/entity/EntityTypes.java @@ -19,166 +19,121 @@ package com.sk89q.worldedit.world.entity; -import com.boydti.fawe.util.ReflectionUtils; -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.blocks.BaseItem; -import com.sk89q.worldedit.blocks.BaseItemStack; -import com.sk89q.worldedit.entity.BaseEntity; -import com.sk89q.worldedit.extension.platform.Capability; -import com.sk89q.worldedit.world.block.BlockTypes; -import com.sk89q.worldedit.world.item.ItemType; -import com.sk89q.worldedit.world.registry.LegacyMapper; - import javax.annotation.Nullable; -import java.util.*; -public enum EntityTypes implements EntityType { - /* - ----------------------------------------------------- - Replaced at runtime by the entity registry - ----------------------------------------------------- - */ - __RESERVED__, - AREA_EFFECT_CLOUD, - ARMOR_STAND, - ARROW, - BAT, - BLAZE, - BOAT, - CAVE_SPIDER, - CHEST_MINECART, - CHICKEN, - COD, - COMMAND_BLOCK_MINECART, - COW, - CREEPER, - DOLPHIN, - DONKEY, - DRAGON_FIREBALL, - DROWNED, - EGG, - ELDER_GUARDIAN, - END_CRYSTAL, - ENDER_DRAGON, - ENDER_PEARL, - ENDERMAN, - ENDERMITE, - EVOKER, - EVOKER_FANGS, - EXPERIENCE_BOTTLE, - EXPERIENCE_ORB, - EYE_OF_ENDER, - FALLING_BLOCK, - FIREBALL, - FIREWORK_ROCKET, - FISHING_BOBBER, - FURNACE_MINECART, - GHAST, - GIANT, - GUARDIAN, - HOPPER_MINECART, - HORSE, - HUSK, - ILLUSIONER, - IRON_GOLEM, - ITEM, - ITEM_FRAME, - LEASH_KNOT, - LIGHTNING_BOLT, - LLAMA, - LLAMA_SPIT, - MAGMA_CUBE, - MINECART, - MOOSHROOM, - MULE, - OCELOT, - PAINTING, - PARROT, - PHANTOM, - PIG, - PLAYER, - POLAR_BEAR, - POTION, - PUFFERFISH, - RABBIT, - SALMON, - SHEEP, - SHULKER, - SHULKER_BULLET, - SILVERFISH, - SKELETON, - SKELETON_HORSE, - SLIME, - SMALL_FIREBALL, - SNOW_GOLEM, - SNOWBALL, - SPAWNER_MINECART, - SPECTRAL_ARROW, - SPIDER, - SQUID, - STRAY, - TNT, - TNT_MINECART, - TRIDENT, - TROPICAL_FISH, - TURTLE, - VEX, - VILLAGER, - VINDICATOR, - WITCH, - WITHER, - WITHER_SKELETON, - WITHER_SKULL, - WOLF, - ZOMBIE, - ZOMBIE_HORSE, - ZOMBIE_PIGMAN, - ZOMBIE_VILLAGER, +public class EntityTypes { - ; + public static final EntityType AREA_EFFECT_CLOUD = register("minecraft:area_effect_cloud"); + public static final EntityType ARMOR_STAND = register("minecraft:armor_stand"); + public static final EntityType ARROW = register("minecraft:arrow"); + public static final EntityType BAT = register("minecraft:bat"); + public static final EntityType BLAZE = register("minecraft:blaze"); + public static final EntityType BOAT = register("minecraft:boat"); + public static final EntityType CAVE_SPIDER = register("minecraft:cave_spider"); + public static final EntityType CHEST_MINECART = register("minecraft:chest_minecart"); + public static final EntityType CHICKEN = register("minecraft:chicken"); + public static final EntityType COD = register("minecraft:cod"); + public static final EntityType COMMAND_BLOCK_MINECART = register("minecraft:command_block_minecart"); + public static final EntityType COW = register("minecraft:cow"); + public static final EntityType CREEPER = register("minecraft:creeper"); + public static final EntityType DOLPHIN = register("minecraft:dolphin"); + public static final EntityType DONKEY = register("minecraft:donkey"); + public static final EntityType DRAGON_FIREBALL = register("minecraft:dragon_fireball"); + public static final EntityType DROWNED = register("minecraft:drowned"); + public static final EntityType EGG = register("minecraft:egg"); + public static final EntityType ELDER_GUARDIAN = register("minecraft:elder_guardian"); + public static final EntityType END_CRYSTAL = register("minecraft:end_crystal"); + public static final EntityType ENDER_DRAGON = register("minecraft:ender_dragon"); + public static final EntityType ENDER_PEARL = register("minecraft:ender_pearl"); + public static final EntityType ENDERMAN = register("minecraft:enderman"); + public static final EntityType ENDERMITE = register("minecraft:endermite"); + public static final EntityType EVOKER = register("minecraft:evoker"); + public static final EntityType EVOKER_FANGS = register("minecraft:evoker_fangs"); + public static final EntityType EXPERIENCE_BOTTLE = register("minecraft:experience_bottle"); + public static final EntityType EXPERIENCE_ORB = register("minecraft:experience_orb"); + public static final EntityType EYE_OF_ENDER = register("minecraft:eye_of_ender"); + public static final EntityType FALLING_BLOCK = register("minecraft:falling_block"); + public static final EntityType FIREBALL = register("minecraft:fireball"); + public static final EntityType FIREWORK_ROCKET = register("minecraft:firework_rocket"); + public static final EntityType FISHING_BOBBER = register("minecraft:fishing_bobber"); + public static final EntityType FURNACE_MINECART = register("minecraft:furnace_minecart"); + public static final EntityType GHAST = register("minecraft:ghast"); + public static final EntityType GIANT = register("minecraft:giant"); + public static final EntityType GUARDIAN = register("minecraft:guardian"); + public static final EntityType HOPPER_MINECART = register("minecraft:hopper_minecart"); + public static final EntityType HORSE = register("minecraft:horse"); + public static final EntityType HUSK = register("minecraft:husk"); + public static final EntityType ILLUSIONER = register("minecraft:illusioner"); + public static final EntityType IRON_GOLEM = register("minecraft:iron_golem"); + public static final EntityType ITEM = register("minecraft:item"); + public static final EntityType ITEM_FRAME = register("minecraft:item_frame"); + public static final EntityType LEASH_KNOT = register("minecraft:leash_knot"); + public static final EntityType LIGHTNING_BOLT = register("minecraft:lightning_bolt"); + public static final EntityType LLAMA = register("minecraft:llama"); + public static final EntityType LLAMA_SPIT = register("minecraft:llama_spit"); + public static final EntityType MAGMA_CUBE = register("minecraft:magma_cube"); + public static final EntityType MINECART = register("minecraft:minecart"); + public static final EntityType MOOSHROOM = register("minecraft:mooshroom"); + public static final EntityType MULE = register("minecraft:mule"); + public static final EntityType OCELOT = register("minecraft:ocelot"); + public static final EntityType PAINTING = register("minecraft:painting"); + public static final EntityType PARROT = register("minecraft:parrot"); + public static final EntityType PHANTOM = register("minecraft:phantom"); + public static final EntityType PIG = register("minecraft:pig"); + public static final EntityType PLAYER = register("minecraft:player"); + public static final EntityType POLAR_BEAR = register("minecraft:polar_bear"); + public static final EntityType POTION = register("minecraft:potion"); + public static final EntityType PUFFERFISH = register("minecraft:pufferfish"); + public static final EntityType RABBIT = register("minecraft:rabbit"); + public static final EntityType SALMON = register("minecraft:salmon"); + public static final EntityType SHEEP = register("minecraft:sheep"); + public static final EntityType SHULKER = register("minecraft:shulker"); + public static final EntityType SHULKER_BULLET = register("minecraft:shulker_bullet"); + public static final EntityType SILVERFISH = register("minecraft:silverfish"); + public static final EntityType SKELETON = register("minecraft:skeleton"); + public static final EntityType SKELETON_HORSE = register("minecraft:skeleton_horse"); + public static final EntityType SLIME = register("minecraft:slime"); + public static final EntityType SMALL_FIREBALL = register("minecraft:small_fireball"); + public static final EntityType SNOW_GOLEM = register("minecraft:snow_golem"); + public static final EntityType SNOWBALL = register("minecraft:snowball"); + public static final EntityType SPAWNER_MINECART = register("minecraft:spawner_minecart"); + public static final EntityType SPECTRAL_ARROW = register("minecraft:spectral_arrow"); + public static final EntityType SPIDER = register("minecraft:spider"); + public static final EntityType SQUID = register("minecraft:squid"); + public static final EntityType STRAY = register("minecraft:stray"); + public static final EntityType TNT = register("minecraft:tnt"); + public static final EntityType TNT_MINECART = register("minecraft:tnt_minecart"); + public static final EntityType TRIDENT = register("minecraft:trident"); + public static final EntityType TROPICAL_FISH = register("minecraft:tropical_fish"); + public static final EntityType TURTLE = register("minecraft:turtle"); + public static final EntityType VEX = register("minecraft:vex"); + public static final EntityType VILLAGER = register("minecraft:villager"); + public static final EntityType VINDICATOR = register("minecraft:vindicator"); + public static final EntityType WITCH = register("minecraft:witch"); + public static final EntityType WITHER = register("minecraft:wither"); + public static final EntityType WITHER_SKELETON = register("minecraft:wither_skeleton"); + public static final EntityType WITHER_SKULL = register("minecraft:wither_skull"); + public static final EntityType WOLF = register("minecraft:wolf"); + public static final EntityType ZOMBIE = register("minecraft:zombie"); + public static final EntityType ZOMBIE_HORSE = register("minecraft:zombie_horse"); + public static final EntityType ZOMBIE_PIGMAN = register("minecraft:zombie_pigman"); + public static final EntityType ZOMBIE_VILLAGER = register("minecraft:zombie_villager"); - private String id; - private int internalId; - - EntityTypes() { - this(null); + private EntityTypes() { } - EntityTypes(String id) { - init(id); + private static EntityType register(final String id) { + return register(new EntityType(id)); } - private void init(String id) { - if (id == null) id = "minecraft:" + name().toLowerCase(); - // If it has no namespace, assume minecraft. - else if (!id.contains(":")) { - id = "minecraft:" + id; - } - this.id = id; - this.internalId = ordinal(); + public static EntityType register(final EntityType entityType) { + return EntityType.REGISTRY.register(entityType.getId(), entityType); } - @Override - public String getId() { - return id; + public static @Nullable EntityType get(final String id) { + return EntityType.REGISTRY.get(id); } - - @Override - public String toString() { - return getId(); - } - - @Override - public int getInternalId() { - return internalId; - } - - /* - ----------------------------------------------------- - Static Initializer - ----------------------------------------------------- - */ - + public static EntityType parse(String id) { if (id.startsWith("minecraft:")) id = id.substring(10); switch (id) { @@ -246,64 +201,4 @@ public enum EntityTypes implements EntityType { } } - private static final Map $REGISTRY = new HashMap<>(); - private static int $LENGTH; - public static final EntityTypes[] values; - - static { - try { - Collection ents = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getEntityRegistry().registerEntities(); - EntityTypes[] oldValues = values(); - $LENGTH = oldValues.length; - LinkedHashSet newValues = new LinkedHashSet<>(Arrays.asList(oldValues)); - if (!ents.isEmpty()) { // No types found - use defaults - for (String ent : ents) { - EntityTypes registered = register(ent); - if (!newValues.contains(registered)) newValues.add(registered); - } - } - // Cache the values - values = newValues.toArray(new EntityTypes[newValues.size()]); - } catch (Throwable e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - private static EntityTypes register(final String id) { - // Get the enum name (remove namespace if minecraft:) - int propStart = id.indexOf('['); - String typeName = id.substring(0, propStart == -1 ? id.length() : propStart); - String enumName = (typeName.startsWith("minecraft:") ? typeName.substring(10) : typeName).toUpperCase(); - // Check existing - EntityTypes existing = null; - try { existing = valueOf(enumName.toUpperCase()); } catch (IllegalArgumentException ignore) {} - if (existing == null) { - existing = ReflectionUtils.addEnum(EntityTypes.class, enumName); - } - int internalId = existing.ordinal(); - if (existing.id == null) { - existing.init(null); - } - if (internalId == 0 && existing != __RESERVED__) { - existing.internalId = $LENGTH++; - } - if (typeName.startsWith("minecraft:")) $REGISTRY.put(typeName.substring(10), existing); - $REGISTRY.put(typeName, existing); - return existing; - } - - public static final @Nullable EntityTypes get(final String id) { - return $REGISTRY.get(id); - } - - @Deprecated - public static final EntityTypes get(final int ordinal) { - return values[ordinal]; - } - - public static int size() { - return values.length; - } - } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/item/ItemType.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/item/ItemType.java index 829c62f5a..b68db45b4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/item/ItemType.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/item/ItemType.java @@ -19,29 +19,58 @@ package com.sk89q.worldedit.world.item; +import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.blocks.BaseItem; +import com.sk89q.worldedit.extension.platform.Capability; +import com.sk89q.worldedit.registry.NamespacedRegistry; import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockTypes; -import com.sk89q.worldedit.world.registry.LegacyMapper; import javax.annotation.Nullable; -public interface ItemType { +public class ItemType { - default ItemTypes toEnum() { - return (ItemTypes) this; + public static final NamespacedRegistry REGISTRY = new NamespacedRegistry<>("item type"); + + private String id; + private BlockType blockType; + private int internalId; + private BaseItem defaultState; + + public ItemType(String id) { + // If it has no namespace, assume minecraft. + if (!id.contains(":")) { + id = "minecraft:" + id; + } + this.id = id; + this.blockType = BlockTypes.get(this.id); } - String getId(); - - int getInternalId(); + public String getId() { + return this.id; + } + + public int getInternalId() { + return this.internalId; + } + + public void setInternalId(int internalId) { + this.internalId = internalId; + } /** * Gets the name of this item, or the ID if the name cannot be found. * * @return The name, or ID */ - String getName(); + public String getName() { + String name = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getItemRegistry().getName(this); + if (name == null) { + return getId(); + } else { + return name; + } + } /** @@ -49,7 +78,7 @@ public interface ItemType { * * @return If it has a block */ - default boolean hasBlockType() { + public boolean hasBlockType() { return getBlockType() != null; } @@ -59,11 +88,34 @@ public interface ItemType { * @return The block representation */ @Nullable - default BlockTypes getBlockType() { - return BlockTypes.get(getId()); + public BlockType getBlockType() { + return this.blockType; + } + + public void setBlockType(BlockType blockType) { + this.blockType = blockType; + } + + public BaseItem getDefaultState() { + return this.defaultState; + } + + public void setDefaultState(BaseItem defaultState) { + this.defaultState = defaultState; } - default BaseItem getDefaultState() { - return new BaseItem(this); + @Override + public String toString() { + return getId(); } -} + + @Override + public int hashCode() { + return this.id.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof ItemType && this.id.equals(((ItemType) obj).id); + } +} \ No newline at end of file diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/item/ItemTypes.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/item/ItemTypes.java index 61c7c1173..20ff44846 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/item/ItemTypes.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/item/ItemTypes.java @@ -16,948 +16,849 @@ * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ + package com.sk89q.worldedit.world.item; -import com.boydti.fawe.util.MathMan; -import com.boydti.fawe.util.ReflectionUtils; -import com.sk89q.util.ReflectionUtil; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Map; + +import javax.annotation.Nullable; + import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.extension.platform.Capability; -import com.sk89q.worldedit.registry.NamespacedRegistry; import com.sk89q.worldedit.world.block.BlockType; -import com.sk89q.worldedit.world.block.BlockTypes; -import com.sk89q.worldedit.world.entity.EntityTypes; -import com.sk89q.worldedit.world.registry.BundledItemData; import com.sk89q.worldedit.world.registry.LegacyMapper; -import javax.annotation.Nullable; -import java.lang.reflect.Field; -import java.util.*; +public final class ItemTypes { -public enum ItemTypes implements ItemType { - /* - ----------------------------------------------------- - Replaced at runtime by the item registry - ----------------------------------------------------- - */ + @Nullable public static final ItemType ACACIA_BOAT = register("minecraft:acacia_boat"); + @Nullable public static final ItemType ACACIA_BUTTON = register("minecraft:acacia_button"); + @Nullable public static final ItemType ACACIA_DOOR = register("minecraft:acacia_door"); + @Nullable public static final ItemType ACACIA_FENCE = register("minecraft:acacia_fence"); + @Nullable public static final ItemType ACACIA_FENCE_GATE = register("minecraft:acacia_fence_gate"); + @Nullable public static final ItemType ACACIA_LEAVES = register("minecraft:acacia_leaves"); + @Nullable public static final ItemType ACACIA_LOG = register("minecraft:acacia_log"); + @Nullable public static final ItemType ACACIA_PLANKS = register("minecraft:acacia_planks"); + @Nullable public static final ItemType ACACIA_PRESSURE_PLATE = register("minecraft:acacia_pressure_plate"); + @Nullable public static final ItemType ACACIA_SAPLING = register("minecraft:acacia_sapling"); + @Nullable public static final ItemType ACACIA_SLAB = register("minecraft:acacia_slab"); + @Nullable public static final ItemType ACACIA_STAIRS = register("minecraft:acacia_stairs"); + @Nullable public static final ItemType ACACIA_TRAPDOOR = register("minecraft:acacia_trapdoor"); + @Nullable public static final ItemType ACACIA_WOOD = register("minecraft:acacia_wood"); + @Nullable public static final ItemType ACTIVATOR_RAIL = register("minecraft:activator_rail"); + @Nullable public static final ItemType AIR = register("minecraft:air"); + @Nullable public static final ItemType ALLIUM = register("minecraft:allium"); + @Nullable public static final ItemType ANDESITE = register("minecraft:andesite"); + @Nullable public static final ItemType ANVIL = register("minecraft:anvil"); + @Nullable public static final ItemType APPLE = register("minecraft:apple"); + @Nullable public static final ItemType ARMOR_STAND = register("minecraft:armor_stand"); + @Nullable public static final ItemType ARROW = register("minecraft:arrow"); + @Nullable public static final ItemType AZURE_BLUET = register("minecraft:azure_bluet"); + @Nullable public static final ItemType BAKED_POTATO = register("minecraft:baked_potato"); + @Nullable public static final ItemType BARRIER = register("minecraft:barrier"); + @Nullable public static final ItemType BAT_SPAWN_EGG = register("minecraft:bat_spawn_egg"); + @Nullable public static final ItemType BEACON = register("minecraft:beacon"); + @Nullable public static final ItemType BEDROCK = register("minecraft:bedrock"); + @Nullable public static final ItemType BEEF = register("minecraft:beef"); + @Nullable public static final ItemType BEETROOT = register("minecraft:beetroot"); + @Nullable public static final ItemType BEETROOT_SEEDS = register("minecraft:beetroot_seeds"); + @Nullable public static final ItemType BEETROOT_SOUP = register("minecraft:beetroot_soup"); + @Nullable public static final ItemType BIRCH_BOAT = register("minecraft:birch_boat"); + @Nullable public static final ItemType BIRCH_BUTTON = register("minecraft:birch_button"); + @Nullable public static final ItemType BIRCH_DOOR = register("minecraft:birch_door"); + @Nullable public static final ItemType BIRCH_FENCE = register("minecraft:birch_fence"); + @Nullable public static final ItemType BIRCH_FENCE_GATE = register("minecraft:birch_fence_gate"); + @Nullable public static final ItemType BIRCH_LEAVES = register("minecraft:birch_leaves"); + @Nullable public static final ItemType BIRCH_LOG = register("minecraft:birch_log"); + @Nullable public static final ItemType BIRCH_PLANKS = register("minecraft:birch_planks"); + @Nullable public static final ItemType BIRCH_PRESSURE_PLATE = register("minecraft:birch_pressure_plate"); + @Nullable public static final ItemType BIRCH_SAPLING = register("minecraft:birch_sapling"); + @Nullable public static final ItemType BIRCH_SLAB = register("minecraft:birch_slab"); + @Nullable public static final ItemType BIRCH_STAIRS = register("minecraft:birch_stairs"); + @Nullable public static final ItemType BIRCH_TRAPDOOR = register("minecraft:birch_trapdoor"); + @Nullable public static final ItemType BIRCH_WOOD = register("minecraft:birch_wood"); + @Nullable public static final ItemType BLACK_BANNER = register("minecraft:black_banner"); + @Nullable public static final ItemType BLACK_BED = register("minecraft:black_bed"); + @Nullable public static final ItemType BLACK_CARPET = register("minecraft:black_carpet"); + @Nullable public static final ItemType BLACK_CONCRETE = register("minecraft:black_concrete"); + @Nullable public static final ItemType BLACK_CONCRETE_POWDER = register("minecraft:black_concrete_powder"); + @Nullable public static final ItemType BLACK_GLAZED_TERRACOTTA = register("minecraft:black_glazed_terracotta"); + @Nullable public static final ItemType BLACK_SHULKER_BOX = register("minecraft:black_shulker_box"); + @Nullable public static final ItemType BLACK_STAINED_GLASS = register("minecraft:black_stained_glass"); + @Nullable public static final ItemType BLACK_STAINED_GLASS_PANE = register("minecraft:black_stained_glass_pane"); + @Nullable public static final ItemType BLACK_TERRACOTTA = register("minecraft:black_terracotta"); + @Nullable public static final ItemType BLACK_WOOL = register("minecraft:black_wool"); + @Nullable public static final ItemType BLAZE_POWDER = register("minecraft:blaze_powder"); + @Nullable public static final ItemType BLAZE_ROD = register("minecraft:blaze_rod"); + @Nullable public static final ItemType BLAZE_SPAWN_EGG = register("minecraft:blaze_spawn_egg"); + @Nullable public static final ItemType BLUE_BANNER = register("minecraft:blue_banner"); + @Nullable public static final ItemType BLUE_BED = register("minecraft:blue_bed"); + @Nullable public static final ItemType BLUE_CARPET = register("minecraft:blue_carpet"); + @Nullable public static final ItemType BLUE_CONCRETE = register("minecraft:blue_concrete"); + @Nullable public static final ItemType BLUE_CONCRETE_POWDER = register("minecraft:blue_concrete_powder"); + @Nullable public static final ItemType BLUE_GLAZED_TERRACOTTA = register("minecraft:blue_glazed_terracotta"); + @Nullable public static final ItemType BLUE_ICE = register("minecraft:blue_ice"); + @Nullable public static final ItemType BLUE_ORCHID = register("minecraft:blue_orchid"); + @Nullable public static final ItemType BLUE_SHULKER_BOX = register("minecraft:blue_shulker_box"); + @Nullable public static final ItemType BLUE_STAINED_GLASS = register("minecraft:blue_stained_glass"); + @Nullable public static final ItemType BLUE_STAINED_GLASS_PANE = register("minecraft:blue_stained_glass_pane"); + @Nullable public static final ItemType BLUE_TERRACOTTA = register("minecraft:blue_terracotta"); + @Nullable public static final ItemType BLUE_WOOL = register("minecraft:blue_wool"); + @Nullable public static final ItemType BONE = register("minecraft:bone"); + @Nullable public static final ItemType BONE_BLOCK = register("minecraft:bone_block"); + @Nullable public static final ItemType BONE_MEAL = register("minecraft:bone_meal"); + @Nullable public static final ItemType BOOK = register("minecraft:book"); + @Nullable public static final ItemType BOOKSHELF = register("minecraft:bookshelf"); + @Nullable public static final ItemType BOW = register("minecraft:bow"); + @Nullable public static final ItemType BOWL = register("minecraft:bowl"); + @Nullable public static final ItemType BRAIN_CORAL = register("minecraft:brain_coral"); + @Nullable public static final ItemType BRAIN_CORAL_BLOCK = register("minecraft:brain_coral_block"); + @Nullable public static final ItemType BRAIN_CORAL_FAN = register("minecraft:brain_coral_fan"); + @Nullable public static final ItemType BREAD = register("minecraft:bread"); + @Nullable public static final ItemType BREWING_STAND = register("minecraft:brewing_stand"); + @Nullable public static final ItemType BRICK = register("minecraft:brick"); + @Nullable public static final ItemType BRICK_SLAB = register("minecraft:brick_slab"); + @Nullable public static final ItemType BRICK_STAIRS = register("minecraft:brick_stairs"); + @Nullable public static final ItemType BRICKS = register("minecraft:bricks"); + @Nullable public static final ItemType BROWN_BANNER = register("minecraft:brown_banner"); + @Nullable public static final ItemType BROWN_BED = register("minecraft:brown_bed"); + @Nullable public static final ItemType BROWN_CARPET = register("minecraft:brown_carpet"); + @Nullable public static final ItemType BROWN_CONCRETE = register("minecraft:brown_concrete"); + @Nullable public static final ItemType BROWN_CONCRETE_POWDER = register("minecraft:brown_concrete_powder"); + @Nullable public static final ItemType BROWN_GLAZED_TERRACOTTA = register("minecraft:brown_glazed_terracotta"); + @Nullable public static final ItemType BROWN_MUSHROOM = register("minecraft:brown_mushroom"); + @Nullable public static final ItemType BROWN_MUSHROOM_BLOCK = register("minecraft:brown_mushroom_block"); + @Nullable public static final ItemType BROWN_SHULKER_BOX = register("minecraft:brown_shulker_box"); + @Nullable public static final ItemType BROWN_STAINED_GLASS = register("minecraft:brown_stained_glass"); + @Nullable public static final ItemType BROWN_STAINED_GLASS_PANE = register("minecraft:brown_stained_glass_pane"); + @Nullable public static final ItemType BROWN_TERRACOTTA = register("minecraft:brown_terracotta"); + @Nullable public static final ItemType BROWN_WOOL = register("minecraft:brown_wool"); + @Nullable public static final ItemType BUBBLE_CORAL = register("minecraft:bubble_coral"); + @Nullable public static final ItemType BUBBLE_CORAL_BLOCK = register("minecraft:bubble_coral_block"); + @Nullable public static final ItemType BUBBLE_CORAL_FAN = register("minecraft:bubble_coral_fan"); + @Nullable public static final ItemType BUCKET = register("minecraft:bucket"); + @Nullable public static final ItemType CACTUS = register("minecraft:cactus"); + @Nullable public static final ItemType CACTUS_GREEN = register("minecraft:cactus_green"); + @Nullable public static final ItemType CAKE = register("minecraft:cake"); + @Nullable public static final ItemType CARROT = register("minecraft:carrot"); + @Nullable public static final ItemType CARROT_ON_A_STICK = register("minecraft:carrot_on_a_stick"); + @Nullable public static final ItemType CARVED_PUMPKIN = register("minecraft:carved_pumpkin"); + @Nullable public static final ItemType CAULDRON = register("minecraft:cauldron"); + @Nullable public static final ItemType CAVE_SPIDER_SPAWN_EGG = register("minecraft:cave_spider_spawn_egg"); + @Nullable public static final ItemType CHAIN_COMMAND_BLOCK = register("minecraft:chain_command_block"); + @Nullable public static final ItemType CHAINMAIL_BOOTS = register("minecraft:chainmail_boots"); + @Nullable public static final ItemType CHAINMAIL_CHESTPLATE = register("minecraft:chainmail_chestplate"); + @Nullable public static final ItemType CHAINMAIL_HELMET = register("minecraft:chainmail_helmet"); + @Nullable public static final ItemType CHAINMAIL_LEGGINGS = register("minecraft:chainmail_leggings"); + @Nullable public static final ItemType CHARCOAL = register("minecraft:charcoal"); + @Nullable public static final ItemType CHEST = register("minecraft:chest"); + @Nullable public static final ItemType CHEST_MINECART = register("minecraft:chest_minecart"); + @Nullable public static final ItemType CHICKEN = register("minecraft:chicken"); + @Nullable public static final ItemType CHICKEN_SPAWN_EGG = register("minecraft:chicken_spawn_egg"); + @Nullable public static final ItemType CHIPPED_ANVIL = register("minecraft:chipped_anvil"); + @Nullable public static final ItemType CHISELED_QUARTZ_BLOCK = register("minecraft:chiseled_quartz_block"); + @Nullable public static final ItemType CHISELED_RED_SANDSTONE = register("minecraft:chiseled_red_sandstone"); + @Nullable public static final ItemType CHISELED_SANDSTONE = register("minecraft:chiseled_sandstone"); + @Nullable public static final ItemType CHISELED_STONE_BRICKS = register("minecraft:chiseled_stone_bricks"); + @Nullable public static final ItemType CHORUS_FLOWER = register("minecraft:chorus_flower"); + @Nullable public static final ItemType CHORUS_FRUIT = register("minecraft:chorus_fruit"); + @Nullable public static final ItemType CHORUS_PLANT = register("minecraft:chorus_plant"); + @Nullable public static final ItemType CLAY = register("minecraft:clay"); + @Nullable public static final ItemType CLAY_BALL = register("minecraft:clay_ball"); + @Nullable public static final ItemType CLOCK = register("minecraft:clock"); + @Nullable public static final ItemType COAL = register("minecraft:coal"); + @Nullable public static final ItemType COAL_BLOCK = register("minecraft:coal_block"); + @Nullable public static final ItemType COAL_ORE = register("minecraft:coal_ore"); + @Nullable public static final ItemType COARSE_DIRT = register("minecraft:coarse_dirt"); + @Nullable public static final ItemType COBBLESTONE = register("minecraft:cobblestone"); + @Nullable public static final ItemType COBBLESTONE_SLAB = register("minecraft:cobblestone_slab"); + @Nullable public static final ItemType COBBLESTONE_STAIRS = register("minecraft:cobblestone_stairs"); + @Nullable public static final ItemType COBBLESTONE_WALL = register("minecraft:cobblestone_wall"); + @Nullable public static final ItemType COBWEB = register("minecraft:cobweb"); + @Nullable public static final ItemType COCOA_BEANS = register("minecraft:cocoa_beans"); + @Nullable public static final ItemType COD = register("minecraft:cod"); + @Nullable public static final ItemType COD_BUCKET = register("minecraft:cod_bucket"); + @Nullable public static final ItemType COD_SPAWN_EGG = register("minecraft:cod_spawn_egg"); + @Nullable public static final ItemType COMMAND_BLOCK = register("minecraft:command_block"); + @Nullable public static final ItemType COMMAND_BLOCK_MINECART = register("minecraft:command_block_minecart"); + @Nullable public static final ItemType COMPARATOR = register("minecraft:comparator"); + @Nullable public static final ItemType COMPASS = register("minecraft:compass"); + @Nullable public static final ItemType CONDUIT = register("minecraft:conduit"); + @Nullable public static final ItemType COOKED_BEEF = register("minecraft:cooked_beef"); + @Nullable public static final ItemType COOKED_CHICKEN = register("minecraft:cooked_chicken"); + @Nullable public static final ItemType COOKED_COD = register("minecraft:cooked_cod"); + @Nullable public static final ItemType COOKED_MUTTON = register("minecraft:cooked_mutton"); + @Nullable public static final ItemType COOKED_PORKCHOP = register("minecraft:cooked_porkchop"); + @Nullable public static final ItemType COOKED_RABBIT = register("minecraft:cooked_rabbit"); + @Nullable public static final ItemType COOKED_SALMON = register("minecraft:cooked_salmon"); + @Nullable public static final ItemType COOKIE = register("minecraft:cookie"); + @Nullable public static final ItemType COW_SPAWN_EGG = register("minecraft:cow_spawn_egg"); + @Nullable public static final ItemType CRACKED_STONE_BRICKS = register("minecraft:cracked_stone_bricks"); + @Nullable public static final ItemType CRAFTING_TABLE = register("minecraft:crafting_table"); + @Nullable public static final ItemType CREEPER_HEAD = register("minecraft:creeper_head"); + @Nullable public static final ItemType CREEPER_SPAWN_EGG = register("minecraft:creeper_spawn_egg"); + @Nullable public static final ItemType CUT_RED_SANDSTONE = register("minecraft:cut_red_sandstone"); + @Nullable public static final ItemType CUT_SANDSTONE = register("minecraft:cut_sandstone"); + @Nullable public static final ItemType CYAN_BANNER = register("minecraft:cyan_banner"); + @Nullable public static final ItemType CYAN_BED = register("minecraft:cyan_bed"); + @Nullable public static final ItemType CYAN_CARPET = register("minecraft:cyan_carpet"); + @Nullable public static final ItemType CYAN_CONCRETE = register("minecraft:cyan_concrete"); + @Nullable public static final ItemType CYAN_CONCRETE_POWDER = register("minecraft:cyan_concrete_powder"); + @Nullable public static final ItemType CYAN_DYE = register("minecraft:cyan_dye"); + @Nullable public static final ItemType CYAN_GLAZED_TERRACOTTA = register("minecraft:cyan_glazed_terracotta"); + @Nullable public static final ItemType CYAN_SHULKER_BOX = register("minecraft:cyan_shulker_box"); + @Nullable public static final ItemType CYAN_STAINED_GLASS = register("minecraft:cyan_stained_glass"); + @Nullable public static final ItemType CYAN_STAINED_GLASS_PANE = register("minecraft:cyan_stained_glass_pane"); + @Nullable public static final ItemType CYAN_TERRACOTTA = register("minecraft:cyan_terracotta"); + @Nullable public static final ItemType CYAN_WOOL = register("minecraft:cyan_wool"); + @Nullable public static final ItemType DAMAGED_ANVIL = register("minecraft:damaged_anvil"); + @Nullable public static final ItemType DANDELION = register("minecraft:dandelion"); + @Nullable public static final ItemType DANDELION_YELLOW = register("minecraft:dandelion_yellow"); + @Nullable public static final ItemType DARK_OAK_BOAT = register("minecraft:dark_oak_boat"); + @Nullable public static final ItemType DARK_OAK_BUTTON = register("minecraft:dark_oak_button"); + @Nullable public static final ItemType DARK_OAK_DOOR = register("minecraft:dark_oak_door"); + @Nullable public static final ItemType DARK_OAK_FENCE = register("minecraft:dark_oak_fence"); + @Nullable public static final ItemType DARK_OAK_FENCE_GATE = register("minecraft:dark_oak_fence_gate"); + @Nullable public static final ItemType DARK_OAK_LEAVES = register("minecraft:dark_oak_leaves"); + @Nullable public static final ItemType DARK_OAK_LOG = register("minecraft:dark_oak_log"); + @Nullable public static final ItemType DARK_OAK_PLANKS = register("minecraft:dark_oak_planks"); + @Nullable public static final ItemType DARK_OAK_PRESSURE_PLATE = register("minecraft:dark_oak_pressure_plate"); + @Nullable public static final ItemType DARK_OAK_SAPLING = register("minecraft:dark_oak_sapling"); + @Nullable public static final ItemType DARK_OAK_SLAB = register("minecraft:dark_oak_slab"); + @Nullable public static final ItemType DARK_OAK_STAIRS = register("minecraft:dark_oak_stairs"); + @Nullable public static final ItemType DARK_OAK_TRAPDOOR = register("minecraft:dark_oak_trapdoor"); + @Nullable public static final ItemType DARK_OAK_WOOD = register("minecraft:dark_oak_wood"); + @Nullable public static final ItemType DARK_PRISMARINE = register("minecraft:dark_prismarine"); + @Nullable public static final ItemType DARK_PRISMARINE_SLAB = register("minecraft:dark_prismarine_slab"); + @Nullable public static final ItemType DARK_PRISMARINE_STAIRS = register("minecraft:dark_prismarine_stairs"); + @Nullable public static final ItemType DAYLIGHT_DETECTOR = register("minecraft:daylight_detector"); + @Nullable public static final ItemType DEAD_BRAIN_CORAL = register("minecraft:dead_brain_coral"); + @Nullable public static final ItemType DEAD_BRAIN_CORAL_BLOCK = register("minecraft:dead_brain_coral_block"); + @Nullable public static final ItemType DEAD_BRAIN_CORAL_FAN = register("minecraft:dead_brain_coral_fan"); + @Nullable public static final ItemType DEAD_BUBBLE_CORAL = register("minecraft:dead_bubble_coral"); + @Nullable public static final ItemType DEAD_BUBBLE_CORAL_BLOCK = register("minecraft:dead_bubble_coral_block"); + @Nullable public static final ItemType DEAD_BUBBLE_CORAL_FAN = register("minecraft:dead_bubble_coral_fan"); + @Nullable public static final ItemType DEAD_BUSH = register("minecraft:dead_bush"); + @Nullable public static final ItemType DEAD_FIRE_CORAL = register("minecraft:dead_fire_coral"); + @Nullable public static final ItemType DEAD_FIRE_CORAL_BLOCK = register("minecraft:dead_fire_coral_block"); + @Nullable public static final ItemType DEAD_FIRE_CORAL_FAN = register("minecraft:dead_fire_coral_fan"); + @Nullable public static final ItemType DEAD_HORN_CORAL = register("minecraft:dead_horn_coral"); + @Nullable public static final ItemType DEAD_HORN_CORAL_BLOCK = register("minecraft:dead_horn_coral_block"); + @Nullable public static final ItemType DEAD_HORN_CORAL_FAN = register("minecraft:dead_horn_coral_fan"); + @Nullable public static final ItemType DEAD_TUBE_CORAL = register("minecraft:dead_tube_coral"); + @Nullable public static final ItemType DEAD_TUBE_CORAL_BLOCK = register("minecraft:dead_tube_coral_block"); + @Nullable public static final ItemType DEAD_TUBE_CORAL_FAN = register("minecraft:dead_tube_coral_fan"); + @Nullable public static final ItemType DEBUG_STICK = register("minecraft:debug_stick"); + @Nullable public static final ItemType DETECTOR_RAIL = register("minecraft:detector_rail"); + @Nullable public static final ItemType DIAMOND = register("minecraft:diamond"); + @Nullable public static final ItemType DIAMOND_AXE = register("minecraft:diamond_axe"); + @Nullable public static final ItemType DIAMOND_BLOCK = register("minecraft:diamond_block"); + @Nullable public static final ItemType DIAMOND_BOOTS = register("minecraft:diamond_boots"); + @Nullable public static final ItemType DIAMOND_CHESTPLATE = register("minecraft:diamond_chestplate"); + @Nullable public static final ItemType DIAMOND_HELMET = register("minecraft:diamond_helmet"); + @Nullable public static final ItemType DIAMOND_HOE = register("minecraft:diamond_hoe"); + @Nullable public static final ItemType DIAMOND_HORSE_ARMOR = register("minecraft:diamond_horse_armor"); + @Nullable public static final ItemType DIAMOND_LEGGINGS = register("minecraft:diamond_leggings"); + @Nullable public static final ItemType DIAMOND_ORE = register("minecraft:diamond_ore"); + @Nullable public static final ItemType DIAMOND_PICKAXE = register("minecraft:diamond_pickaxe"); + @Nullable public static final ItemType DIAMOND_SHOVEL = register("minecraft:diamond_shovel"); + @Nullable public static final ItemType DIAMOND_SWORD = register("minecraft:diamond_sword"); + @Nullable public static final ItemType DIORITE = register("minecraft:diorite"); + @Nullable public static final ItemType DIRT = register("minecraft:dirt"); + @Nullable public static final ItemType DISPENSER = register("minecraft:dispenser"); + @Nullable public static final ItemType DOLPHIN_SPAWN_EGG = register("minecraft:dolphin_spawn_egg"); + @Nullable public static final ItemType DONKEY_SPAWN_EGG = register("minecraft:donkey_spawn_egg"); + @Nullable public static final ItemType DRAGON_BREATH = register("minecraft:dragon_breath"); + @Nullable public static final ItemType DRAGON_EGG = register("minecraft:dragon_egg"); + @Nullable public static final ItemType DRAGON_HEAD = register("minecraft:dragon_head"); + @Nullable public static final ItemType DRIED_KELP = register("minecraft:dried_kelp"); + @Nullable public static final ItemType DRIED_KELP_BLOCK = register("minecraft:dried_kelp_block"); + @Nullable public static final ItemType DROPPER = register("minecraft:dropper"); + @Nullable public static final ItemType DROWNED_SPAWN_EGG = register("minecraft:drowned_spawn_egg"); + @Nullable public static final ItemType EGG = register("minecraft:egg"); + @Nullable public static final ItemType ELDER_GUARDIAN_SPAWN_EGG = register("minecraft:elder_guardian_spawn_egg"); + @Nullable public static final ItemType ELYTRA = register("minecraft:elytra"); + @Nullable public static final ItemType EMERALD = register("minecraft:emerald"); + @Nullable public static final ItemType EMERALD_BLOCK = register("minecraft:emerald_block"); + @Nullable public static final ItemType EMERALD_ORE = register("minecraft:emerald_ore"); + @Nullable public static final ItemType ENCHANTED_BOOK = register("minecraft:enchanted_book"); + @Nullable public static final ItemType ENCHANTED_GOLDEN_APPLE = register("minecraft:enchanted_golden_apple"); + @Nullable public static final ItemType ENCHANTING_TABLE = register("minecraft:enchanting_table"); + @Nullable public static final ItemType END_CRYSTAL = register("minecraft:end_crystal"); + @Nullable public static final ItemType END_PORTAL_FRAME = register("minecraft:end_portal_frame"); + @Nullable public static final ItemType END_ROD = register("minecraft:end_rod"); + @Nullable public static final ItemType END_STONE = register("minecraft:end_stone"); + @Nullable public static final ItemType END_STONE_BRICKS = register("minecraft:end_stone_bricks"); + @Nullable public static final ItemType ENDER_CHEST = register("minecraft:ender_chest"); + @Nullable public static final ItemType ENDER_EYE = register("minecraft:ender_eye"); + @Nullable public static final ItemType ENDER_PEARL = register("minecraft:ender_pearl"); + @Nullable public static final ItemType ENDERMAN_SPAWN_EGG = register("minecraft:enderman_spawn_egg"); + @Nullable public static final ItemType ENDERMITE_SPAWN_EGG = register("minecraft:endermite_spawn_egg"); + @Nullable public static final ItemType EVOKER_SPAWN_EGG = register("minecraft:evoker_spawn_egg"); + @Nullable public static final ItemType EXPERIENCE_BOTTLE = register("minecraft:experience_bottle"); + @Nullable public static final ItemType FARMLAND = register("minecraft:farmland"); + @Nullable public static final ItemType FEATHER = register("minecraft:feather"); + @Nullable public static final ItemType FERMENTED_SPIDER_EYE = register("minecraft:fermented_spider_eye"); + @Nullable public static final ItemType FERN = register("minecraft:fern"); + @Nullable public static final ItemType FILLED_MAP = register("minecraft:filled_map"); + @Nullable public static final ItemType FIRE_CHARGE = register("minecraft:fire_charge"); + @Nullable public static final ItemType FIRE_CORAL = register("minecraft:fire_coral"); + @Nullable public static final ItemType FIRE_CORAL_BLOCK = register("minecraft:fire_coral_block"); + @Nullable public static final ItemType FIRE_CORAL_FAN = register("minecraft:fire_coral_fan"); + @Nullable public static final ItemType FIREWORK_ROCKET = register("minecraft:firework_rocket"); + @Nullable public static final ItemType FIREWORK_STAR = register("minecraft:firework_star"); + @Nullable public static final ItemType FISHING_ROD = register("minecraft:fishing_rod"); + @Nullable public static final ItemType FLINT = register("minecraft:flint"); + @Nullable public static final ItemType FLINT_AND_STEEL = register("minecraft:flint_and_steel"); + @Nullable public static final ItemType FLOWER_POT = register("minecraft:flower_pot"); + @Nullable public static final ItemType FURNACE = register("minecraft:furnace"); + @Nullable public static final ItemType FURNACE_MINECART = register("minecraft:furnace_minecart"); + @Nullable public static final ItemType GHAST_SPAWN_EGG = register("minecraft:ghast_spawn_egg"); + @Nullable public static final ItemType GHAST_TEAR = register("minecraft:ghast_tear"); + @Nullable public static final ItemType GLASS = register("minecraft:glass"); + @Nullable public static final ItemType GLASS_BOTTLE = register("minecraft:glass_bottle"); + @Nullable public static final ItemType GLASS_PANE = register("minecraft:glass_pane"); + @Nullable public static final ItemType GLISTERING_MELON_SLICE = register("minecraft:glistering_melon_slice"); + @Nullable public static final ItemType GLOWSTONE = register("minecraft:glowstone"); + @Nullable public static final ItemType GLOWSTONE_DUST = register("minecraft:glowstone_dust"); + @Nullable public static final ItemType GOLD_BLOCK = register("minecraft:gold_block"); + @Nullable public static final ItemType GOLD_INGOT = register("minecraft:gold_ingot"); + @Nullable public static final ItemType GOLD_NUGGET = register("minecraft:gold_nugget"); + @Nullable public static final ItemType GOLD_ORE = register("minecraft:gold_ore"); + @Nullable public static final ItemType GOLDEN_APPLE = register("minecraft:golden_apple"); + @Nullable public static final ItemType GOLDEN_AXE = register("minecraft:golden_axe"); + @Nullable public static final ItemType GOLDEN_BOOTS = register("minecraft:golden_boots"); + @Nullable public static final ItemType GOLDEN_CARROT = register("minecraft:golden_carrot"); + @Nullable public static final ItemType GOLDEN_CHESTPLATE = register("minecraft:golden_chestplate"); + @Nullable public static final ItemType GOLDEN_HELMET = register("minecraft:golden_helmet"); + @Nullable public static final ItemType GOLDEN_HOE = register("minecraft:golden_hoe"); + @Nullable public static final ItemType GOLDEN_HORSE_ARMOR = register("minecraft:golden_horse_armor"); + @Nullable public static final ItemType GOLDEN_LEGGINGS = register("minecraft:golden_leggings"); + @Nullable public static final ItemType GOLDEN_PICKAXE = register("minecraft:golden_pickaxe"); + @Nullable public static final ItemType GOLDEN_SHOVEL = register("minecraft:golden_shovel"); + @Nullable public static final ItemType GOLDEN_SWORD = register("minecraft:golden_sword"); + @Nullable public static final ItemType GRANITE = register("minecraft:granite"); + @Nullable public static final ItemType GRASS = register("minecraft:grass"); + @Nullable public static final ItemType GRASS_BLOCK = register("minecraft:grass_block"); + @Nullable public static final ItemType GRASS_PATH = register("minecraft:grass_path"); + @Nullable public static final ItemType GRAVEL = register("minecraft:gravel"); + @Nullable public static final ItemType GRAY_BANNER = register("minecraft:gray_banner"); + @Nullable public static final ItemType GRAY_BED = register("minecraft:gray_bed"); + @Nullable public static final ItemType GRAY_CARPET = register("minecraft:gray_carpet"); + @Nullable public static final ItemType GRAY_CONCRETE = register("minecraft:gray_concrete"); + @Nullable public static final ItemType GRAY_CONCRETE_POWDER = register("minecraft:gray_concrete_powder"); + @Nullable public static final ItemType GRAY_DYE = register("minecraft:gray_dye"); + @Nullable public static final ItemType GRAY_GLAZED_TERRACOTTA = register("minecraft:gray_glazed_terracotta"); + @Nullable public static final ItemType GRAY_SHULKER_BOX = register("minecraft:gray_shulker_box"); + @Nullable public static final ItemType GRAY_STAINED_GLASS = register("minecraft:gray_stained_glass"); + @Nullable public static final ItemType GRAY_STAINED_GLASS_PANE = register("minecraft:gray_stained_glass_pane"); + @Nullable public static final ItemType GRAY_TERRACOTTA = register("minecraft:gray_terracotta"); + @Nullable public static final ItemType GRAY_WOOL = register("minecraft:gray_wool"); + @Nullable public static final ItemType GREEN_BANNER = register("minecraft:green_banner"); + @Nullable public static final ItemType GREEN_BED = register("minecraft:green_bed"); + @Nullable public static final ItemType GREEN_CARPET = register("minecraft:green_carpet"); + @Nullable public static final ItemType GREEN_CONCRETE = register("minecraft:green_concrete"); + @Nullable public static final ItemType GREEN_CONCRETE_POWDER = register("minecraft:green_concrete_powder"); + @Nullable public static final ItemType GREEN_GLAZED_TERRACOTTA = register("minecraft:green_glazed_terracotta"); + @Nullable public static final ItemType GREEN_SHULKER_BOX = register("minecraft:green_shulker_box"); + @Nullable public static final ItemType GREEN_STAINED_GLASS = register("minecraft:green_stained_glass"); + @Nullable public static final ItemType GREEN_STAINED_GLASS_PANE = register("minecraft:green_stained_glass_pane"); + @Nullable public static final ItemType GREEN_TERRACOTTA = register("minecraft:green_terracotta"); + @Nullable public static final ItemType GREEN_WOOL = register("minecraft:green_wool"); + @Nullable public static final ItemType GUARDIAN_SPAWN_EGG = register("minecraft:guardian_spawn_egg"); + @Nullable public static final ItemType GUNPOWDER = register("minecraft:gunpowder"); + @Nullable public static final ItemType HAY_BLOCK = register("minecraft:hay_block"); + @Nullable public static final ItemType HEART_OF_THE_SEA = register("minecraft:heart_of_the_sea"); + @Nullable public static final ItemType HEAVY_WEIGHTED_PRESSURE_PLATE = register("minecraft:heavy_weighted_pressure_plate"); + @Nullable public static final ItemType HOPPER = register("minecraft:hopper"); + @Nullable public static final ItemType HOPPER_MINECART = register("minecraft:hopper_minecart"); + @Nullable public static final ItemType HORN_CORAL = register("minecraft:horn_coral"); + @Nullable public static final ItemType HORN_CORAL_BLOCK = register("minecraft:horn_coral_block"); + @Nullable public static final ItemType HORN_CORAL_FAN = register("minecraft:horn_coral_fan"); + @Nullable public static final ItemType HORSE_SPAWN_EGG = register("minecraft:horse_spawn_egg"); + @Nullable public static final ItemType HUSK_SPAWN_EGG = register("minecraft:husk_spawn_egg"); + @Nullable public static final ItemType ICE = register("minecraft:ice"); + @Nullable public static final ItemType INFESTED_CHISELED_STONE_BRICKS = register("minecraft:infested_chiseled_stone_bricks"); + @Nullable public static final ItemType INFESTED_COBBLESTONE = register("minecraft:infested_cobblestone"); + @Nullable public static final ItemType INFESTED_CRACKED_STONE_BRICKS = register("minecraft:infested_cracked_stone_bricks"); + @Nullable public static final ItemType INFESTED_MOSSY_STONE_BRICKS = register("minecraft:infested_mossy_stone_bricks"); + @Nullable public static final ItemType INFESTED_STONE = register("minecraft:infested_stone"); + @Nullable public static final ItemType INFESTED_STONE_BRICKS = register("minecraft:infested_stone_bricks"); + @Nullable public static final ItemType INK_SAC = register("minecraft:ink_sac"); + @Nullable public static final ItemType IRON_AXE = register("minecraft:iron_axe"); + @Nullable public static final ItemType IRON_BARS = register("minecraft:iron_bars"); + @Nullable public static final ItemType IRON_BLOCK = register("minecraft:iron_block"); + @Nullable public static final ItemType IRON_BOOTS = register("minecraft:iron_boots"); + @Nullable public static final ItemType IRON_CHESTPLATE = register("minecraft:iron_chestplate"); + @Nullable public static final ItemType IRON_DOOR = register("minecraft:iron_door"); + @Nullable public static final ItemType IRON_HELMET = register("minecraft:iron_helmet"); + @Nullable public static final ItemType IRON_HOE = register("minecraft:iron_hoe"); + @Nullable public static final ItemType IRON_HORSE_ARMOR = register("minecraft:iron_horse_armor"); + @Nullable public static final ItemType IRON_INGOT = register("minecraft:iron_ingot"); + @Nullable public static final ItemType IRON_LEGGINGS = register("minecraft:iron_leggings"); + @Nullable public static final ItemType IRON_NUGGET = register("minecraft:iron_nugget"); + @Nullable public static final ItemType IRON_ORE = register("minecraft:iron_ore"); + @Nullable public static final ItemType IRON_PICKAXE = register("minecraft:iron_pickaxe"); + @Nullable public static final ItemType IRON_SHOVEL = register("minecraft:iron_shovel"); + @Nullable public static final ItemType IRON_SWORD = register("minecraft:iron_sword"); + @Nullable public static final ItemType IRON_TRAPDOOR = register("minecraft:iron_trapdoor"); + @Nullable public static final ItemType ITEM_FRAME = register("minecraft:item_frame"); + @Nullable public static final ItemType JACK_O_LANTERN = register("minecraft:jack_o_lantern"); + @Nullable public static final ItemType JUKEBOX = register("minecraft:jukebox"); + @Nullable public static final ItemType JUNGLE_BOAT = register("minecraft:jungle_boat"); + @Nullable public static final ItemType JUNGLE_BUTTON = register("minecraft:jungle_button"); + @Nullable public static final ItemType JUNGLE_DOOR = register("minecraft:jungle_door"); + @Nullable public static final ItemType JUNGLE_FENCE = register("minecraft:jungle_fence"); + @Nullable public static final ItemType JUNGLE_FENCE_GATE = register("minecraft:jungle_fence_gate"); + @Nullable public static final ItemType JUNGLE_LEAVES = register("minecraft:jungle_leaves"); + @Nullable public static final ItemType JUNGLE_LOG = register("minecraft:jungle_log"); + @Nullable public static final ItemType JUNGLE_PLANKS = register("minecraft:jungle_planks"); + @Nullable public static final ItemType JUNGLE_PRESSURE_PLATE = register("minecraft:jungle_pressure_plate"); + @Nullable public static final ItemType JUNGLE_SAPLING = register("minecraft:jungle_sapling"); + @Nullable public static final ItemType JUNGLE_SLAB = register("minecraft:jungle_slab"); + @Nullable public static final ItemType JUNGLE_STAIRS = register("minecraft:jungle_stairs"); + @Nullable public static final ItemType JUNGLE_TRAPDOOR = register("minecraft:jungle_trapdoor"); + @Nullable public static final ItemType JUNGLE_WOOD = register("minecraft:jungle_wood"); + @Nullable public static final ItemType KELP = register("minecraft:kelp"); + @Nullable public static final ItemType KNOWLEDGE_BOOK = register("minecraft:knowledge_book"); + @Nullable public static final ItemType LADDER = register("minecraft:ladder"); + @Nullable public static final ItemType LAPIS_BLOCK = register("minecraft:lapis_block"); + @Nullable public static final ItemType LAPIS_LAZULI = register("minecraft:lapis_lazuli"); + @Nullable public static final ItemType LAPIS_ORE = register("minecraft:lapis_ore"); + @Nullable public static final ItemType LARGE_FERN = register("minecraft:large_fern"); + @Nullable public static final ItemType LAVA_BUCKET = register("minecraft:lava_bucket"); + @Nullable public static final ItemType LEAD = register("minecraft:lead"); + @Nullable public static final ItemType LEATHER = register("minecraft:leather"); + @Nullable public static final ItemType LEATHER_BOOTS = register("minecraft:leather_boots"); + @Nullable public static final ItemType LEATHER_CHESTPLATE = register("minecraft:leather_chestplate"); + @Nullable public static final ItemType LEATHER_HELMET = register("minecraft:leather_helmet"); + @Nullable public static final ItemType LEATHER_LEGGINGS = register("minecraft:leather_leggings"); + @Nullable public static final ItemType LEVER = register("minecraft:lever"); + @Nullable public static final ItemType LIGHT_BLUE_BANNER = register("minecraft:light_blue_banner"); + @Nullable public static final ItemType LIGHT_BLUE_BED = register("minecraft:light_blue_bed"); + @Nullable public static final ItemType LIGHT_BLUE_CARPET = register("minecraft:light_blue_carpet"); + @Nullable public static final ItemType LIGHT_BLUE_CONCRETE = register("minecraft:light_blue_concrete"); + @Nullable public static final ItemType LIGHT_BLUE_CONCRETE_POWDER = register("minecraft:light_blue_concrete_powder"); + @Nullable public static final ItemType LIGHT_BLUE_DYE = register("minecraft:light_blue_dye"); + @Nullable public static final ItemType LIGHT_BLUE_GLAZED_TERRACOTTA = register("minecraft:light_blue_glazed_terracotta"); + @Nullable public static final ItemType LIGHT_BLUE_SHULKER_BOX = register("minecraft:light_blue_shulker_box"); + @Nullable public static final ItemType LIGHT_BLUE_STAINED_GLASS = register("minecraft:light_blue_stained_glass"); + @Nullable public static final ItemType LIGHT_BLUE_STAINED_GLASS_PANE = register("minecraft:light_blue_stained_glass_pane"); + @Nullable public static final ItemType LIGHT_BLUE_TERRACOTTA = register("minecraft:light_blue_terracotta"); + @Nullable public static final ItemType LIGHT_BLUE_WOOL = register("minecraft:light_blue_wool"); + @Nullable public static final ItemType LIGHT_GRAY_BANNER = register("minecraft:light_gray_banner"); + @Nullable public static final ItemType LIGHT_GRAY_BED = register("minecraft:light_gray_bed"); + @Nullable public static final ItemType LIGHT_GRAY_CARPET = register("minecraft:light_gray_carpet"); + @Nullable public static final ItemType LIGHT_GRAY_CONCRETE = register("minecraft:light_gray_concrete"); + @Nullable public static final ItemType LIGHT_GRAY_CONCRETE_POWDER = register("minecraft:light_gray_concrete_powder"); + @Nullable public static final ItemType LIGHT_GRAY_DYE = register("minecraft:light_gray_dye"); + @Nullable public static final ItemType LIGHT_GRAY_GLAZED_TERRACOTTA = register("minecraft:light_gray_glazed_terracotta"); + @Nullable public static final ItemType LIGHT_GRAY_SHULKER_BOX = register("minecraft:light_gray_shulker_box"); + @Nullable public static final ItemType LIGHT_GRAY_STAINED_GLASS = register("minecraft:light_gray_stained_glass"); + @Nullable public static final ItemType LIGHT_GRAY_STAINED_GLASS_PANE = register("minecraft:light_gray_stained_glass_pane"); + @Nullable public static final ItemType LIGHT_GRAY_TERRACOTTA = register("minecraft:light_gray_terracotta"); + @Nullable public static final ItemType LIGHT_GRAY_WOOL = register("minecraft:light_gray_wool"); + @Nullable public static final ItemType LIGHT_WEIGHTED_PRESSURE_PLATE = register("minecraft:light_weighted_pressure_plate"); + @Nullable public static final ItemType LILAC = register("minecraft:lilac"); + @Nullable public static final ItemType LILY_PAD = register("minecraft:lily_pad"); + @Nullable public static final ItemType LIME_BANNER = register("minecraft:lime_banner"); + @Nullable public static final ItemType LIME_BED = register("minecraft:lime_bed"); + @Nullable public static final ItemType LIME_CARPET = register("minecraft:lime_carpet"); + @Nullable public static final ItemType LIME_CONCRETE = register("minecraft:lime_concrete"); + @Nullable public static final ItemType LIME_CONCRETE_POWDER = register("minecraft:lime_concrete_powder"); + @Nullable public static final ItemType LIME_DYE = register("minecraft:lime_dye"); + @Nullable public static final ItemType LIME_GLAZED_TERRACOTTA = register("minecraft:lime_glazed_terracotta"); + @Nullable public static final ItemType LIME_SHULKER_BOX = register("minecraft:lime_shulker_box"); + @Nullable public static final ItemType LIME_STAINED_GLASS = register("minecraft:lime_stained_glass"); + @Nullable public static final ItemType LIME_STAINED_GLASS_PANE = register("minecraft:lime_stained_glass_pane"); + @Nullable public static final ItemType LIME_TERRACOTTA = register("minecraft:lime_terracotta"); + @Nullable public static final ItemType LIME_WOOL = register("minecraft:lime_wool"); + @Nullable public static final ItemType LINGERING_POTION = register("minecraft:lingering_potion"); + @Nullable public static final ItemType LLAMA_SPAWN_EGG = register("minecraft:llama_spawn_egg"); + @Nullable public static final ItemType MAGENTA_BANNER = register("minecraft:magenta_banner"); + @Nullable public static final ItemType MAGENTA_BED = register("minecraft:magenta_bed"); + @Nullable public static final ItemType MAGENTA_CARPET = register("minecraft:magenta_carpet"); + @Nullable public static final ItemType MAGENTA_CONCRETE = register("minecraft:magenta_concrete"); + @Nullable public static final ItemType MAGENTA_CONCRETE_POWDER = register("minecraft:magenta_concrete_powder"); + @Nullable public static final ItemType MAGENTA_DYE = register("minecraft:magenta_dye"); + @Nullable public static final ItemType MAGENTA_GLAZED_TERRACOTTA = register("minecraft:magenta_glazed_terracotta"); + @Nullable public static final ItemType MAGENTA_SHULKER_BOX = register("minecraft:magenta_shulker_box"); + @Nullable public static final ItemType MAGENTA_STAINED_GLASS = register("minecraft:magenta_stained_glass"); + @Nullable public static final ItemType MAGENTA_STAINED_GLASS_PANE = register("minecraft:magenta_stained_glass_pane"); + @Nullable public static final ItemType MAGENTA_TERRACOTTA = register("minecraft:magenta_terracotta"); + @Nullable public static final ItemType MAGENTA_WOOL = register("minecraft:magenta_wool"); + @Nullable public static final ItemType MAGMA_BLOCK = register("minecraft:magma_block"); + @Nullable public static final ItemType MAGMA_CREAM = register("minecraft:magma_cream"); + @Nullable public static final ItemType MAGMA_CUBE_SPAWN_EGG = register("minecraft:magma_cube_spawn_egg"); + @Nullable public static final ItemType MAP = register("minecraft:map"); + @Nullable public static final ItemType MELON = register("minecraft:melon"); + @Nullable public static final ItemType MELON_SEEDS = register("minecraft:melon_seeds"); + @Nullable public static final ItemType MELON_SLICE = register("minecraft:melon_slice"); + @Nullable public static final ItemType MILK_BUCKET = register("minecraft:milk_bucket"); + @Nullable public static final ItemType MINECART = register("minecraft:minecart"); + @Nullable public static final ItemType MOOSHROOM_SPAWN_EGG = register("minecraft:mooshroom_spawn_egg"); + @Nullable public static final ItemType MOSSY_COBBLESTONE = register("minecraft:mossy_cobblestone"); + @Nullable public static final ItemType MOSSY_COBBLESTONE_WALL = register("minecraft:mossy_cobblestone_wall"); + @Nullable public static final ItemType MOSSY_STONE_BRICKS = register("minecraft:mossy_stone_bricks"); + @Nullable public static final ItemType MULE_SPAWN_EGG = register("minecraft:mule_spawn_egg"); + @Nullable public static final ItemType MUSHROOM_STEM = register("minecraft:mushroom_stem"); + @Nullable public static final ItemType MUSHROOM_STEW = register("minecraft:mushroom_stew"); + @Nullable public static final ItemType MUSIC_DISC_11 = register("minecraft:music_disc_11"); + @Nullable public static final ItemType MUSIC_DISC_13 = register("minecraft:music_disc_13"); + @Nullable public static final ItemType MUSIC_DISC_BLOCKS = register("minecraft:music_disc_blocks"); + @Nullable public static final ItemType MUSIC_DISC_CAT = register("minecraft:music_disc_cat"); + @Nullable public static final ItemType MUSIC_DISC_CHIRP = register("minecraft:music_disc_chirp"); + @Nullable public static final ItemType MUSIC_DISC_FAR = register("minecraft:music_disc_far"); + @Nullable public static final ItemType MUSIC_DISC_MALL = register("minecraft:music_disc_mall"); + @Nullable public static final ItemType MUSIC_DISC_MELLOHI = register("minecraft:music_disc_mellohi"); + @Nullable public static final ItemType MUSIC_DISC_STAL = register("minecraft:music_disc_stal"); + @Nullable public static final ItemType MUSIC_DISC_STRAD = register("minecraft:music_disc_strad"); + @Nullable public static final ItemType MUSIC_DISC_WAIT = register("minecraft:music_disc_wait"); + @Nullable public static final ItemType MUSIC_DISC_WARD = register("minecraft:music_disc_ward"); + @Nullable public static final ItemType MUTTON = register("minecraft:mutton"); + @Nullable public static final ItemType MYCELIUM = register("minecraft:mycelium"); + @Nullable public static final ItemType NAME_TAG = register("minecraft:name_tag"); + @Nullable public static final ItemType NAUTILUS_SHELL = register("minecraft:nautilus_shell"); + @Nullable public static final ItemType NETHER_BRICK = register("minecraft:nether_brick"); + @Nullable public static final ItemType NETHER_BRICK_FENCE = register("minecraft:nether_brick_fence"); + @Nullable public static final ItemType NETHER_BRICK_SLAB = register("minecraft:nether_brick_slab"); + @Nullable public static final ItemType NETHER_BRICK_STAIRS = register("minecraft:nether_brick_stairs"); + @Nullable public static final ItemType NETHER_BRICKS = register("minecraft:nether_bricks"); + @Nullable public static final ItemType NETHER_QUARTZ_ORE = register("minecraft:nether_quartz_ore"); + @Nullable public static final ItemType NETHER_STAR = register("minecraft:nether_star"); + @Nullable public static final ItemType NETHER_WART = register("minecraft:nether_wart"); + @Nullable public static final ItemType NETHER_WART_BLOCK = register("minecraft:nether_wart_block"); + @Nullable public static final ItemType NETHERRACK = register("minecraft:netherrack"); + @Nullable public static final ItemType NOTE_BLOCK = register("minecraft:note_block"); + @Nullable public static final ItemType OAK_BOAT = register("minecraft:oak_boat"); + @Nullable public static final ItemType OAK_BUTTON = register("minecraft:oak_button"); + @Nullable public static final ItemType OAK_DOOR = register("minecraft:oak_door"); + @Nullable public static final ItemType OAK_FENCE = register("minecraft:oak_fence"); + @Nullable public static final ItemType OAK_FENCE_GATE = register("minecraft:oak_fence_gate"); + @Nullable public static final ItemType OAK_LEAVES = register("minecraft:oak_leaves"); + @Nullable public static final ItemType OAK_LOG = register("minecraft:oak_log"); + @Nullable public static final ItemType OAK_PLANKS = register("minecraft:oak_planks"); + @Nullable public static final ItemType OAK_PRESSURE_PLATE = register("minecraft:oak_pressure_plate"); + @Nullable public static final ItemType OAK_SAPLING = register("minecraft:oak_sapling"); + @Nullable public static final ItemType OAK_SLAB = register("minecraft:oak_slab"); + @Nullable public static final ItemType OAK_STAIRS = register("minecraft:oak_stairs"); + @Nullable public static final ItemType OAK_TRAPDOOR = register("minecraft:oak_trapdoor"); + @Nullable public static final ItemType OAK_WOOD = register("minecraft:oak_wood"); + @Nullable public static final ItemType OBSERVER = register("minecraft:observer"); + @Nullable public static final ItemType OBSIDIAN = register("minecraft:obsidian"); + @Nullable public static final ItemType OCELOT_SPAWN_EGG = register("minecraft:ocelot_spawn_egg"); + @Nullable public static final ItemType ORANGE_BANNER = register("minecraft:orange_banner"); + @Nullable public static final ItemType ORANGE_BED = register("minecraft:orange_bed"); + @Nullable public static final ItemType ORANGE_CARPET = register("minecraft:orange_carpet"); + @Nullable public static final ItemType ORANGE_CONCRETE = register("minecraft:orange_concrete"); + @Nullable public static final ItemType ORANGE_CONCRETE_POWDER = register("minecraft:orange_concrete_powder"); + @Nullable public static final ItemType ORANGE_DYE = register("minecraft:orange_dye"); + @Nullable public static final ItemType ORANGE_GLAZED_TERRACOTTA = register("minecraft:orange_glazed_terracotta"); + @Nullable public static final ItemType ORANGE_SHULKER_BOX = register("minecraft:orange_shulker_box"); + @Nullable public static final ItemType ORANGE_STAINED_GLASS = register("minecraft:orange_stained_glass"); + @Nullable public static final ItemType ORANGE_STAINED_GLASS_PANE = register("minecraft:orange_stained_glass_pane"); + @Nullable public static final ItemType ORANGE_TERRACOTTA = register("minecraft:orange_terracotta"); + @Nullable public static final ItemType ORANGE_TULIP = register("minecraft:orange_tulip"); + @Nullable public static final ItemType ORANGE_WOOL = register("minecraft:orange_wool"); + @Nullable public static final ItemType OXEYE_DAISY = register("minecraft:oxeye_daisy"); + @Nullable public static final ItemType PACKED_ICE = register("minecraft:packed_ice"); + @Nullable public static final ItemType PAINTING = register("minecraft:painting"); + @Nullable public static final ItemType PAPER = register("minecraft:paper"); + @Nullable public static final ItemType PARROT_SPAWN_EGG = register("minecraft:parrot_spawn_egg"); + @Nullable public static final ItemType PEONY = register("minecraft:peony"); + @Nullable public static final ItemType PETRIFIED_OAK_SLAB = register("minecraft:petrified_oak_slab"); + @Nullable public static final ItemType PHANTOM_MEMBRANE = register("minecraft:phantom_membrane"); + @Nullable public static final ItemType PHANTOM_SPAWN_EGG = register("minecraft:phantom_spawn_egg"); + @Nullable public static final ItemType PIG_SPAWN_EGG = register("minecraft:pig_spawn_egg"); + @Nullable public static final ItemType PINK_BANNER = register("minecraft:pink_banner"); + @Nullable public static final ItemType PINK_BED = register("minecraft:pink_bed"); + @Nullable public static final ItemType PINK_CARPET = register("minecraft:pink_carpet"); + @Nullable public static final ItemType PINK_CONCRETE = register("minecraft:pink_concrete"); + @Nullable public static final ItemType PINK_CONCRETE_POWDER = register("minecraft:pink_concrete_powder"); + @Nullable public static final ItemType PINK_DYE = register("minecraft:pink_dye"); + @Nullable public static final ItemType PINK_GLAZED_TERRACOTTA = register("minecraft:pink_glazed_terracotta"); + @Nullable public static final ItemType PINK_SHULKER_BOX = register("minecraft:pink_shulker_box"); + @Nullable public static final ItemType PINK_STAINED_GLASS = register("minecraft:pink_stained_glass"); + @Nullable public static final ItemType PINK_STAINED_GLASS_PANE = register("minecraft:pink_stained_glass_pane"); + @Nullable public static final ItemType PINK_TERRACOTTA = register("minecraft:pink_terracotta"); + @Nullable public static final ItemType PINK_TULIP = register("minecraft:pink_tulip"); + @Nullable public static final ItemType PINK_WOOL = register("minecraft:pink_wool"); + @Nullable public static final ItemType PISTON = register("minecraft:piston"); + @Nullable public static final ItemType PLAYER_HEAD = register("minecraft:player_head"); + @Nullable public static final ItemType PODZOL = register("minecraft:podzol"); + @Nullable public static final ItemType POISONOUS_POTATO = register("minecraft:poisonous_potato"); + @Nullable public static final ItemType POLAR_BEAR_SPAWN_EGG = register("minecraft:polar_bear_spawn_egg"); + @Nullable public static final ItemType POLISHED_ANDESITE = register("minecraft:polished_andesite"); + @Nullable public static final ItemType POLISHED_DIORITE = register("minecraft:polished_diorite"); + @Nullable public static final ItemType POLISHED_GRANITE = register("minecraft:polished_granite"); + @Nullable public static final ItemType POPPED_CHORUS_FRUIT = register("minecraft:popped_chorus_fruit"); + @Nullable public static final ItemType POPPY = register("minecraft:poppy"); + @Nullable public static final ItemType PORKCHOP = register("minecraft:porkchop"); + @Nullable public static final ItemType POTATO = register("minecraft:potato"); + @Nullable public static final ItemType POTION = register("minecraft:potion"); + @Nullable public static final ItemType POWERED_RAIL = register("minecraft:powered_rail"); + @Nullable public static final ItemType PRISMARINE = register("minecraft:prismarine"); + @Nullable public static final ItemType PRISMARINE_BRICK_SLAB = register("minecraft:prismarine_brick_slab"); + @Nullable public static final ItemType PRISMARINE_BRICK_STAIRS = register("minecraft:prismarine_brick_stairs"); + @Nullable public static final ItemType PRISMARINE_BRICKS = register("minecraft:prismarine_bricks"); + @Nullable public static final ItemType PRISMARINE_CRYSTALS = register("minecraft:prismarine_crystals"); + @Nullable public static final ItemType PRISMARINE_SHARD = register("minecraft:prismarine_shard"); + @Nullable public static final ItemType PRISMARINE_SLAB = register("minecraft:prismarine_slab"); + @Nullable public static final ItemType PRISMARINE_STAIRS = register("minecraft:prismarine_stairs"); + @Nullable public static final ItemType PUFFERFISH = register("minecraft:pufferfish"); + @Nullable public static final ItemType PUFFERFISH_BUCKET = register("minecraft:pufferfish_bucket"); + @Nullable public static final ItemType PUFFERFISH_SPAWN_EGG = register("minecraft:pufferfish_spawn_egg"); + @Nullable public static final ItemType PUMPKIN = register("minecraft:pumpkin"); + @Nullable public static final ItemType PUMPKIN_PIE = register("minecraft:pumpkin_pie"); + @Nullable public static final ItemType PUMPKIN_SEEDS = register("minecraft:pumpkin_seeds"); + @Nullable public static final ItemType PURPLE_BANNER = register("minecraft:purple_banner"); + @Nullable public static final ItemType PURPLE_BED = register("minecraft:purple_bed"); + @Nullable public static final ItemType PURPLE_CARPET = register("minecraft:purple_carpet"); + @Nullable public static final ItemType PURPLE_CONCRETE = register("minecraft:purple_concrete"); + @Nullable public static final ItemType PURPLE_CONCRETE_POWDER = register("minecraft:purple_concrete_powder"); + @Nullable public static final ItemType PURPLE_DYE = register("minecraft:purple_dye"); + @Nullable public static final ItemType PURPLE_GLAZED_TERRACOTTA = register("minecraft:purple_glazed_terracotta"); + @Nullable public static final ItemType PURPLE_SHULKER_BOX = register("minecraft:purple_shulker_box"); + @Nullable public static final ItemType PURPLE_STAINED_GLASS = register("minecraft:purple_stained_glass"); + @Nullable public static final ItemType PURPLE_STAINED_GLASS_PANE = register("minecraft:purple_stained_glass_pane"); + @Nullable public static final ItemType PURPLE_TERRACOTTA = register("minecraft:purple_terracotta"); + @Nullable public static final ItemType PURPLE_WOOL = register("minecraft:purple_wool"); + @Nullable public static final ItemType PURPUR_BLOCK = register("minecraft:purpur_block"); + @Nullable public static final ItemType PURPUR_PILLAR = register("minecraft:purpur_pillar"); + @Nullable public static final ItemType PURPUR_SLAB = register("minecraft:purpur_slab"); + @Nullable public static final ItemType PURPUR_STAIRS = register("minecraft:purpur_stairs"); + @Nullable public static final ItemType QUARTZ = register("minecraft:quartz"); + @Nullable public static final ItemType QUARTZ_BLOCK = register("minecraft:quartz_block"); + @Nullable public static final ItemType QUARTZ_PILLAR = register("minecraft:quartz_pillar"); + @Nullable public static final ItemType QUARTZ_SLAB = register("minecraft:quartz_slab"); + @Nullable public static final ItemType QUARTZ_STAIRS = register("minecraft:quartz_stairs"); + @Nullable public static final ItemType RABBIT = register("minecraft:rabbit"); + @Nullable public static final ItemType RABBIT_FOOT = register("minecraft:rabbit_foot"); + @Nullable public static final ItemType RABBIT_HIDE = register("minecraft:rabbit_hide"); + @Nullable public static final ItemType RABBIT_SPAWN_EGG = register("minecraft:rabbit_spawn_egg"); + @Nullable public static final ItemType RABBIT_STEW = register("minecraft:rabbit_stew"); + @Nullable public static final ItemType RAIL = register("minecraft:rail"); + @Nullable public static final ItemType RED_BANNER = register("minecraft:red_banner"); + @Nullable public static final ItemType RED_BED = register("minecraft:red_bed"); + @Nullable public static final ItemType RED_CARPET = register("minecraft:red_carpet"); + @Nullable public static final ItemType RED_CONCRETE = register("minecraft:red_concrete"); + @Nullable public static final ItemType RED_CONCRETE_POWDER = register("minecraft:red_concrete_powder"); + @Nullable public static final ItemType RED_GLAZED_TERRACOTTA = register("minecraft:red_glazed_terracotta"); + @Nullable public static final ItemType RED_MUSHROOM = register("minecraft:red_mushroom"); + @Nullable public static final ItemType RED_MUSHROOM_BLOCK = register("minecraft:red_mushroom_block"); + @Nullable public static final ItemType RED_NETHER_BRICKS = register("minecraft:red_nether_bricks"); + @Nullable public static final ItemType RED_SAND = register("minecraft:red_sand"); + @Nullable public static final ItemType RED_SANDSTONE = register("minecraft:red_sandstone"); + @Nullable public static final ItemType RED_SANDSTONE_SLAB = register("minecraft:red_sandstone_slab"); + @Nullable public static final ItemType RED_SANDSTONE_STAIRS = register("minecraft:red_sandstone_stairs"); + @Nullable public static final ItemType RED_SHULKER_BOX = register("minecraft:red_shulker_box"); + @Nullable public static final ItemType RED_STAINED_GLASS = register("minecraft:red_stained_glass"); + @Nullable public static final ItemType RED_STAINED_GLASS_PANE = register("minecraft:red_stained_glass_pane"); + @Nullable public static final ItemType RED_TERRACOTTA = register("minecraft:red_terracotta"); + @Nullable public static final ItemType RED_TULIP = register("minecraft:red_tulip"); + @Nullable public static final ItemType RED_WOOL = register("minecraft:red_wool"); + @Nullable public static final ItemType REDSTONE = register("minecraft:redstone"); + @Nullable public static final ItemType REDSTONE_BLOCK = register("minecraft:redstone_block"); + @Nullable public static final ItemType REDSTONE_LAMP = register("minecraft:redstone_lamp"); + @Nullable public static final ItemType REDSTONE_ORE = register("minecraft:redstone_ore"); + @Nullable public static final ItemType REDSTONE_TORCH = register("minecraft:redstone_torch"); + @Nullable public static final ItemType REPEATER = register("minecraft:repeater"); + @Nullable public static final ItemType REPEATING_COMMAND_BLOCK = register("minecraft:repeating_command_block"); + @Nullable public static final ItemType ROSE_BUSH = register("minecraft:rose_bush"); + @Nullable public static final ItemType ROSE_RED = register("minecraft:rose_red"); + @Nullable public static final ItemType ROTTEN_FLESH = register("minecraft:rotten_flesh"); + @Nullable public static final ItemType SADDLE = register("minecraft:saddle"); + @Nullable public static final ItemType SALMON = register("minecraft:salmon"); + @Nullable public static final ItemType SALMON_BUCKET = register("minecraft:salmon_bucket"); + @Nullable public static final ItemType SALMON_SPAWN_EGG = register("minecraft:salmon_spawn_egg"); + @Nullable public static final ItemType SAND = register("minecraft:sand"); + @Nullable public static final ItemType SANDSTONE = register("minecraft:sandstone"); + @Nullable public static final ItemType SANDSTONE_SLAB = register("minecraft:sandstone_slab"); + @Nullable public static final ItemType SANDSTONE_STAIRS = register("minecraft:sandstone_stairs"); + @Nullable public static final ItemType SCUTE = register("minecraft:scute"); + @Nullable public static final ItemType SEA_LANTERN = register("minecraft:sea_lantern"); + @Nullable public static final ItemType SEA_PICKLE = register("minecraft:sea_pickle"); + @Nullable public static final ItemType SEAGRASS = register("minecraft:seagrass"); + @Nullable public static final ItemType SHEARS = register("minecraft:shears"); + @Nullable public static final ItemType SHEEP_SPAWN_EGG = register("minecraft:sheep_spawn_egg"); + @Nullable public static final ItemType SHIELD = register("minecraft:shield"); + @Nullable public static final ItemType SHULKER_BOX = register("minecraft:shulker_box"); + @Nullable public static final ItemType SHULKER_SHELL = register("minecraft:shulker_shell"); + @Nullable public static final ItemType SHULKER_SPAWN_EGG = register("minecraft:shulker_spawn_egg"); + @Nullable public static final ItemType SIGN = register("minecraft:sign"); + @Nullable public static final ItemType SILVERFISH_SPAWN_EGG = register("minecraft:silverfish_spawn_egg"); + @Nullable public static final ItemType SKELETON_HORSE_SPAWN_EGG = register("minecraft:skeleton_horse_spawn_egg"); + @Nullable public static final ItemType SKELETON_SKULL = register("minecraft:skeleton_skull"); + @Nullable public static final ItemType SKELETON_SPAWN_EGG = register("minecraft:skeleton_spawn_egg"); + @Nullable public static final ItemType SLIME_BALL = register("minecraft:slime_ball"); + @Nullable public static final ItemType SLIME_BLOCK = register("minecraft:slime_block"); + @Nullable public static final ItemType SLIME_SPAWN_EGG = register("minecraft:slime_spawn_egg"); + @Nullable public static final ItemType SMOOTH_QUARTZ = register("minecraft:smooth_quartz"); + @Nullable public static final ItemType SMOOTH_RED_SANDSTONE = register("minecraft:smooth_red_sandstone"); + @Nullable public static final ItemType SMOOTH_SANDSTONE = register("minecraft:smooth_sandstone"); + @Nullable public static final ItemType SMOOTH_STONE = register("minecraft:smooth_stone"); + @Nullable public static final ItemType SNOW = register("minecraft:snow"); + @Nullable public static final ItemType SNOW_BLOCK = register("minecraft:snow_block"); + @Nullable public static final ItemType SNOWBALL = register("minecraft:snowball"); + @Nullable public static final ItemType SOUL_SAND = register("minecraft:soul_sand"); + @Nullable public static final ItemType SPAWNER = register("minecraft:spawner"); + @Nullable public static final ItemType SPECTRAL_ARROW = register("minecraft:spectral_arrow"); + @Nullable public static final ItemType SPIDER_EYE = register("minecraft:spider_eye"); + @Nullable public static final ItemType SPIDER_SPAWN_EGG = register("minecraft:spider_spawn_egg"); + @Nullable public static final ItemType SPLASH_POTION = register("minecraft:splash_potion"); + @Nullable public static final ItemType SPONGE = register("minecraft:sponge"); + @Nullable public static final ItemType SPRUCE_BOAT = register("minecraft:spruce_boat"); + @Nullable public static final ItemType SPRUCE_BUTTON = register("minecraft:spruce_button"); + @Nullable public static final ItemType SPRUCE_DOOR = register("minecraft:spruce_door"); + @Nullable public static final ItemType SPRUCE_FENCE = register("minecraft:spruce_fence"); + @Nullable public static final ItemType SPRUCE_FENCE_GATE = register("minecraft:spruce_fence_gate"); + @Nullable public static final ItemType SPRUCE_LEAVES = register("minecraft:spruce_leaves"); + @Nullable public static final ItemType SPRUCE_LOG = register("minecraft:spruce_log"); + @Nullable public static final ItemType SPRUCE_PLANKS = register("minecraft:spruce_planks"); + @Nullable public static final ItemType SPRUCE_PRESSURE_PLATE = register("minecraft:spruce_pressure_plate"); + @Nullable public static final ItemType SPRUCE_SAPLING = register("minecraft:spruce_sapling"); + @Nullable public static final ItemType SPRUCE_SLAB = register("minecraft:spruce_slab"); + @Nullable public static final ItemType SPRUCE_STAIRS = register("minecraft:spruce_stairs"); + @Nullable public static final ItemType SPRUCE_TRAPDOOR = register("minecraft:spruce_trapdoor"); + @Nullable public static final ItemType SPRUCE_WOOD = register("minecraft:spruce_wood"); + @Nullable public static final ItemType SQUID_SPAWN_EGG = register("minecraft:squid_spawn_egg"); + @Nullable public static final ItemType STICK = register("minecraft:stick"); + @Nullable public static final ItemType STICKY_PISTON = register("minecraft:sticky_piston"); + @Nullable public static final ItemType STONE = register("minecraft:stone"); + @Nullable public static final ItemType STONE_AXE = register("minecraft:stone_axe"); + @Nullable public static final ItemType STONE_BRICK_SLAB = register("minecraft:stone_brick_slab"); + @Nullable public static final ItemType STONE_BRICK_STAIRS = register("minecraft:stone_brick_stairs"); + @Nullable public static final ItemType STONE_BRICKS = register("minecraft:stone_bricks"); + @Nullable public static final ItemType STONE_BUTTON = register("minecraft:stone_button"); + @Nullable public static final ItemType STONE_HOE = register("minecraft:stone_hoe"); + @Nullable public static final ItemType STONE_PICKAXE = register("minecraft:stone_pickaxe"); + @Nullable public static final ItemType STONE_PRESSURE_PLATE = register("minecraft:stone_pressure_plate"); + @Nullable public static final ItemType STONE_SHOVEL = register("minecraft:stone_shovel"); + @Nullable public static final ItemType STONE_SLAB = register("minecraft:stone_slab"); + @Nullable public static final ItemType STONE_SWORD = register("minecraft:stone_sword"); + @Nullable public static final ItemType STRAY_SPAWN_EGG = register("minecraft:stray_spawn_egg"); + @Nullable public static final ItemType STRING = register("minecraft:string"); + @Nullable public static final ItemType STRIPPED_ACACIA_LOG = register("minecraft:stripped_acacia_log"); + @Nullable public static final ItemType STRIPPED_ACACIA_WOOD = register("minecraft:stripped_acacia_wood"); + @Nullable public static final ItemType STRIPPED_BIRCH_LOG = register("minecraft:stripped_birch_log"); + @Nullable public static final ItemType STRIPPED_BIRCH_WOOD = register("minecraft:stripped_birch_wood"); + @Nullable public static final ItemType STRIPPED_DARK_OAK_LOG = register("minecraft:stripped_dark_oak_log"); + @Nullable public static final ItemType STRIPPED_DARK_OAK_WOOD = register("minecraft:stripped_dark_oak_wood"); + @Nullable public static final ItemType STRIPPED_JUNGLE_LOG = register("minecraft:stripped_jungle_log"); + @Nullable public static final ItemType STRIPPED_JUNGLE_WOOD = register("minecraft:stripped_jungle_wood"); + @Nullable public static final ItemType STRIPPED_OAK_LOG = register("minecraft:stripped_oak_log"); + @Nullable public static final ItemType STRIPPED_OAK_WOOD = register("minecraft:stripped_oak_wood"); + @Nullable public static final ItemType STRIPPED_SPRUCE_LOG = register("minecraft:stripped_spruce_log"); + @Nullable public static final ItemType STRIPPED_SPRUCE_WOOD = register("minecraft:stripped_spruce_wood"); + @Nullable public static final ItemType STRUCTURE_BLOCK = register("minecraft:structure_block"); + @Nullable public static final ItemType STRUCTURE_VOID = register("minecraft:structure_void"); + @Nullable public static final ItemType SUGAR = register("minecraft:sugar"); + @Nullable public static final ItemType SUGAR_CANE = register("minecraft:sugar_cane"); + @Nullable public static final ItemType SUNFLOWER = register("minecraft:sunflower"); + @Nullable public static final ItemType TALL_GRASS = register("minecraft:tall_grass"); + @Nullable public static final ItemType TERRACOTTA = register("minecraft:terracotta"); + @Nullable public static final ItemType TIPPED_ARROW = register("minecraft:tipped_arrow"); + @Nullable public static final ItemType TNT = register("minecraft:tnt"); + @Nullable public static final ItemType TNT_MINECART = register("minecraft:tnt_minecart"); + @Nullable public static final ItemType TORCH = register("minecraft:torch"); + @Nullable public static final ItemType TOTEM_OF_UNDYING = register("minecraft:totem_of_undying"); + @Nullable public static final ItemType TRAPPED_CHEST = register("minecraft:trapped_chest"); + @Nullable public static final ItemType TRIDENT = register("minecraft:trident"); + @Nullable public static final ItemType TRIPWIRE_HOOK = register("minecraft:tripwire_hook"); + @Nullable public static final ItemType TROPICAL_FISH = register("minecraft:tropical_fish"); + @Nullable public static final ItemType TROPICAL_FISH_BUCKET = register("minecraft:tropical_fish_bucket"); + @Nullable public static final ItemType TROPICAL_FISH_SPAWN_EGG = register("minecraft:tropical_fish_spawn_egg"); + @Nullable public static final ItemType TUBE_CORAL = register("minecraft:tube_coral"); + @Nullable public static final ItemType TUBE_CORAL_BLOCK = register("minecraft:tube_coral_block"); + @Nullable public static final ItemType TUBE_CORAL_FAN = register("minecraft:tube_coral_fan"); + @Nullable public static final ItemType TURTLE_EGG = register("minecraft:turtle_egg"); + @Nullable public static final ItemType TURTLE_HELMET = register("minecraft:turtle_helmet"); + @Nullable public static final ItemType TURTLE_SPAWN_EGG = register("minecraft:turtle_spawn_egg"); + @Nullable public static final ItemType VEX_SPAWN_EGG = register("minecraft:vex_spawn_egg"); + @Nullable public static final ItemType VILLAGER_SPAWN_EGG = register("minecraft:villager_spawn_egg"); + @Nullable public static final ItemType VINDICATOR_SPAWN_EGG = register("minecraft:vindicator_spawn_egg"); + @Nullable public static final ItemType VINE = register("minecraft:vine"); + @Nullable public static final ItemType WATER_BUCKET = register("minecraft:water_bucket"); + @Nullable public static final ItemType WET_SPONGE = register("minecraft:wet_sponge"); + @Nullable public static final ItemType WHEAT = register("minecraft:wheat"); + @Nullable public static final ItemType WHEAT_SEEDS = register("minecraft:wheat_seeds"); + @Nullable public static final ItemType WHITE_BANNER = register("minecraft:white_banner"); + @Nullable public static final ItemType WHITE_BED = register("minecraft:white_bed"); + @Nullable public static final ItemType WHITE_CARPET = register("minecraft:white_carpet"); + @Nullable public static final ItemType WHITE_CONCRETE = register("minecraft:white_concrete"); + @Nullable public static final ItemType WHITE_CONCRETE_POWDER = register("minecraft:white_concrete_powder"); + @Nullable public static final ItemType WHITE_GLAZED_TERRACOTTA = register("minecraft:white_glazed_terracotta"); + @Nullable public static final ItemType WHITE_SHULKER_BOX = register("minecraft:white_shulker_box"); + @Nullable public static final ItemType WHITE_STAINED_GLASS = register("minecraft:white_stained_glass"); + @Nullable public static final ItemType WHITE_STAINED_GLASS_PANE = register("minecraft:white_stained_glass_pane"); + @Nullable public static final ItemType WHITE_TERRACOTTA = register("minecraft:white_terracotta"); + @Nullable public static final ItemType WHITE_TULIP = register("minecraft:white_tulip"); + @Nullable public static final ItemType WHITE_WOOL = register("minecraft:white_wool"); + @Nullable public static final ItemType WITCH_SPAWN_EGG = register("minecraft:witch_spawn_egg"); + @Nullable public static final ItemType WITHER_SKELETON_SKULL = register("minecraft:wither_skeleton_skull"); + @Nullable public static final ItemType WITHER_SKELETON_SPAWN_EGG = register("minecraft:wither_skeleton_spawn_egg"); + @Nullable public static final ItemType WOLF_SPAWN_EGG = register("minecraft:wolf_spawn_egg"); + @Nullable public static final ItemType WOODEN_AXE = register("minecraft:wooden_axe"); + @Nullable public static final ItemType WOODEN_HOE = register("minecraft:wooden_hoe"); + @Nullable public static final ItemType WOODEN_PICKAXE = register("minecraft:wooden_pickaxe"); + @Nullable public static final ItemType WOODEN_SHOVEL = register("minecraft:wooden_shovel"); + @Nullable public static final ItemType WOODEN_SWORD = register("minecraft:wooden_sword"); + @Nullable public static final ItemType WRITABLE_BOOK = register("minecraft:writable_book"); + @Nullable public static final ItemType WRITTEN_BOOK = register("minecraft:written_book"); + @Nullable public static final ItemType YELLOW_BANNER = register("minecraft:yellow_banner"); + @Nullable public static final ItemType YELLOW_BED = register("minecraft:yellow_bed"); + @Nullable public static final ItemType YELLOW_CARPET = register("minecraft:yellow_carpet"); + @Nullable public static final ItemType YELLOW_CONCRETE = register("minecraft:yellow_concrete"); + @Nullable public static final ItemType YELLOW_CONCRETE_POWDER = register("minecraft:yellow_concrete_powder"); + @Nullable public static final ItemType YELLOW_GLAZED_TERRACOTTA = register("minecraft:yellow_glazed_terracotta"); + @Nullable public static final ItemType YELLOW_SHULKER_BOX = register("minecraft:yellow_shulker_box"); + @Nullable public static final ItemType YELLOW_STAINED_GLASS = register("minecraft:yellow_stained_glass"); + @Nullable public static final ItemType YELLOW_STAINED_GLASS_PANE = register("minecraft:yellow_stained_glass_pane"); + @Nullable public static final ItemType YELLOW_TERRACOTTA = register("minecraft:yellow_terracotta"); + @Nullable public static final ItemType YELLOW_WOOL = register("minecraft:yellow_wool"); + @Nullable public static final ItemType ZOMBIE_HEAD = register("minecraft:zombie_head"); + @Nullable public static final ItemType ZOMBIE_HORSE_SPAWN_EGG = register("minecraft:zombie_horse_spawn_egg"); + @Nullable public static final ItemType ZOMBIE_PIGMAN_SPAWN_EGG = register("minecraft:zombie_pigman_spawn_egg"); + @Nullable public static final ItemType ZOMBIE_SPAWN_EGG = register("minecraft:zombie_spawn_egg"); + @Nullable public static final ItemType ZOMBIE_VILLAGER_SPAWN_EGG = register("minecraft:zombie_villager_spawn_egg"); - __RESERVED__, - ACACIA_BOAT, - ACACIA_BUTTON, - ACACIA_DOOR, - ACACIA_FENCE, - ACACIA_FENCE_GATE, - ACACIA_LEAVES, - ACACIA_LOG, - ACACIA_PLANKS, - ACACIA_PRESSURE_PLATE, - ACACIA_SAPLING, - ACACIA_SLAB, - ACACIA_STAIRS, - ACACIA_TRAPDOOR, - ACACIA_WOOD, - ACTIVATOR_RAIL, - AIR, - ALLIUM, - ANDESITE, - ANVIL, - APPLE, - ARMOR_STAND, - ARROW, - AZURE_BLUET, - BAKED_POTATO, - BARRIER, - BAT_SPAWN_EGG, - BEACON, - BEDROCK, - BEEF, - BEETROOT, - BEETROOT_SEEDS, - BEETROOT_SOUP, - BIRCH_BOAT, - BIRCH_BUTTON, - BIRCH_DOOR, - BIRCH_FENCE, - BIRCH_FENCE_GATE, - BIRCH_LEAVES, - BIRCH_LOG, - BIRCH_PLANKS, - BIRCH_PRESSURE_PLATE, - BIRCH_SAPLING, - BIRCH_SLAB, - BIRCH_STAIRS, - BIRCH_TRAPDOOR, - BIRCH_WOOD, - BLACK_BANNER, - BLACK_BED, - BLACK_CARPET, - BLACK_CONCRETE, - BLACK_CONCRETE_POWDER, - BLACK_GLAZED_TERRACOTTA, - BLACK_SHULKER_BOX, - BLACK_STAINED_GLASS, - BLACK_STAINED_GLASS_PANE, - BLACK_TERRACOTTA, - BLACK_WOOL, - BLAZE_POWDER, - BLAZE_ROD, - BLAZE_SPAWN_EGG, - BLUE_BANNER, - BLUE_BED, - BLUE_CARPET, - BLUE_CONCRETE, - BLUE_CONCRETE_POWDER, - BLUE_GLAZED_TERRACOTTA, - BLUE_ICE, - BLUE_ORCHID, - BLUE_SHULKER_BOX, - BLUE_STAINED_GLASS, - BLUE_STAINED_GLASS_PANE, - BLUE_TERRACOTTA, - BLUE_WOOL, - BONE, - BONE_BLOCK, - BONE_MEAL, - BOOK, - BOOKSHELF, - BOW, - BOWL, - BRAIN_CORAL, - BRAIN_CORAL_BLOCK, - BRAIN_CORAL_FAN, - BREAD, - BREWING_STAND, - BRICK, - BRICKS, - BRICK_SLAB, - BRICK_STAIRS, - BROWN_BANNER, - BROWN_BED, - BROWN_CARPET, - BROWN_CONCRETE, - BROWN_CONCRETE_POWDER, - BROWN_GLAZED_TERRACOTTA, - BROWN_MUSHROOM, - BROWN_MUSHROOM_BLOCK, - BROWN_SHULKER_BOX, - BROWN_STAINED_GLASS, - BROWN_STAINED_GLASS_PANE, - BROWN_TERRACOTTA, - BROWN_WOOL, - BUBBLE_CORAL, - BUBBLE_CORAL_BLOCK, - BUBBLE_CORAL_FAN, - BUCKET, - CACTUS, - CACTUS_GREEN, - CAKE, - CARROT, - CARROT_ON_A_STICK, - CARVED_PUMPKIN, - CAULDRON, - CAVE_SPIDER_SPAWN_EGG, - CHAINMAIL_BOOTS, - CHAINMAIL_CHESTPLATE, - CHAINMAIL_HELMET, - CHAINMAIL_LEGGINGS, - CHAIN_COMMAND_BLOCK, - CHARCOAL, - CHEST, - CHEST_MINECART, - CHICKEN, - CHICKEN_SPAWN_EGG, - CHIPPED_ANVIL, - CHISELED_QUARTZ_BLOCK, - CHISELED_RED_SANDSTONE, - CHISELED_SANDSTONE, - CHISELED_STONE_BRICKS, - CHORUS_FLOWER, - CHORUS_FRUIT, - CHORUS_PLANT, - CLAY, - CLAY_BALL, - CLOCK, - COAL, - COAL_BLOCK, - COAL_ORE, - COARSE_DIRT, - COBBLESTONE, - COBBLESTONE_SLAB, - COBBLESTONE_STAIRS, - COBBLESTONE_WALL, - COBWEB, - COCOA_BEANS, - COD, - COD_BUCKET, - COD_SPAWN_EGG, - COMMAND_BLOCK, - COMMAND_BLOCK_MINECART, - COMPARATOR, - COMPASS, - CONDUIT, - COOKED_BEEF, - COOKED_CHICKEN, - COOKED_COD, - COOKED_MUTTON, - COOKED_PORKCHOP, - COOKED_RABBIT, - COOKED_SALMON, - COOKIE, - COW_SPAWN_EGG, - CRACKED_STONE_BRICKS, - CRAFTING_TABLE, - CREEPER_HEAD, - CREEPER_SPAWN_EGG, - CUT_RED_SANDSTONE, - CUT_SANDSTONE, - CYAN_BANNER, - CYAN_BED, - CYAN_CARPET, - CYAN_CONCRETE, - CYAN_CONCRETE_POWDER, - CYAN_DYE, - CYAN_GLAZED_TERRACOTTA, - CYAN_SHULKER_BOX, - CYAN_STAINED_GLASS, - CYAN_STAINED_GLASS_PANE, - CYAN_TERRACOTTA, - CYAN_WOOL, - DAMAGED_ANVIL, - DANDELION, - DANDELION_YELLOW, - DARK_OAK_BOAT, - DARK_OAK_BUTTON, - DARK_OAK_DOOR, - DARK_OAK_FENCE, - DARK_OAK_FENCE_GATE, - DARK_OAK_LEAVES, - DARK_OAK_LOG, - DARK_OAK_PLANKS, - DARK_OAK_PRESSURE_PLATE, - DARK_OAK_SAPLING, - DARK_OAK_SLAB, - DARK_OAK_STAIRS, - DARK_OAK_TRAPDOOR, - DARK_OAK_WOOD, - DARK_PRISMARINE, - DARK_PRISMARINE_SLAB, - DARK_PRISMARINE_STAIRS, - DAYLIGHT_DETECTOR, - DEAD_BRAIN_CORAL, - DEAD_BRAIN_CORAL_BLOCK, - DEAD_BRAIN_CORAL_FAN, - DEAD_BUBBLE_CORAL, - DEAD_BUBBLE_CORAL_BLOCK, - DEAD_BUBBLE_CORAL_FAN, - DEAD_BUSH, - DEAD_FIRE_CORAL, - DEAD_FIRE_CORAL_BLOCK, - DEAD_FIRE_CORAL_FAN, - DEAD_HORN_CORAL, - DEAD_HORN_CORAL_BLOCK, - DEAD_HORN_CORAL_FAN, - DEAD_TUBE_CORAL, - DEAD_TUBE_CORAL_BLOCK, - DEAD_TUBE_CORAL_FAN, - DEBUG_STICK, - DETECTOR_RAIL, - DIAMOND, - DIAMOND_AXE, - DIAMOND_BLOCK, - DIAMOND_BOOTS, - DIAMOND_CHESTPLATE, - DIAMOND_HELMET, - DIAMOND_HOE, - DIAMOND_HORSE_ARMOR, - DIAMOND_LEGGINGS, - DIAMOND_ORE, - DIAMOND_PICKAXE, - DIAMOND_SHOVEL, - DIAMOND_SWORD, - DIORITE, - DIRT, - DISPENSER, - DOLPHIN_SPAWN_EGG, - DONKEY_SPAWN_EGG, - DRAGON_BREATH, - DRAGON_EGG, - DRAGON_HEAD, - DRIED_KELP, - DRIED_KELP_BLOCK, - DROPPER, - DROWNED_SPAWN_EGG, - EGG, - ELDER_GUARDIAN_SPAWN_EGG, - ELYTRA, - EMERALD, - EMERALD_BLOCK, - EMERALD_ORE, - ENCHANTED_BOOK, - ENCHANTED_GOLDEN_APPLE, - ENCHANTING_TABLE, - ENDERMAN_SPAWN_EGG, - ENDERMITE_SPAWN_EGG, - ENDER_CHEST, - ENDER_EYE, - ENDER_PEARL, - END_CRYSTAL, - END_PORTAL_FRAME, - END_ROD, - END_STONE, - END_STONE_BRICKS, - EVOKER_SPAWN_EGG, - EXPERIENCE_BOTTLE, - FARMLAND, - FEATHER, - FERMENTED_SPIDER_EYE, - FERN, - FILLED_MAP, - FIREWORK_ROCKET, - FIREWORK_STAR, - FIRE_CHARGE, - FIRE_CORAL, - FIRE_CORAL_BLOCK, - FIRE_CORAL_FAN, - FISHING_ROD, - FLINT, - FLINT_AND_STEEL, - FLOWER_POT, - FURNACE, - FURNACE_MINECART, - GHAST_SPAWN_EGG, - GHAST_TEAR, - GLASS, - GLASS_BOTTLE, - GLASS_PANE, - GLISTERING_MELON_SLICE, - GLOWSTONE, - GLOWSTONE_DUST, - GOLDEN_APPLE, - GOLDEN_AXE, - GOLDEN_BOOTS, - GOLDEN_CARROT, - GOLDEN_CHESTPLATE, - GOLDEN_HELMET, - GOLDEN_HOE, - GOLDEN_HORSE_ARMOR, - GOLDEN_LEGGINGS, - GOLDEN_PICKAXE, - GOLDEN_SHOVEL, - GOLDEN_SWORD, - GOLD_BLOCK, - GOLD_INGOT, - GOLD_NUGGET, - GOLD_ORE, - GRANITE, - GRASS, - GRASS_BLOCK, - GRASS_PATH, - GRAVEL, - GRAY_BANNER, - GRAY_BED, - GRAY_CARPET, - GRAY_CONCRETE, - GRAY_CONCRETE_POWDER, - GRAY_DYE, - GRAY_GLAZED_TERRACOTTA, - GRAY_SHULKER_BOX, - GRAY_STAINED_GLASS, - GRAY_STAINED_GLASS_PANE, - GRAY_TERRACOTTA, - GRAY_WOOL, - GREEN_BANNER, - GREEN_BED, - GREEN_CARPET, - GREEN_CONCRETE, - GREEN_CONCRETE_POWDER, - GREEN_GLAZED_TERRACOTTA, - GREEN_SHULKER_BOX, - GREEN_STAINED_GLASS, - GREEN_STAINED_GLASS_PANE, - GREEN_TERRACOTTA, - GREEN_WOOL, - GUARDIAN_SPAWN_EGG, - GUNPOWDER, - HAY_BLOCK, - HEART_OF_THE_SEA, - HEAVY_WEIGHTED_PRESSURE_PLATE, - HOPPER, - HOPPER_MINECART, - HORN_CORAL, - HORN_CORAL_BLOCK, - HORN_CORAL_FAN, - HORSE_SPAWN_EGG, - HUSK_SPAWN_EGG, - ICE, - INFESTED_CHISELED_STONE_BRICKS, - INFESTED_COBBLESTONE, - INFESTED_CRACKED_STONE_BRICKS, - INFESTED_MOSSY_STONE_BRICKS, - INFESTED_STONE, - INFESTED_STONE_BRICKS, - INK_SAC, - IRON_AXE, - IRON_BARS, - IRON_BLOCK, - IRON_BOOTS, - IRON_CHESTPLATE, - IRON_DOOR, - IRON_HELMET, - IRON_HOE, - IRON_HORSE_ARMOR, - IRON_INGOT, - IRON_LEGGINGS, - IRON_NUGGET, - IRON_ORE, - IRON_PICKAXE, - IRON_SHOVEL, - IRON_SWORD, - IRON_TRAPDOOR, - ITEM_FRAME, - JACK_O_LANTERN, - JUKEBOX, - JUNGLE_BOAT, - JUNGLE_BUTTON, - JUNGLE_DOOR, - JUNGLE_FENCE, - JUNGLE_FENCE_GATE, - JUNGLE_LEAVES, - JUNGLE_LOG, - JUNGLE_PLANKS, - JUNGLE_PRESSURE_PLATE, - JUNGLE_SAPLING, - JUNGLE_SLAB, - JUNGLE_STAIRS, - JUNGLE_TRAPDOOR, - JUNGLE_WOOD, - KELP, - KNOWLEDGE_BOOK, - LADDER, - LAPIS_BLOCK, - LAPIS_LAZULI, - LAPIS_ORE, - LARGE_FERN, - LAVA_BUCKET, - LEAD, - LEATHER, - LEATHER_BOOTS, - LEATHER_CHESTPLATE, - LEATHER_HELMET, - LEATHER_LEGGINGS, - LEVER, - LIGHT_BLUE_BANNER, - LIGHT_BLUE_BED, - LIGHT_BLUE_CARPET, - LIGHT_BLUE_CONCRETE, - LIGHT_BLUE_CONCRETE_POWDER, - LIGHT_BLUE_DYE, - LIGHT_BLUE_GLAZED_TERRACOTTA, - LIGHT_BLUE_SHULKER_BOX, - LIGHT_BLUE_STAINED_GLASS, - LIGHT_BLUE_STAINED_GLASS_PANE, - LIGHT_BLUE_TERRACOTTA, - LIGHT_BLUE_WOOL, - LIGHT_GRAY_BANNER, - LIGHT_GRAY_BED, - LIGHT_GRAY_CARPET, - LIGHT_GRAY_CONCRETE, - LIGHT_GRAY_CONCRETE_POWDER, - LIGHT_GRAY_DYE, - LIGHT_GRAY_GLAZED_TERRACOTTA, - LIGHT_GRAY_SHULKER_BOX, - LIGHT_GRAY_STAINED_GLASS, - LIGHT_GRAY_STAINED_GLASS_PANE, - LIGHT_GRAY_TERRACOTTA, - LIGHT_GRAY_WOOL, - LIGHT_WEIGHTED_PRESSURE_PLATE, - LILAC, - LILY_PAD, - LIME_BANNER, - LIME_BED, - LIME_CARPET, - LIME_CONCRETE, - LIME_CONCRETE_POWDER, - LIME_DYE, - LIME_GLAZED_TERRACOTTA, - LIME_SHULKER_BOX, - LIME_STAINED_GLASS, - LIME_STAINED_GLASS_PANE, - LIME_TERRACOTTA, - LIME_WOOL, - LINGERING_POTION, - LLAMA_SPAWN_EGG, - MAGENTA_BANNER, - MAGENTA_BED, - MAGENTA_CARPET, - MAGENTA_CONCRETE, - MAGENTA_CONCRETE_POWDER, - MAGENTA_DYE, - MAGENTA_GLAZED_TERRACOTTA, - MAGENTA_SHULKER_BOX, - MAGENTA_STAINED_GLASS, - MAGENTA_STAINED_GLASS_PANE, - MAGENTA_TERRACOTTA, - MAGENTA_WOOL, - MAGMA_BLOCK, - MAGMA_CREAM, - MAGMA_CUBE_SPAWN_EGG, - MAP, - MELON, - MELON_SEEDS, - MELON_SLICE, - MILK_BUCKET, - MINECART, - MOOSHROOM_SPAWN_EGG, - MOSSY_COBBLESTONE, - MOSSY_COBBLESTONE_WALL, - MOSSY_STONE_BRICKS, - MULE_SPAWN_EGG, - MUSHROOM_STEM, - MUSHROOM_STEW, - MUSIC_DISC_11, - MUSIC_DISC_13, - MUSIC_DISC_BLOCKS, - MUSIC_DISC_CAT, - MUSIC_DISC_CHIRP, - MUSIC_DISC_FAR, - MUSIC_DISC_MALL, - MUSIC_DISC_MELLOHI, - MUSIC_DISC_STAL, - MUSIC_DISC_STRAD, - MUSIC_DISC_WAIT, - MUSIC_DISC_WARD, - MUTTON, - MYCELIUM, - NAME_TAG, - NAUTILUS_SHELL, - NETHERRACK, - NETHER_BRICK, - NETHER_BRICKS, - NETHER_BRICK_FENCE, - NETHER_BRICK_SLAB, - NETHER_BRICK_STAIRS, - NETHER_QUARTZ_ORE, - NETHER_STAR, - NETHER_WART, - NETHER_WART_BLOCK, - NOTE_BLOCK, - OAK_BOAT, - OAK_BUTTON, - OAK_DOOR, - OAK_FENCE, - OAK_FENCE_GATE, - OAK_LEAVES, - OAK_LOG, - OAK_PLANKS, - OAK_PRESSURE_PLATE, - OAK_SAPLING, - OAK_SLAB, - OAK_STAIRS, - OAK_TRAPDOOR, - OAK_WOOD, - OBSERVER, - OBSIDIAN, - OCELOT_SPAWN_EGG, - ORANGE_BANNER, - ORANGE_BED, - ORANGE_CARPET, - ORANGE_CONCRETE, - ORANGE_CONCRETE_POWDER, - ORANGE_DYE, - ORANGE_GLAZED_TERRACOTTA, - ORANGE_SHULKER_BOX, - ORANGE_STAINED_GLASS, - ORANGE_STAINED_GLASS_PANE, - ORANGE_TERRACOTTA, - ORANGE_TULIP, - ORANGE_WOOL, - OXEYE_DAISY, - PACKED_ICE, - PAINTING, - PAPER, - PARROT_SPAWN_EGG, - PEONY, - PETRIFIED_OAK_SLAB, - PHANTOM_MEMBRANE, - PHANTOM_SPAWN_EGG, - PIG_SPAWN_EGG, - PINK_BANNER, - PINK_BED, - PINK_CARPET, - PINK_CONCRETE, - PINK_CONCRETE_POWDER, - PINK_DYE, - PINK_GLAZED_TERRACOTTA, - PINK_SHULKER_BOX, - PINK_STAINED_GLASS, - PINK_STAINED_GLASS_PANE, - PINK_TERRACOTTA, - PINK_TULIP, - PINK_WOOL, - PISTON, - PLAYER_HEAD, - PODZOL, - POISONOUS_POTATO, - POLAR_BEAR_SPAWN_EGG, - POLISHED_ANDESITE, - POLISHED_DIORITE, - POLISHED_GRANITE, - POPPED_CHORUS_FRUIT, - POPPY, - PORKCHOP, - POTATO, - POTION, - POWERED_RAIL, - PRISMARINE, - PRISMARINE_BRICKS, - PRISMARINE_BRICK_SLAB, - PRISMARINE_BRICK_STAIRS, - PRISMARINE_CRYSTALS, - PRISMARINE_SHARD, - PRISMARINE_SLAB, - PRISMARINE_STAIRS, - PUFFERFISH, - PUFFERFISH_BUCKET, - PUFFERFISH_SPAWN_EGG, - PUMPKIN, - PUMPKIN_PIE, - PUMPKIN_SEEDS, - PURPLE_BANNER, - PURPLE_BED, - PURPLE_CARPET, - PURPLE_CONCRETE, - PURPLE_CONCRETE_POWDER, - PURPLE_DYE, - PURPLE_GLAZED_TERRACOTTA, - PURPLE_SHULKER_BOX, - PURPLE_STAINED_GLASS, - PURPLE_STAINED_GLASS_PANE, - PURPLE_TERRACOTTA, - PURPLE_WOOL, - PURPUR_BLOCK, - PURPUR_PILLAR, - PURPUR_SLAB, - PURPUR_STAIRS, - QUARTZ, - QUARTZ_BLOCK, - QUARTZ_PILLAR, - QUARTZ_SLAB, - QUARTZ_STAIRS, - RABBIT, - RABBIT_FOOT, - RABBIT_HIDE, - RABBIT_SPAWN_EGG, - RABBIT_STEW, - RAIL, - REDSTONE, - REDSTONE_BLOCK, - REDSTONE_LAMP, - REDSTONE_ORE, - REDSTONE_TORCH, - RED_BANNER, - RED_BED, - RED_CARPET, - RED_CONCRETE, - RED_CONCRETE_POWDER, - RED_GLAZED_TERRACOTTA, - RED_MUSHROOM, - RED_MUSHROOM_BLOCK, - RED_NETHER_BRICKS, - RED_SAND, - RED_SANDSTONE, - RED_SANDSTONE_SLAB, - RED_SANDSTONE_STAIRS, - RED_SHULKER_BOX, - RED_STAINED_GLASS, - RED_STAINED_GLASS_PANE, - RED_TERRACOTTA, - RED_TULIP, - RED_WOOL, - REPEATER, - REPEATING_COMMAND_BLOCK, - ROSE_BUSH, - ROSE_RED, - ROTTEN_FLESH, - SADDLE, - SALMON, - SALMON_BUCKET, - SALMON_SPAWN_EGG, - SAND, - SANDSTONE, - SANDSTONE_SLAB, - SANDSTONE_STAIRS, - SCUTE, - SEAGRASS, - SEA_LANTERN, - SEA_PICKLE, - SHEARS, - SHEEP_SPAWN_EGG, - SHIELD, - SHULKER_BOX, - SHULKER_SHELL, - SHULKER_SPAWN_EGG, - SIGN, - SILVERFISH_SPAWN_EGG, - SKELETON_HORSE_SPAWN_EGG, - SKELETON_SKULL, - SKELETON_SPAWN_EGG, - SLIME_BALL, - SLIME_BLOCK, - SLIME_SPAWN_EGG, - SMOOTH_QUARTZ, - SMOOTH_RED_SANDSTONE, - SMOOTH_SANDSTONE, - SMOOTH_STONE, - SNOW, - SNOWBALL, - SNOW_BLOCK, - SOUL_SAND, - SPAWNER, - SPECTRAL_ARROW, - SPIDER_EYE, - SPIDER_SPAWN_EGG, - SPLASH_POTION, - SPONGE, - SPRUCE_BOAT, - SPRUCE_BUTTON, - SPRUCE_DOOR, - SPRUCE_FENCE, - SPRUCE_FENCE_GATE, - SPRUCE_LEAVES, - SPRUCE_LOG, - SPRUCE_PLANKS, - SPRUCE_PRESSURE_PLATE, - SPRUCE_SAPLING, - SPRUCE_SLAB, - SPRUCE_STAIRS, - SPRUCE_TRAPDOOR, - SPRUCE_WOOD, - SQUID_SPAWN_EGG, - STICK, - STICKY_PISTON, - STONE, - STONE_AXE, - STONE_BRICKS, - STONE_BRICK_SLAB, - STONE_BRICK_STAIRS, - STONE_BUTTON, - STONE_HOE, - STONE_PICKAXE, - STONE_PRESSURE_PLATE, - STONE_SHOVEL, - STONE_SLAB, - STONE_SWORD, - STRAY_SPAWN_EGG, - STRING, - STRIPPED_ACACIA_LOG, - STRIPPED_ACACIA_WOOD, - STRIPPED_BIRCH_LOG, - STRIPPED_BIRCH_WOOD, - STRIPPED_DARK_OAK_LOG, - STRIPPED_DARK_OAK_WOOD, - STRIPPED_JUNGLE_LOG, - STRIPPED_JUNGLE_WOOD, - STRIPPED_OAK_LOG, - STRIPPED_OAK_WOOD, - STRIPPED_SPRUCE_LOG, - STRIPPED_SPRUCE_WOOD, - STRUCTURE_BLOCK, - STRUCTURE_VOID, - SUGAR, - SUGAR_CANE, - SUNFLOWER, - TALL_GRASS, - TERRACOTTA, - TIPPED_ARROW, - TNT, - TNT_MINECART, - TORCH, - TOTEM_OF_UNDYING, - TRAPPED_CHEST, - TRIDENT, - TRIPWIRE_HOOK, - TROPICAL_FISH, - TROPICAL_FISH_BUCKET, - TROPICAL_FISH_SPAWN_EGG, - TUBE_CORAL, - TUBE_CORAL_BLOCK, - TUBE_CORAL_FAN, - TURTLE_EGG, - TURTLE_HELMET, - TURTLE_SPAWN_EGG, - VEX_SPAWN_EGG, - VILLAGER_SPAWN_EGG, - VINDICATOR_SPAWN_EGG, - VINE, - WATER_BUCKET, - WET_SPONGE, - WHEAT, - WHEAT_SEEDS, - WHITE_BANNER, - WHITE_BED, - WHITE_CARPET, - WHITE_CONCRETE, - WHITE_CONCRETE_POWDER, - WHITE_GLAZED_TERRACOTTA, - WHITE_SHULKER_BOX, - WHITE_STAINED_GLASS, - WHITE_STAINED_GLASS_PANE, - WHITE_TERRACOTTA, - WHITE_TULIP, - WHITE_WOOL, - WITCH_SPAWN_EGG, - WITHER_SKELETON_SKULL, - WITHER_SKELETON_SPAWN_EGG, - WOLF_SPAWN_EGG, - WOODEN_AXE, - WOODEN_HOE, - WOODEN_PICKAXE, - WOODEN_SHOVEL, - WOODEN_SWORD, - WRITABLE_BOOK, - WRITTEN_BOOK, - YELLOW_BANNER, - YELLOW_BED, - YELLOW_CARPET, - YELLOW_CONCRETE, - YELLOW_CONCRETE_POWDER, - YELLOW_GLAZED_TERRACOTTA, - YELLOW_SHULKER_BOX, - YELLOW_STAINED_GLASS, - YELLOW_STAINED_GLASS_PANE, - YELLOW_TERRACOTTA, - YELLOW_WOOL, - ZOMBIE_HEAD, - ZOMBIE_HORSE_SPAWN_EGG, - ZOMBIE_PIGMAN_SPAWN_EGG, - ZOMBIE_SPAWN_EGG, - ZOMBIE_VILLAGER_SPAWN_EGG, - - ; - - /* - ----------------------------------------------------- - Instance - ----------------------------------------------------- - */ - - private BlockTypes blockType; - private String id; - private BaseItem defaultState; - private int internalId; - - ItemTypes() { - this(null); + private ItemTypes() { } - ItemTypes(String id) { - init(id); + private static ItemType register(final String id) { + return register(new ItemType(id)); } - private void init(String id) { - if (id == null) id = "minecraft:" + name().toLowerCase(); - // If it has no namespace, assume minecraft. - else if (!id.contains(":")) { - id = "minecraft:" + id; - } - this.id = id; - this.defaultState = new BaseItemStack(this, 1); - this.internalId = ordinal(); + public static ItemType register(final ItemType item) { + if(sortedRegistry == null) + sortedRegistry = new ArrayList<>(); + if(!sortedRegistry.contains(item))sortedRegistry.add(item); +// return ItemType.REGISTRY.register(item.getId(), item); + return internalRegister(item); } - private void setBlockType(BlockTypes type) { - this.blockType = type; + public static @Nullable ItemType get(final String id) { + return ItemType.REGISTRY.get(id); + } + + private static ArrayList sortedRegistry; + + public static ItemType[] values() { + return sortedRegistry.toArray(new ItemType[sortedRegistry.size()]); } - @Override - public BaseItem getDefaultState() { - return defaultState; - } - - public String getId() { - return this.id; - } - - @Deprecated - public int getInternalId() { - return this.internalId; - } - - /** - * Gets the name of this item, or the ID if the name cannot be found. - * - * @return The name, or ID - */ - public String getName() { - BundledItemData.ItemEntry entry = BundledItemData.getInstance().findById(this.id); - if (entry == null) { - return getId(); - } else { - return entry.localizedName; - } - } - - - /** - * Gets whether this item type has a block representation. - * - * @return If it has a block - */ - public boolean hasBlockType() { - return getBlockType() != null; - } - - /** - * Gets the block representation of this item type, if it exists. - * - * @return The block representation - */ @Nullable - public BlockTypes getBlockType() { - return blockType; - } - - @Override - public String toString() { - return getId(); - } - - /* - ----------------------------------------------------- - Static Initializer - ----------------------------------------------------- - */ - private static final Map $REGISTRY = new HashMap<>(); - private static int $LENGTH; - public static final ItemTypes[] values; - - static { - try { - Collection items = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getItemRegistry().registerItems(); - ItemTypes[] oldValues = values(); - $LENGTH = oldValues.length; - LinkedHashSet newValues = new LinkedHashSet<>(Arrays.asList(oldValues)); - if (!items.isEmpty()) { // No types found - use defaults - for (String item : items) { - ItemTypes registered = register(item); - if (!newValues.contains(registered)) newValues.add(registered); - } - } - // Cache the values - values = newValues.toArray(new ItemTypes[newValues.size()]); - } catch (Throwable e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - public static ItemTypes parse(String input) { + public static ItemType parse(String input) { input = input.toLowerCase(); if (!Character.isAlphabetic(input.charAt(0))) { try { - ItemTypes legacy = LegacyMapper.getInstance().getItemFromLegacy(input); + ItemType legacy = LegacyMapper.getInstance().getItemFromLegacy(input); if (legacy != null) return legacy; } catch (NumberFormatException e) { e.printStackTrace(); @@ -965,40 +866,18 @@ public enum ItemTypes implements ItemType { } if (!input.split("\\[", 2)[0].contains(":")) input = "minecraft:" + input; - ItemTypes result = $REGISTRY.get(input); - if (result != null) return result; - return null; + ItemType result = get(input); + return result; } - private static ItemTypes register(final String id) { - // Get the enum name (remove namespace if minecraft:) - int propStart = id.indexOf('['); - String typeName = id.substring(0, propStart == -1 ? id.length() : propStart); - String enumName = (typeName.startsWith("minecraft:") ? typeName.substring(10) : typeName).toUpperCase(); - // Check existing - ItemTypes existing = null; - try { existing = valueOf(enumName.toUpperCase()); } catch (IllegalArgumentException ignore) {} - if (existing == null) { - existing = ReflectionUtils.addEnum(ItemTypes.class, enumName); - } - int internalId = existing.ordinal(); - if (existing.id == null) { - existing.init(null); - } - if (internalId == 0 && existing != __RESERVED__) { - existing.internalId = $LENGTH++; - } - if (typeName.startsWith("minecraft:")) $REGISTRY.put(typeName.substring(10), existing); - $REGISTRY.put(typeName, existing); - return existing; + private static ItemType internalRegister(final ItemType type) { + type.setInternalId(sortedRegistry.indexOf(type)); + type.setDefaultState(new BaseItemStack(type, 1)); + return ItemType.REGISTRY.register(type.getId(), type); } - public static final @Nullable ItemTypes get(final String id) { - return $REGISTRY.get(id); - } - - public static final @Nullable ItemTypes get(BlockTypes type) { - ItemTypes item = $REGISTRY.get(type.getId()); + public static final @Nullable ItemType get(BlockType type) { + ItemType item = get(type.getId()); if (item != null && item.getBlockType() == null) { item.setBlockType(type); } @@ -1006,11 +885,11 @@ public enum ItemTypes implements ItemType { } @Deprecated - public static final ItemTypes get(final int ordinal) { - return values[ordinal]; + public static final ItemType get(final int ordinal) { + return values()[ordinal]; } public static int size() { - return values.length; + return values().length; } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BlockMaterial.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BlockMaterial.java similarity index 98% rename from worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BlockMaterial.java rename to worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BlockMaterial.java index 86b010819..52220730b 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/blocks/BlockMaterial.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BlockMaterial.java @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -package com.sk89q.worldedit.blocks; +package com.sk89q.worldedit.world.registry; /** * Describes the material for a block. 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 50d212a08..176e77a8f 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 @@ -19,7 +19,6 @@ package com.sk89q.worldedit.world.registry; -import com.sk89q.worldedit.blocks.BlockMaterial; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockType; @@ -36,6 +35,15 @@ import javax.annotation.Nullable; */ public interface BlockRegistry { + /** + * Gets the name for the given block. + * + * @param blockType the block + * @return The name, or null if it's unknown + */ + @Nullable + String getName(BlockType blockType); + /** * Get the material for the given block. * @@ -56,8 +64,7 @@ public interface BlockRegistry { * @param blockType the block * @return a map of states where the key is the state's ID */ - Map getProperties(BlockType blockType); - + Map> getProperties(BlockType blockType); /** * Register all blocks diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockData.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockData.java index ad34a0a86..9023fefd5 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockData.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockData.java @@ -22,8 +22,7 @@ package com.sk89q.worldedit.world.registry; import com.google.common.io.Resources; import com.google.gson.*; import com.google.gson.reflect.TypeToken; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BlockMaterial; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.gson.VectorAdapter; import java.io.IOException; @@ -74,7 +73,8 @@ public class BundledBlockData { */ private void loadFromResource() throws IOException { GsonBuilder gsonBuilder = new GsonBuilder(); - gsonBuilder.registerTypeAdapter(Vector.class, new VectorAdapter()); +//<<<<<<< HEAD + gsonBuilder.registerTypeAdapter(Vector3.class, new VectorAdapter()); gsonBuilder.registerTypeAdapter(int.class, new JsonDeserializer() { @Override public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { @@ -87,6 +87,9 @@ public class BundledBlockData { return primitive.getAsInt(); } }); +//======= +// gsonBuilder.registerTypeAdapter(Vector3.class, new VectorAdapter()); +//>>>>>>> 399e0ad5... Refactor vector system to be cleaner Gson gson = gsonBuilder.create(); URL url = BundledBlockData.class.getResource("blocks.json"); if (url == null) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockRegistry.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockRegistry.java index 1f1a2b317..62c8b5c3a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockRegistry.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledBlockRegistry.java @@ -19,7 +19,6 @@ package com.sk89q.worldedit.world.registry; -import com.sk89q.worldedit.blocks.BlockMaterial; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.world.block.BlockType; @@ -34,6 +33,13 @@ import javax.annotation.Nullable; */ public class BundledBlockRegistry implements BlockRegistry { + @Nullable + @Override + public String getName(BlockType blockType) { + BundledBlockData.BlockEntry blockEntry = BundledBlockData.getInstance().findById(blockType.getId()); + return blockEntry != null ? blockEntry.localizedName : null; + } + @Nullable @Override public BlockMaterial getMaterial(BlockType blockType) { @@ -42,7 +48,7 @@ public class BundledBlockRegistry implements BlockRegistry { @Nullable @Override - public Map getProperties(BlockType blockType) { + public Map> getProperties(BlockType blockType) { return Collections.emptyMap(); // Oof } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemData.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemData.java index 00cafb244..2867b2e56 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemData.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemData.java @@ -23,7 +23,7 @@ import com.google.common.io.Resources; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.gson.VectorAdapter; import java.io.IOException; @@ -73,7 +73,7 @@ public class BundledItemData { */ private void loadFromResource() throws IOException { GsonBuilder gsonBuilder = new GsonBuilder(); - gsonBuilder.registerTypeAdapter(Vector.class, new VectorAdapter()); + gsonBuilder.registerTypeAdapter(Vector3.class, new VectorAdapter()); Gson gson = gsonBuilder.create(); URL url = BundledItemData.class.getResource("items.json"); if (url == null) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemRegistry.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemRegistry.java index 6827a0e9c..4af6acaaf 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemRegistry.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/BundledItemRegistry.java @@ -44,4 +44,11 @@ public class BundledItemRegistry implements ItemRegistry { public Collection registerItems() { return Collections.emptyList(); } + + @Nullable + @Override + public String getName(ItemType itemType) { + BundledItemData.ItemEntry itemEntry = BundledItemData.getInstance().findById(itemType.getId()); + return itemEntry != null ? itemEntry.localizedName : null; + } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/CategoryRegistry.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/CategoryRegistry.java index 1a54c7961..496893821 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/CategoryRegistry.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/CategoryRegistry.java @@ -37,12 +37,4 @@ public interface CategoryRegistry { Set getCategorisedByName(String category); Set getAll(final Category category); - - /** - * Gets a list of categories given to a value. - * - * @param categorised The value - * @return A set of categories - */ - Set getCategories(T categorised); } 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 bbfec725f..ff879c6b8 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 @@ -22,6 +22,7 @@ package com.sk89q.worldedit.world.registry; import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; +import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.entity.EntityTypes; import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemTypes; @@ -43,7 +44,7 @@ public interface EntityRegistry { */ @Nullable default BaseEntity createFromId(String id) { - EntityTypes entType = EntityTypes.get(id); + EntityType entType = EntityTypes.get(id); return entType == null ? null : new BaseEntity(entType); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/ItemRegistry.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/ItemRegistry.java index d9d30a7fe..5e46af3fe 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/ItemRegistry.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/ItemRegistry.java @@ -20,6 +20,7 @@ package com.sk89q.worldedit.world.registry; import com.sk89q.worldedit.blocks.BaseItem; +import com.sk89q.worldedit.world.item.ItemType; import javax.annotation.Nullable; import java.util.Collection; @@ -42,5 +43,14 @@ public interface ItemRegistry { default Collection registerItems() { return Collections.emptyList(); } + + /** + * Gets the name for the given item. + * + * @param itemType the item + * @return The name, or null if it's unknown + */ + @Nullable + String getName(ItemType itemType); } 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 148d22db2..369578dfa 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 @@ -19,14 +19,21 @@ package com.sk89q.worldedit.world.registry; +import com.github.intellectualsites.plotsquared.plot.object.LegacyPlotBlock; +import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.github.intellectualsites.plotsquared.plot.object.StringPlotBlock; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.io.Resources; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.registry.state.PropertyKey; +import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.input.ParserContext; +import com.sk89q.worldedit.math.Vector3; +import com.sk89q.worldedit.util.gson.VectorAdapter; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockType; @@ -54,7 +61,7 @@ public class LegacyMapper { private final Int2ObjectArrayMap blockStateToLegacyId4Data = new Int2ObjectArrayMap<>(); private final Int2ObjectArrayMap extraId4DataToStateId = new Int2ObjectArrayMap<>(); private final int[] blockArr = new int[4096]; - private final BiMap itemMap = HashBiMap.create(); + private final BiMap itemMap = HashBiMap.create(); /** * Create a new instance. @@ -75,7 +82,7 @@ public class LegacyMapper { */ private void loadFromResource() throws IOException { GsonBuilder gsonBuilder = new GsonBuilder(); - gsonBuilder.registerTypeAdapter(Vector.class, new VectorAdapter()); + gsonBuilder.registerTypeAdapter(Vector3.class, new VectorAdapter()); Gson gson = gsonBuilder.disableHtmlEscaping().create(); URL url = LegacyMapper.class.getResource("legacy.json"); if (url == null) { @@ -92,7 +99,8 @@ public class LegacyMapper { for (Map.Entry blockEntry : dataFile.blocks.entrySet()) { try { BlockStateHolder blockState = BlockState.get(null, blockEntry.getValue()); - BlockTypes type = blockState.getBlockType(); +// BlockState blockState = WorldEdit.getInstance().getBlockFactory().parseFromInput(blockEntry.getValue(), parserContext).toImmutableState(); + BlockType type = blockState.getBlockType(); if (type.hasProperty(PropertyKey.WATERLOGGED)) { blockState = blockState.with(PropertyKey.WATERLOGGED, false); } @@ -130,11 +138,11 @@ public class LegacyMapper { } @Nullable - public ItemTypes getItemFromLegacy(int legacyId) { + public ItemType getItemFromLegacy(int legacyId) { return itemMap.get(legacyId << 4); } - public ItemTypes getItemFromLegacy(String input) { + public ItemType getItemFromLegacy(String input) { if (input.startsWith("minecraft:")) input = input.substring(10); return itemMap.get(getCombinedId(input)); } @@ -145,7 +153,7 @@ public class LegacyMapper { } @Nullable - public ItemTypes getItemFromLegacy(int legacyId, int data) { + public ItemType getItemFromLegacy(int legacyId, int data) { return itemMap.get((legacyId << 4) + data); } @@ -218,6 +226,29 @@ public class LegacyMapper { Integer combinedId = getLegacyCombined(blockState); return combinedId == null ? null : new int[] { combinedId >> 4, combinedId & 0xF }; } + + public BaseBlock getBaseBlockFromPlotBlock(PlotBlock plotBlock) { + if(plotBlock instanceof StringPlotBlock) { + try { + return BlockTypes.get(plotBlock.toString()).getDefaultState().toBaseBlock(); + }catch(Throwable failed) { + log.severe("Unable to convert StringPlotBlock " + plotBlock + " to BaseBlock!"); + failed.printStackTrace(); + return null; + } + }else if(plotBlock instanceof LegacyPlotBlock) { + try { + return new BaseBlock(((LegacyPlotBlock)plotBlock).getId(), ((LegacyPlotBlock)plotBlock).getData()); + }catch(Throwable failed) { + log.severe("Unable to convert LegacyPlotBlock " + plotBlock + " to BaseBlock!"); + failed.printStackTrace(); + return null; + } + }else { + log.severe("Unable to convert LegacyPlotBlock " + plotBlock + " to BaseBlock!"); + return null; + } + } public static LegacyMapper getInstance() { if (INSTANCE == null) { @@ -226,7 +257,7 @@ public class LegacyMapper { return INSTANCE; } - @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection", "unused"}) + @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) private static class LegacyDataFile { private Map blocks; private Map items; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/NullBlockCategoryRegistry.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/NullBlockCategoryRegistry.java index b26286498..4484d67d2 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/NullBlockCategoryRegistry.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/NullBlockCategoryRegistry.java @@ -36,9 +36,4 @@ public class NullBlockCategoryRegistry implements BlockCategoryRegistry { public Set getAll(final Category category) { return Collections.emptySet(); } - - @Override - public Set getCategories(BlockType categorised) { - return Collections.emptySet(); - } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/NullItemCategoryRegistry.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/NullItemCategoryRegistry.java index d047706c2..8eb5d9ee6 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/NullItemCategoryRegistry.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/NullItemCategoryRegistry.java @@ -36,9 +36,4 @@ public class NullItemCategoryRegistry implements ItemCategoryRegistry { public Set getAll(final Category category) { return Collections.emptySet(); } - - @Override - public Set getCategories(ItemType categorised) { - return Collections.emptySet(); - } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/PassthroughBlockMaterial.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/PassthroughBlockMaterial.java index d3421bb6e..17436f1f3 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/PassthroughBlockMaterial.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/PassthroughBlockMaterial.java @@ -19,8 +19,6 @@ package com.sk89q.worldedit.world.registry; -import com.sk89q.worldedit.blocks.BlockMaterial; - import javax.annotation.Nullable; public class PassthroughBlockMaterial implements BlockMaterial { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/SimpleBlockMaterial.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/SimpleBlockMaterial.java index 66dfc7aa7..6a8b2b378 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/SimpleBlockMaterial.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/registry/SimpleBlockMaterial.java @@ -19,9 +19,7 @@ package com.sk89q.worldedit.world.registry; -import com.sk89q.worldedit.blocks.BlockMaterial; - -public class SimpleBlockMaterial implements BlockMaterial { +class SimpleBlockMaterial implements BlockMaterial { private boolean isAir; private boolean fullCube; 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 d3ca0c251..58525a7d2 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 @@ -133,9 +133,10 @@ public class Snapshot implements Comparable { public boolean containsWorld(String worldname) { try { if (file.getName().toLowerCase().endsWith(".zip")) { - ZipFile entry = new ZipFile(file); - return (entry.getEntry(worldname) != null - || entry.getEntry(worldname + "/level.dat") != null); + try (ZipFile entry = new ZipFile(file)) { + return (entry.getEntry(worldname) != null + || entry.getEntry(worldname + "/level.dat") != null); + } } else if (file.getName().toLowerCase().endsWith(".tar.bz2") || file.getName().toLowerCase().endsWith(".tar.gz") || file.getName().toLowerCase().endsWith(".tar")) { 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 d812e13e5..4a128409c 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 @@ -19,11 +19,11 @@ package com.sk89q.worldedit.world.snapshot; -import com.sk89q.worldedit.BlockVector2D; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.DataException; @@ -42,11 +42,11 @@ import java.util.Map; */ public class SnapshotRestore { - private final Map> neededChunks = new LinkedHashMap<>(); + private final Map> neededChunks = new LinkedHashMap<>(); private final ChunkStore chunkStore; private final EditSession editSession; - private ArrayList missingChunks; - private ArrayList errorChunks; + private ArrayList missingChunks; + private ArrayList errorChunks; private String lastErrorMessage; /** @@ -73,15 +73,15 @@ public class SnapshotRestore { * @param region The {@link Region} to iterate */ private void findNeededCuboidChunks(Region region) { - Vector min = region.getMinimumPoint(); - Vector max = region.getMaximumPoint(); + BlockVector3 min = region.getMinimumPoint(); + BlockVector3 max = region.getMaximumPoint(); // First, we need to group points by chunk so that we only need // to keep one chunk in memory at any given moment for (int x = min.getBlockX(); x <= max.getBlockX(); ++x) { for (int y = min.getBlockY(); y <= max.getBlockY(); ++y) { for (int z = min.getBlockZ(); z <= max.getBlockZ(); ++z) { - Vector pos = new Vector(x, y, z); + BlockVector3 pos = BlockVector3.at(x, y, z); checkAndAddBlock(pos); } } @@ -96,16 +96,16 @@ public class SnapshotRestore { private void findNeededChunks(Region region) { // First, we need to group points by chunk so that we only need // to keep one chunk in memory at any given moment - for (Vector pos : region) { + for (BlockVector3 pos : region) { checkAndAddBlock(pos); } } - private void checkAndAddBlock(Vector pos) { + private void checkAndAddBlock(BlockVector3 pos) { if (editSession.getMask() != null && !editSession.getMask().test(pos)) return; - BlockVector2D chunkPos = ChunkStore.toChunk(pos); + BlockVector2 chunkPos = ChunkStore.toChunk(pos); // Unidentified chunk if (!neededChunks.containsKey(chunkPos)) { @@ -135,8 +135,8 @@ public class SnapshotRestore { errorChunks = new ArrayList<>(); // Now let's start restoring! - for (Map.Entry> entry : neededChunks.entrySet()) { - BlockVector2D chunkPos = entry.getKey(); + for (Map.Entry> entry : neededChunks.entrySet()) { + BlockVector2 chunkPos = entry.getKey(); Chunk chunk; try { @@ -144,7 +144,7 @@ public class SnapshotRestore { // Good, the chunk could be at least loaded // Now just copy blocks! - for (Vector pos : entry.getValue()) { + for (BlockVector3 pos : entry.getValue()) { try { editSession.setBlock(pos, chunk.getBlock(pos)); } catch (DataException e) { @@ -166,7 +166,7 @@ public class SnapshotRestore { * * @return a list of coordinates */ - public List getMissingChunks() { + public List getMissingChunks() { return missingChunks; } @@ -176,7 +176,7 @@ public class SnapshotRestore { * * @return a list of coordinates */ - public List getErrorChunks() { + public List getErrorChunks() { return errorChunks; } 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 a2d5da198..319503740 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 @@ -21,9 +21,8 @@ package com.sk89q.worldedit.world.storage; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.BlockVector2D; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.DataException; import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.chunk.AnvilChunk; @@ -57,11 +56,8 @@ public abstract class ChunkStore implements Closeable { * @param position the position * @return chunk coordinates */ - public static BlockVector2D toChunk(Vector position) { - int chunkX = (int) Math.floor(position.getBlockX() / 16.0); - int chunkZ = (int) Math.floor(position.getBlockZ() / 16.0); - - return new BlockVector2D(chunkX, chunkZ); + public static BlockVector2 toChunk(BlockVector3 position) { + return BlockVector2.at(position.getX() >> CHUNK_SHIFTS, position.getZ() >> CHUNK_SHIFTS); } /** @@ -72,7 +68,7 @@ public abstract class ChunkStore implements Closeable { * @throws DataException thrown on data error * @throws IOException thrown on I/O error */ - public abstract CompoundTag getChunkTag(Vector2D position, World world) throws DataException, IOException; + public abstract CompoundTag getChunkTag(BlockVector2 position, World world) throws DataException, IOException; /** * Get a chunk at a location. @@ -83,7 +79,7 @@ public abstract class ChunkStore implements Closeable { * @throws DataException thrown on data error * @throws IOException thrown on I/O error */ - public Chunk getChunk(Vector2D position, World world) throws DataException, IOException { + public Chunk getChunk(BlockVector2 position, World world) throws DataException, IOException { CompoundTag rootTag = getChunkTag(position, world); Map children = rootTag.getValue(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/LegacyChunkStore.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/LegacyChunkStore.java index 0bdf4c6da..4d193b694 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/LegacyChunkStore.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/LegacyChunkStore.java @@ -22,7 +22,7 @@ package com.sk89q.worldedit.world.storage; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.NBTInputStream; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.world.DataException; import com.sk89q.worldedit.world.World; @@ -46,7 +46,7 @@ public abstract class LegacyChunkStore extends ChunkStore { * @param separator folder separator character * @return pathname */ - public static String getFilename(Vector2D position, String separator) { + public static String getFilename(BlockVector2 position, String separator) { int x = position.getBlockX(); int z = position.getBlockZ(); @@ -65,12 +65,12 @@ public abstract class LegacyChunkStore extends ChunkStore { * @param position chunk position * @return pathname */ - public static String getFilename(Vector2D position) { + public static String getFilename(BlockVector2 position) { return getFilename(position, File.separator); } @Override - public CompoundTag getChunkTag(Vector2D position, World world) throws DataException, IOException { + public CompoundTag getChunkTag(BlockVector2 position, World world) throws DataException, IOException { int x = position.getBlockX(); int z = position.getBlockZ(); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/McRegionChunkStore.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/McRegionChunkStore.java index 7959d8a37..5c4eabfd9 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/McRegionChunkStore.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/McRegionChunkStore.java @@ -22,13 +22,12 @@ package com.sk89q.worldedit.world.storage; import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.NBTInputStream; import com.sk89q.jnbt.Tag; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.world.DataException; import com.sk89q.worldedit.world.World; import java.io.IOException; import java.io.InputStream; -import java.util.Map; public abstract class McRegionChunkStore extends ChunkStore { @@ -41,14 +40,14 @@ public abstract class McRegionChunkStore extends ChunkStore { * @param position chunk position * @return the filename */ - public static String getFilename(Vector2D position) { + public static String getFilename(BlockVector2 position) { int x = position.getBlockX(); int z = position.getBlockZ(); return "r." + (x >> 5) + "." + (z >> 5) + ".mca"; } - protected McRegionReader getReader(Vector2D pos, String worldname) throws DataException, IOException { + protected McRegionReader getReader(BlockVector2 pos, String worldname) throws DataException, IOException { String filename = getFilename(pos); if (curFilename != null) { if (curFilename.equals(filename)) { @@ -67,7 +66,7 @@ public abstract class McRegionChunkStore extends ChunkStore { } @Override - public CompoundTag getChunkTag(Vector2D position, World world) throws DataException, IOException { + public CompoundTag getChunkTag(BlockVector2 position, World world) throws DataException, IOException { McRegionReader reader = getReader(position, world.getName()); InputStream stream = reader.getChunkInputStream(position); diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/McRegionReader.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/McRegionReader.java index 6f4509267..e991216ae 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/McRegionReader.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/McRegionReader.java @@ -55,7 +55,7 @@ package com.sk89q.worldedit.world.storage; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.util.io.ForwardSeekableInputStream; import com.sk89q.worldedit.world.DataException; @@ -120,7 +120,7 @@ public class McRegionReader { * @throws IOException * @throws DataException */ - public synchronized InputStream getChunkInputStream(Vector2D position) throws IOException, DataException { + public synchronized InputStream getChunkInputStream(BlockVector2 position) throws IOException, DataException { int x = position.getBlockX() & 31; int z = position.getBlockZ() & 31; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/MissingChunkException.java b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/MissingChunkException.java index 0ed5c0554..9d1d7c3a1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/MissingChunkException.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/world/storage/MissingChunkException.java @@ -19,20 +19,20 @@ package com.sk89q.worldedit.world.storage; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.Vector2; /** * Thrown if a chunk is missing. */ public class MissingChunkException extends ChunkStoreException { - private Vector2D position; + private Vector2 position; public MissingChunkException() { super(); } - public MissingChunkException(Vector2D position) { + public MissingChunkException(Vector2 position) { super(); this.position = position; } @@ -42,7 +42,7 @@ public class MissingChunkException extends ChunkStoreException { * * @return a chunk position */ - public Vector2D getChunkPosition() { + public Vector2 getChunkPosition() { return position; } diff --git a/worldedit-core/src/test/java/com/sk89q/minecraft/util/commands/CommandContextTest.java b/worldedit-core/src/test/java/com/sk89q/minecraft/util/commands/CommandContextTest.java index bcdf19dd2..025981e6e 100644 --- a/worldedit-core/src/test/java/com/sk89q/minecraft/util/commands/CommandContextTest.java +++ b/worldedit-core/src/test/java/com/sk89q/minecraft/util/commands/CommandContextTest.java @@ -38,7 +38,7 @@ public class CommandContextTest { @Before public void setUpTest() { try { - firstCommand = new CommandContext(firstCmdString, new HashSet(Arrays.asList('o', 'w'))); + firstCommand = new CommandContext(firstCmdString, new HashSet<>(Arrays.asList('o', 'w'))); } catch (CommandException e) { log.log(Level.WARNING, "Error", e); fail("Unexpected exception when creating CommandContext"); @@ -48,7 +48,7 @@ public class CommandContextTest { @Test(expected = CommandException.class) public void testInvalidFlags() throws CommandException { final String failingCommand = "herpderp -opw testers"; - new CommandContext(failingCommand, new HashSet(Arrays.asList('o', 'w'))); + new CommandContext(failingCommand, new HashSet<>(Arrays.asList('o', 'w'))); } @Test diff --git a/worldedit-core/src/test/java/com/sk89q/worldedit/VectorTest.java b/worldedit-core/src/test/java/com/sk89q/worldedit/VectorTest.java deleted file mode 100644 index 51d50f93b..000000000 --- a/worldedit-core/src/test/java/com/sk89q/worldedit/VectorTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * WorldEdit, a Minecraft world manipulation toolkit - * Copyright (C) sk89q - * Copyright (C) WorldEdit team and contributors - * - * This program is free software: you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as published by the - * Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package com.sk89q.worldedit; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class VectorTest { - @Test - public void collinearityTest() { - assertCollinear(0,0,0, 0,0,0); - - assertCollinear(0,0,0, 1,0,0); - assertCollinear(0,0,0, 0,1,0); - assertCollinear(0,0,0, 0,0,1); - - assertCollinear(1,0,0, 0,0,0); - assertCollinear(0,1,0, 0,0,0); - assertCollinear(0,0,1, 0,0,0); - - assertCollinear(1,0,0, 2,0,0); - assertNotCollinear(1,0,0, 0,1,0); - - assertNotCollinear(2,2,2, 8,4,4); - assertCollinear(8,2,2, 8,2,2); - assertNotCollinear(4,2,4, 4,4,4); - assertNotCollinear(1,1,2, 4,8,2); - assertNotCollinear(4,1,8, 1,4,4); - assertCollinear(2,4,2, 1,2,1); - assertNotCollinear(2,2,4, 1,2,1); - assertNotCollinear(4,4,1, 4,4,4); - assertNotCollinear(4,1,4, 1,8,2); - assertCollinear(8,8,4, 4,4,2); - assertNotCollinear(2,1,8, 1,1,2); - assertNotCollinear(8,1,2, 2,1,2); - assertNotCollinear(4,4,8, 2,2,8); - assertNotCollinear(8,4,8, 1,4,8); - assertNotCollinear(2,2,2, 1,4,2); - assertNotCollinear(1,1,2, 8,8,2); - assertNotCollinear(4,4,8, 8,4,4); - assertNotCollinear(1,8,2, 4,4,4); - assertNotCollinear(8,4,2, 1,2,2); - assertNotCollinear(1,8,2, 8,1,4); - assertNotCollinear(4,8,1, 4,8,8); - assertNotCollinear(8,1,8, 8,8,8); - assertNotCollinear(8,4,1, 4,2,2); - assertNotCollinear(4,8,1, 4,2,1); - assertNotCollinear(8,8,1, 2,4,2); - assertCollinear(8,1,4, 8,1,4); - assertNotCollinear(4,1,1, 2,4,8); - assertNotCollinear(4,2,8, 1,4,1); - assertNotCollinear(1,8,2, 1,8,1); - assertNotCollinear(1,1,2, 4,2,2); - - assertCollinear(0,0, 0,0); - - assertCollinear(0,0, 1,0); - assertCollinear(0,0, 0,1); - assertCollinear(0,0, 0,0); - - assertCollinear(1,0, 0,0); - assertCollinear(0,1, 0,0); - assertCollinear(0,0, 0,0); - - assertCollinear(1,0, 2,0); - assertNotCollinear(1,0, 0,1); - - assertNotCollinear(2,2, 8,4); - assertCollinear(8,2, 8,2); - assertNotCollinear(4,2, 4,4); - assertNotCollinear(1,1, 4,8); - assertNotCollinear(4,1, 1,4); - assertCollinear(2,4, 1,2); - assertNotCollinear(2,2, 1,2); - assertCollinear(4,4, 4,4); - assertNotCollinear(4,1, 1,8); - assertCollinear(8,8, 4,4); - assertNotCollinear(2,1, 1,1); - assertNotCollinear(8,1, 2,1); - assertCollinear(4,4, 2,2); - assertNotCollinear(8,4, 1,4); - assertNotCollinear(2,2, 1,4); - assertCollinear(1,1, 8,8); - assertNotCollinear(4,4, 8,4); - assertNotCollinear(1,8, 4,4); - assertNotCollinear(8,4, 1,2); - assertNotCollinear(1,8, 8,1); - assertCollinear(4,8, 4,8); - assertNotCollinear(8,1, 8,8); - assertCollinear(8,4, 4,2); - assertNotCollinear(4,8, 4,2); - assertNotCollinear(8,8, 2,4); - assertCollinear(8,1, 8,1); - assertNotCollinear(4,1, 2,4); - assertNotCollinear(4,2, 1,4); - assertCollinear(1,8, 1,8); - assertNotCollinear(1,1, 4,2); - } - - private void assertCollinear(double ax, double ay, double az, double bx, double by, double bz) { - final Vector a = new Vector(ax,ay,az); - final Vector b = new Vector(bx,by,bz); - assertTrue(a.isCollinearWith(b)); - assertTrue(b.isCollinearWith(a)); - assertTrue(a.multiply(-1.0).isCollinearWith(b)); - assertTrue(a.isCollinearWith(b.multiply(-1.0))); - } - private void assertNotCollinear(double ax, double ay, double az, double bx, double by, double bz) { - final Vector a = new Vector(ax,ay,az); - final Vector b = new Vector(bx,by,bz); - assertFalse(a.isCollinearWith(b)); - assertFalse(b.isCollinearWith(a)); - assertFalse(a.multiply(-1.0).isCollinearWith(b)); - assertFalse(a.isCollinearWith(b.multiply(-1.0))); - } - - private void assertCollinear(double ax, double az, double bx, double bz) { - final Vector2D a = new Vector2D(ax,az); - final Vector2D b = new Vector2D(bx,bz); - assertTrue(a.isCollinearWith(b)); - assertTrue(b.isCollinearWith(a)); - assertTrue(a.multiply(-1.0).isCollinearWith(b)); - assertTrue(a.isCollinearWith(b.multiply(-1.0))); - } - private void assertNotCollinear(double ax, double az, double bx, double bz) { - final Vector2D a = new Vector2D(ax,az); - final Vector2D b = new Vector2D(bx,bz); - assertFalse(a.isCollinearWith(b)); - assertFalse(b.isCollinearWith(a)); - assertFalse(a.multiply(-1.0).isCollinearWith(b)); - assertFalse(a.isCollinearWith(b.multiply(-1.0))); - } -} diff --git a/worldedit-core/src/test/java/com/sk89q/worldedit/extent/transform/BlockTransformExtentTest.java b/worldedit-core/src/test/java/com/sk89q/worldedit/extent/transform/BlockTransformExtentTest.java new file mode 100644 index 000000000..e32b7c6cd --- /dev/null +++ b/worldedit-core/src/test/java/com/sk89q/worldedit/extent/transform/BlockTransformExtentTest.java @@ -0,0 +1,69 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.extent.transform; + +import static org.junit.Assert.assertEquals; + +import com.sk89q.worldedit.math.transform.AffineTransform; +import com.sk89q.worldedit.math.transform.Transform; +import com.sk89q.worldedit.world.block.BlockState; +import com.sk89q.worldedit.world.block.BlockType; +import com.sk89q.worldedit.world.block.BlockTypes; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.util.HashSet; +import java.util.Set; + +@Ignore("A platform is currently required to get properties, preventing this test.") +public class BlockTransformExtentTest { + + private static final Transform ROTATE_90 = new AffineTransform().rotateY(-90); + private static final Transform ROTATE_NEG_90 = new AffineTransform().rotateY(90); + private final Set ignored = new HashSet<>(); + + @Before + public void setUp() throws Exception { + BlockTypes.register(new BlockType("worldedit:test")); + } + + @Test + public void testTransform() throws Exception { + for (BlockType type : BlockType.REGISTRY.values()) { + if (ignored.contains(type)) { + continue; + } + + BlockState base = type.getDefaultState(); + BlockState rotated = base; + + for (int i = 1; i < 4; i++) { + rotated = BlockTransformExtent.transform(base, ROTATE_90); + } + assertEquals(base, rotated); + rotated = base; + for (int i = 1; i < 4; i++) { + rotated = BlockTransformExtent.transform(base, ROTATE_NEG_90); + } + assertEquals(base, rotated); + } + } +} \ No newline at end of file diff --git a/worldedit-core/src/test/java/com/sk89q/worldedit/util/LocationTest.java b/worldedit-core/src/test/java/com/sk89q/worldedit/util/LocationTest.java index b7944d476..0dfd618df 100644 --- a/worldedit-core/src/test/java/com/sk89q/worldedit/util/LocationTest.java +++ b/worldedit-core/src/test/java/com/sk89q/worldedit/util/LocationTest.java @@ -22,7 +22,7 @@ package com.sk89q.worldedit.util; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.world.World; import org.junit.Test; @@ -54,29 +54,29 @@ public class LocationTest { @Test public void testToVector() throws Exception { World world = mock(World.class); - Vector position = new Vector(1, 1, 1); + Vector3 position = Vector3.at(1, 1, 1); Location location = new Location(world, position); - assertEquals(position, location.toVector()); + assertEquals(position, location); } @Test public void testGetX() throws Exception { World world = mock(World.class); - Location location = new Location(world, new Vector(TEST_VALUE, 0, 0)); + Location location = new Location(world, Vector3.at(TEST_VALUE, 0, 0)); assertEquals(TEST_VALUE, location.getX(), EPSILON); } @Test public void testGetBlockX() throws Exception { World world = mock(World.class); - Location location = new Location(world, new Vector(TEST_VALUE, 0, 0)); + Location location = new Location(world, Vector3.at(TEST_VALUE, 0, 0)); assertEquals(TEST_VALUE, location.getBlockX()); } @Test public void testSetX() throws Exception { World world = mock(World.class); - Location location1 = new Location(world, new Vector()); + Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setX(TEST_VALUE); assertEquals(0, location1.getX(), EPSILON); assertEquals(TEST_VALUE, location2.getX(), EPSILON); @@ -87,21 +87,21 @@ public class LocationTest { @Test public void testGetY() throws Exception { World world = mock(World.class); - Location location = new Location(world, new Vector(0, TEST_VALUE, 0)); + Location location = new Location(world, Vector3.at(0, TEST_VALUE, 0)); assertEquals(TEST_VALUE, location.getY(), EPSILON); } @Test public void testGetBlockY() throws Exception { World world = mock(World.class); - Location location = new Location(world, new Vector(0, TEST_VALUE, 0)); + Location location = new Location(world, Vector3.at(0, TEST_VALUE, 0)); assertEquals(TEST_VALUE, location.getBlockY()); } @Test public void testSetY() throws Exception { World world = mock(World.class); - Location location1 = new Location(world, new Vector()); + Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setY(TEST_VALUE); assertEquals(0, location1.getY(), EPSILON); assertEquals(0, location2.getX(), EPSILON); @@ -112,21 +112,21 @@ public class LocationTest { @Test public void testGetZ() throws Exception { World world = mock(World.class); - Location location = new Location(world, new Vector(0, 0, TEST_VALUE)); + Location location = new Location(world, Vector3.at(0, 0, TEST_VALUE)); assertEquals(TEST_VALUE, location.getZ(), EPSILON); } @Test public void testGetBlockZ() throws Exception { World world = mock(World.class); - Location location = new Location(world, new Vector(0, 0, TEST_VALUE)); + Location location = new Location(world, Vector3.at(0, 0, TEST_VALUE)); assertEquals(TEST_VALUE, location.getBlockZ()); } @Test public void testSetZ() throws Exception { World world = mock(World.class); - Location location1 = new Location(world, new Vector()); + Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setZ(TEST_VALUE); assertEquals(0, location1.getZ(), EPSILON); assertEquals(0, location2.getX(), EPSILON); diff --git a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeAdapter.java b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeAdapter.java index 18311a5c5..e0f319cee 100644 --- a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeAdapter.java +++ b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeAdapter.java @@ -20,7 +20,8 @@ package com.sk89q.worldedit.forge; import com.google.common.collect.ImmutableList; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.registry.state.BooleanProperty; import com.sk89q.worldedit.registry.state.DirectionalProperty; import com.sk89q.worldedit.registry.state.EnumProperty; @@ -49,15 +50,15 @@ final class ForgeAdapter { return new ForgeWorld(world); } - public static Vector adapt(Vec3d vector) { - return new Vector(vector.x, vector.y, vector.z); + public static Vector3 adapt(Vec3d vector) { + return Vector3.at(vector.x, vector.y, vector.z); } - public static Vector adapt(BlockPos pos) { - return new Vector(pos.getX(), pos.getY(), pos.getZ()); + public static BlockVector3 adapt(BlockPos pos) { + return BlockVector3.at(pos.getX(), pos.getY(), pos.getZ()); } - public static Vec3d toVec3(Vector vector) { + public static Vec3d toVec3(BlockVector3 vector) { return new Vec3d(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ()); } @@ -87,7 +88,7 @@ final class ForgeAdapter { } } - public static BlockPos toBlockPos(Vector vector) { + public static BlockPos toBlockPos(BlockVector3 vector) { return new BlockPos(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ()); } diff --git a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeBlockRegistry.java b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeBlockRegistry.java index a2d59715a..ddf3762bb 100644 --- a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeBlockRegistry.java +++ b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeBlockRegistry.java @@ -27,16 +27,25 @@ import com.sk89q.worldedit.world.registry.BundledBlockRegistry; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; +import net.minecraft.util.ResourceLocation; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; +import javax.annotation.Nullable; + public class ForgeBlockRegistry extends BundledBlockRegistry { private Map materialMap = new HashMap<>(); + @Nullable + @Override + public String getName(BlockType blockType) { + return Block.REGISTRY.getObject(new ResourceLocation(blockType.getId())).getLocalizedName(); + } + @Override public BlockMaterial getMaterial(BlockType blockType) { return materialMap.computeIfAbsent(Block.getBlockFromName(blockType.getId()).getDefaultState().getMaterial(), diff --git a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeEntity.java b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeEntity.java index 54e28c244..e4b391fe0 100644 --- a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeEntity.java +++ b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeEntity.java @@ -21,11 +21,11 @@ package com.sk89q.worldedit.forge; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.metadata.EntityProperties; import com.sk89q.worldedit.extent.Extent; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.NullWorld; import com.sk89q.worldedit.world.entity.EntityTypes; @@ -66,7 +66,7 @@ class ForgeEntity implements Entity { public Location getLocation() { net.minecraft.entity.Entity entity = entityRef.get(); if (entity != null) { - Vector position = new Vector(entity.posX, entity.posY, entity.posZ); + Vector3 position = Vector3.at(entity.posX, entity.posY, entity.posZ); float yaw = entity.rotationYaw; float pitch = entity.rotationPitch; @@ -76,6 +76,12 @@ class ForgeEntity implements Entity { } } + @Override + public boolean setLocation(Location location) { + // TODO + return false; + } + @Override public Extent getExtent() { net.minecraft.entity.Entity entity = entityRef.get(); diff --git a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeItemRegistry.java b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeItemRegistry.java index c87033075..b1ba36198 100644 --- a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeItemRegistry.java +++ b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeItemRegistry.java @@ -19,6 +19,7 @@ package com.sk89q.worldedit.forge; +<<<<<<< HEAD import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.world.item.ItemTypes; import com.sk89q.worldedit.world.registry.ItemRegistry; @@ -37,5 +38,18 @@ public class ForgeItemRegistry implements ItemRegistry { } else { return null; } +======= +import com.sk89q.worldedit.world.item.ItemType; +import com.sk89q.worldedit.world.registry.BundledItemRegistry; + +import javax.annotation.Nullable; + +public class ForgeItemRegistry extends BundledItemRegistry { + + @Nullable + @Override + public String getName(ItemType itemType) { + return super.getName(itemType); // TODO +>>>>>>> b75d5149... Fixed the bundle being directly used outside of the registry system. } } diff --git a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgePlayer.java b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgePlayer.java index d4b906fc4..fadddd904 100644 --- a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgePlayer.java +++ b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgePlayer.java @@ -20,17 +20,18 @@ package com.sk89q.worldedit.forge; import com.sk89q.util.StringUtil; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.extension.platform.AbstractPlayerActor; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.internal.cui.CUIEvent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.session.SessionKey; import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.item.ItemTypes; -import io.netty.buffer.Unpooled; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -45,6 +46,8 @@ import java.util.UUID; import javax.annotation.Nullable; +import io.netty.buffer.Unpooled; + public class ForgePlayer extends AbstractPlayerActor { private final EntityPlayerMP player; @@ -77,7 +80,7 @@ public class ForgePlayer extends AbstractPlayerActor { @Override public Location getLocation() { - Vector position = new Vector(this.player.posX, this.player.posY, this.player.posZ); + Vector3 position = Vector3.at(this.player.posX, this.player.posY, this.player.posZ); return new Location( ForgeWorldEdit.inst.getWorld(this.player.world), position, @@ -85,6 +88,12 @@ public class ForgePlayer extends AbstractPlayerActor { this.player.rotationPitch); } + @Override + public boolean setLocation(Location location) { + // TODO + return false; + } + @Override public com.sk89q.worldedit.world.World getWorld() { return ForgeWorldEdit.inst.getWorld(this.player.world); @@ -139,7 +148,7 @@ public class ForgePlayer extends AbstractPlayerActor { } @Override - public void setPosition(Vector pos, float pitch, float yaw) { + public void setPosition(Vector3 pos, float pitch, float yaw) { this.player.connection.setPlayerLocation(pos.getX(), pos.getY(), pos.getZ(), yaw, pitch); } @@ -165,6 +174,31 @@ public class ForgePlayer extends AbstractPlayerActor { } @Override +<<<<<<< HEAD +<<<<<<< HEAD +======= + public void sendFakeBlock(BlockVector3 pos, BlockStateHolder block) { +======= + public > void sendFakeBlock(BlockVector3 pos, B block) { +>>>>>>> 3fefcbf9... Remove all raw usages of BSH, improve API generics + BlockPos loc = ForgeAdapter.toBlockPos(pos); + if (block == null) { + // TODO +// player.sendBlockChange(loc, player.getWorld().getBlockAt(loc).getBlockData()); + } else { + // TODO +// player.sendBlockChange(loc, BukkitAdapter.adapt(block)); + if (block instanceof BaseBlock && ((BaseBlock) block).hasNbtData()) { + player.connection.sendPacket(new SPacketUpdateTileEntity( + new BlockPos(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()), 7, + NBTConverter.toNative(((BaseBlock) block).getNbtData())) + ); + } + } + } + + @Override +>>>>>>> 399e0ad5... Refactor vector system to be cleaner public SessionKey getSessionKey() { return new SessionKeyImpl(player.getUniqueID(), player.getName()); } diff --git a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeWorld.java b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeWorld.java index abd4e8151..a2c960f26 100644 --- a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeWorld.java +++ b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/ForgeWorld.java @@ -27,8 +27,9 @@ import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.BlockVector2D; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.blocks.BaseItemStack; @@ -170,7 +171,7 @@ public class ForgeWorld extends AbstractWorld { } @Override - public boolean setBlock(Vector position, BlockStateHolder block, boolean notifyAndLight) throws WorldEditException { + public > boolean setBlock(BlockVector3 position, B block, boolean notifyAndLight) throws WorldEditException { checkNotNull(position); checkNotNull(block); @@ -185,7 +186,6 @@ public class ForgeWorld extends AbstractWorld { IBlockState old = chunk.getBlockState(pos); Block mcBlock = Block.getBlockFromName(block.getBlockType().getId()); IBlockState newState = mcBlock.getDefaultState(); - @SuppressWarnings("unchecked") Map, Object> states = block.getStates(); newState = applyProperties(mcBlock.getBlockState(), newState, states); IBlockState successState = chunk.setBlockState(pos, newState); @@ -213,6 +213,12 @@ public class ForgeWorld extends AbstractWorld { return successful; } + @Override + public boolean notifyAndLightBlock(BlockVector3 position, BlockState previousType) throws WorldEditException { + // TODO Implement + return false; + } + // Can't get the "Object" to be right for withProperty w/o this @SuppressWarnings({ "rawtypes", "unchecked" }) private IBlockState applyProperties(BlockStateContainer stateContainer, IBlockState newState, Map, Object> states) { @@ -237,13 +243,13 @@ public class ForgeWorld extends AbstractWorld { } @Override - public int getBlockLightLevel(Vector position) { + public int getBlockLightLevel(BlockVector3 position) { checkNotNull(position); return getWorld().getLight(new BlockPos(position.getBlockX(), position.getBlockY(), position.getBlockZ())); } @Override - public boolean clearContainerBlockContents(Vector position) { + public boolean clearContainerBlockContents(BlockVector3 position) { checkNotNull(position); TileEntity tile = getWorld().getTileEntity(new BlockPos(position.getBlockX(), position.getBlockY(), position.getBlockZ())); if ((tile instanceof IInventory)) { @@ -258,13 +264,13 @@ public class ForgeWorld extends AbstractWorld { } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { checkNotNull(position); return new BaseBiome(Biome.getIdForBiome(getWorld().getBiomeForCoordsBody(new BlockPos(position.getBlockX(), 0, position.getBlockZ())))); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { checkNotNull(position); checkNotNull(biome); @@ -278,7 +284,7 @@ public class ForgeWorld extends AbstractWorld { } @Override - public boolean useItem(Vector position, BaseItem item, Direction face) { + public boolean useItem(BlockVector3 position, BaseItem item, Direction face) { Item nativeItem = Item.getByNameOrId(item.getType().getId()); ItemStack stack = null; if (item.getNbtData() == null) { @@ -293,7 +299,7 @@ public class ForgeWorld extends AbstractWorld { } @Override - public void dropItem(Vector position, BaseItemStack item) { + public void dropItem(Vector3 position, BaseItemStack item) { checkNotNull(position); checkNotNull(item); @@ -307,7 +313,7 @@ public class ForgeWorld extends AbstractWorld { } @Override - public void simulateBlockMine(Vector position) { + public void simulateBlockMine(BlockVector3 position) { BlockPos pos = ForgeAdapter.toBlockPos(position); IBlockState state = getWorld().getBlockState(pos); state.getBlock().dropBlockAsItem(getWorld(), pos, state, 0); @@ -338,13 +344,13 @@ public class ForgeWorld extends AbstractWorld { // Pre-gen all the chunks // We need to also pull one more chunk in every direction CuboidRegion expandedPreGen = new CuboidRegion(region.getMinimumPoint().subtract(16, 0, 16), region.getMaximumPoint().add(16, 0, 16)); - for (Vector2D chunk : expandedPreGen.getChunks()) { + for (BlockVector2 chunk : expandedPreGen.getChunks()) { freshWorld.getChunkFromChunkCoords(chunk.getBlockX(), chunk.getBlockZ()); } ForgeWorld from = new ForgeWorld(freshWorld); try { - for (BlockVector vec : region) { + for (BlockVector3 vec : region) { editSession.setBlock(vec, from.getFullBlock(vec)); } } catch (MaxChangedBlocksException e) { @@ -386,32 +392,32 @@ public class ForgeWorld extends AbstractWorld { } @Override - public boolean generateTree(TreeType type, EditSession editSession, Vector position) throws MaxChangedBlocksException { + public boolean generateTree(TreeType type, EditSession editSession, BlockVector3 position) throws MaxChangedBlocksException { WorldGenerator generator = createWorldGenerator(type); return generator != null && generator.generate(getWorld(), random, ForgeAdapter.toBlockPos(position)); } @Override - public void checkLoadedChunk(Vector pt) { + public void checkLoadedChunk(BlockVector3 pt) { getWorld().getChunkFromBlockCoords(ForgeAdapter.toBlockPos(pt)); } @Override - public void fixAfterFastMode(Iterable chunks) { + public void fixAfterFastMode(Iterable chunks) { fixLighting(chunks); } @Override - public void fixLighting(Iterable chunks) { + public void fixLighting(Iterable chunks) { World world = getWorld(); - for (BlockVector2D chunk : chunks) { + for (BlockVector2 chunk : chunks) { world.getChunkFromChunkCoords(chunk.getBlockX(), chunk.getBlockZ()).resetRelightChecks(); } } @Override - public boolean playEffect(Vector position, int type, int data) { - getWorld().playEvent(type, ForgeAdapter.toBlockPos(position), data); + public boolean playEffect(Vector3 position, int type, int data) { + getWorld().playEvent(type, ForgeAdapter.toBlockPos(position.toBlockPoint()), data); return true; } @@ -463,7 +469,12 @@ public class ForgeWorld extends AbstractWorld { } @Override - public BlockState getBlock(Vector position) { + public BlockVector3 getSpawnPosition() { + return ForgeAdapter.adapt(getWorld().getSpawnPoint()); + } + + @Override + public BlockState getBlock(BlockVector3 position) { World world = getWorld(); BlockPos pos = new BlockPos(position.getBlockX(), position.getBlockY(), position.getBlockZ()); IBlockState mcState = world.getBlockState(pos); @@ -487,7 +498,7 @@ public class ForgeWorld extends AbstractWorld { } @Override - public BaseBlock getFullBlock(Vector position) { + public BaseBlock getFullBlock(BlockVector3 position) { BlockPos pos = new BlockPos(position.getBlockX(), position.getBlockY(), position.getBlockZ()); TileEntity tile = getWorld().getTileEntity(pos); @@ -523,7 +534,7 @@ public class ForgeWorld extends AbstractWorld { public List getEntities(Region region) { List entities = new ArrayList<>(); for (net.minecraft.entity.Entity entity : getWorld().loadedEntityList) { - if (region.contains(new Vector(entity.posX, entity.posY, entity.posZ))) { + if (region.contains(BlockVector3.at(entity.posX, entity.posY, entity.posZ))) { entities.add(new ForgeEntity(entity)); } } diff --git a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/NBTConverter.java b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/NBTConverter.java index 7773845ed..0992d3d4f 100644 --- a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/NBTConverter.java +++ b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/NBTConverter.java @@ -217,7 +217,7 @@ final class NBTConverter { } public static EndTag fromNative(NBTTagEnd other) { - return EndTag.INSTANCE; + return new EndTag(); } public static LongTag fromNative(NBTTagLong other) { diff --git a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/TileEntityUtils.java b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/TileEntityUtils.java index f87293db8..4147d835c 100644 --- a/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/TileEntityUtils.java +++ b/worldedit-forge/src/main/java/com/sk89q/worldedit/forge/TileEntityUtils.java @@ -21,7 +21,8 @@ package com.sk89q.worldedit.forge; import static com.google.common.base.Preconditions.checkNotNull; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; + import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagInt; import net.minecraft.tileentity.TileEntity; @@ -47,7 +48,7 @@ final class TileEntityUtils { * @param position the position * @return a tag compound */ - private static NBTTagCompound updateForSet(NBTTagCompound tag, Vector position) { + private static NBTTagCompound updateForSet(NBTTagCompound tag, BlockVector3 position) { checkNotNull(tag); checkNotNull(position); @@ -66,7 +67,7 @@ final class TileEntityUtils { * @param clazz the tile entity class * @param tag the tag for the tile entity (may be null to not set NBT data) */ - static void setTileEntity(World world, Vector position, Class clazz, @Nullable NBTTagCompound tag) { + static void setTileEntity(World world, BlockVector3 position, Class clazz, @Nullable NBTTagCompound tag) { checkNotNull(world); checkNotNull(position); checkNotNull(clazz); @@ -94,7 +95,7 @@ final class TileEntityUtils { * @param position the position * @param tag the tag for the tile entity (may be null to do nothing) */ - static void setTileEntity(World world, Vector position, @Nullable NBTTagCompound tag) { + static void setTileEntity(World world, BlockVector3 position, @Nullable NBTTagCompound tag) { if (tag != null) { updateForSet(tag, position); TileEntity tileEntity = TileEntity.create(world, tag); @@ -113,7 +114,7 @@ final class TileEntityUtils { * @return a tile entity (may be null if it failed) */ @Nullable - static TileEntity constructTileEntity(World world, Vector position, Class clazz) { + static TileEntity constructTileEntity(World world, BlockVector3 position, Class clazz) { Constructor baseConstructor; try { baseConstructor = clazz.getConstructor(); // creates "blank" TE diff --git a/worldedit-sponge/build.gradle b/worldedit-sponge/build.gradle index d068d4804..1e011ee8c 100644 --- a/worldedit-sponge/build.gradle +++ b/worldedit-sponge/build.gradle @@ -8,29 +8,55 @@ buildscript { } plugins { - id 'signing' - id 'org.spongepowered.plugin' version '0.8.1' + id 'org.spongepowered.plugin' version '0.9.0' +} + +repositories { + maven { url "https://repo.codemc.org/repository/maven-public" } } dependencies { compile project(':worldedit-core') - compile 'org.spongepowered:spongeapi:7.0.0-SNAPSHOT' + compile 'org.spongepowered:spongeapi:7.1.0' + compile 'org.bstats:bstats-sponge:1.4' testCompile group: 'org.mockito', name: 'mockito-core', version:'1.9.0-rc1' } sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 -sponge { - plugin { - id = 'worldedit' +jar.archiveName="fawe-sponge-${project.parent.version}.jar" +jar.destinationDir = file '../mvn/com/boydti/fawe-sponge/' + project.parent.version +task createPom << { + pom { + project { + groupId 'com.boydti' + artifactId 'fawe-sponge' + version project.parent.version + } } + .getEffectivePom() + .setDependencies(new ArrayList<>()) + .writeTo("../mvn/com/boydti/fawe-sponge/${project.parent.version}/fawe-sponge-${project.parent.version}.pom") + pom { + project { + groupId 'com.boydti' + artifactId 'fawe-sponge' + version 'latest' + } + } + .getEffectivePom() + .setDependencies(new ArrayList<>()) + .writeTo("../mvn/com/boydti/fawe-sponge/latest/fawe-sponge-latest.pom") } - -jar { - manifest { - attributes("Class-Path": "truezip.jar WorldEdit/truezip.jar js.jar WorldEdit/js.jar", - "WorldEdit-Version": version) +task copyFiles { + doLast { + copy { + from "../mvn/com/boydti/fawe-sponge/${project.parent.version}/" + into '../mvn/com/boydti/fawe-sponge/latest/' + include('*.jar') + rename ("fawe-sponge-${project.parent.version}.jar", 'fawe-sponge-latest.jar') + } } } @@ -38,13 +64,10 @@ shadowJar { dependencies { include(dependency(':worldedit-core')) } + archiveName = "${parent.name}-${project.name.replaceAll("worldedit-", "")}-${parent.version}.jar" + destinationDir = file '../target' } -artifacts { - archives shadowJar -} - -signing { - required false - sign shadowJar -} \ No newline at end of file +build.dependsOn(shadowJar) +build.finalizedBy(copyFiles) +copyFiles.dependsOn(createPom) diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeAdapter.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeAdapter.java new file mode 100644 index 000000000..f5df77298 --- /dev/null +++ b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeAdapter.java @@ -0,0 +1,168 @@ +/* + * WorldEdit, a Minecraft world manipulation toolkit + * Copyright (C) sk89q + * Copyright (C) WorldEdit team and contributors + * + * This program is free software: you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.sk89q.worldedit.sponge; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.flowpowered.math.vector.Vector3d; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; +import com.sk89q.worldedit.util.Location; +import com.sk89q.worldedit.world.World; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.entity.living.player.Player; + +/** + * Adapts between Sponge and WorldEdit equivalent objects. + */ +public class SpongeAdapter { + + private SpongeAdapter() { + } + + /** + * Create a WorldEdit world from a Sponge extent. + * + * @param world the Sponge extent + * @return a WorldEdit world + */ + public static World checkWorld(org.spongepowered.api.world.extent.Extent world) { + checkNotNull(world); + if (world instanceof org.spongepowered.api.world.World) { + return adapt((org.spongepowered.api.world.World) world); + } else { + throw new IllegalArgumentException("Extent type is not a world"); + } + } + + /** + * Create a WorldEdit world from a Sponge world. + * + * @param world the Sponge world + * @return a WorldEdit world + */ + public static World adapt(org.spongepowered.api.world.World world) { + checkNotNull(world); + return SpongeWorldEdit.inst().getWorld(world); + } + + /** + * Create a WorldEdit Player from a Sponge Player. + * + * @param player The Sponge player + * @return The WorldEdit player + */ + public static SpongePlayer adapt(Player player) { + return SpongeWorldEdit.inst().wrapPlayer(player); + } + + /** + * Create a Bukkit Player from a WorldEdit Player. + * + * @param player The WorldEdit player + * @return The Bukkit player + */ + public static Player adapt(com.sk89q.worldedit.entity.Player player) { + return ((SpongePlayer) player).getPlayer(); + } + + /** + * Create a Sponge world from a WorldEdit world. + * + * @param world the WorldEdit world + * @return a Sponge world + */ + public static org.spongepowered.api.world.World adapt(World world) { + checkNotNull(world); + if (world instanceof SpongeWorld) { + return ((SpongeWorld) world).getWorld(); + } else { + org.spongepowered.api.world.World match = Sponge.getServer().getWorld(world.getName()).orElse(null); + if (match != null) { + return match; + } else { + throw new IllegalArgumentException("Can't find a Sponge world for " + world); + } + } + } + + /** + * Create a WorldEdit location from a Sponge location. + * + * @param location the Sponge location + * @return a WorldEdit location + */ + public static Location adapt(org.spongepowered.api.world.Location location, Vector3d rotation) { + checkNotNull(location); + Vector3 position = asVector(location); + return new Location( + adapt(location.getExtent()), + position, + (float) rotation.getX(), + (float) rotation.getY()); + } + + /** + * Create a Sponge location from a WorldEdit location. + * + * @param location the WorldEdit location + * @return a Sponge location + */ + public static org.spongepowered.api.world.Location adapt(Location location) { + checkNotNull(location); + Vector3 position = location.toVector(); + return new org.spongepowered.api.world.Location<>( + adapt((World) location.getExtent()), + position.getX(), position.getY(), position.getZ()); + } + + /** + * Create a Sponge rotation from a WorldEdit location. + * + * @param location the WorldEdit location + * @return a Sponge rotation + */ + public static Vector3d adaptRotation(Location location) { + checkNotNull(location); + return new Vector3d(location.getPitch(), location.getYaw(), 0); + } + + /** + * Create a WorldEdit Vector from a Bukkit location. + * + * @param location The Bukkit location + * @return a WorldEdit vector + */ + public static Vector3 asVector(org.spongepowered.api.world.Location location) { + checkNotNull(location); + return Vector3.at(location.getX(), location.getY(), location.getZ()); + } + + /** + * Create a WorldEdit BlockVector from a Bukkit location. + * + * @param location The Bukkit location + * @return a WorldEdit vector + */ + public static BlockVector3 asBlockVector(org.spongepowered.api.world.Location location) { + checkNotNull(location); + return BlockVector3.at(location.getX(), location.getY(), location.getZ()); + } +} diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeEntity.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeEntity.java index 9aa728310..db070d9f1 100644 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeEntity.java +++ b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeEntity.java @@ -66,6 +66,16 @@ class SpongeEntity implements Entity { } } + @Override + public boolean setLocation(Location location) { + org.spongepowered.api.entity.Entity entity = entityRef.get(); + if (entity != null) { + return entity.setLocation(SpongeAdapter.adapt(location)); + } else { + return false; + } + } + @Override public Extent getExtent() { org.spongepowered.api.entity.Entity entity = entityRef.get(); diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePlayer.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePlayer.java index 37774dbc8..3793ffb87 100644 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePlayer.java +++ b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongePlayer.java @@ -21,18 +21,21 @@ package com.sk89q.worldedit.sponge; import com.flowpowered.math.vector.Vector3d; import com.sk89q.util.StringUtil; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.extension.platform.AbstractPlayerActor; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.internal.cui.CUIEvent; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.session.SessionKey; import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.util.Location; +import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.gamemode.GameModes; import com.sk89q.worldedit.world.item.ItemTypes; + import org.spongepowered.api.Sponge; import org.spongepowered.api.data.type.HandTypes; import org.spongepowered.api.entity.living.player.Player; @@ -76,6 +79,11 @@ public class SpongePlayer extends AbstractPlayerActor { return this.player.getName(); } + @Override + public String getDisplayName() { + return player.getDisplayNameData().displayName().getDirect().map(TextSerializers.LEGACY_FORMATTING_CODE::serialize).orElse(getName()); + } + @Override public BaseEntity getState() { throw new UnsupportedOperationException("Cannot create a state from this object"); @@ -89,6 +97,11 @@ public class SpongePlayer extends AbstractPlayerActor { return SpongeWorldEdit.inst().getAdapter().adapt(entityLoc, entityRot); } + @Override + public boolean setLocation(Location location) { + return player.setLocation(SpongeAdapter.adapt(location)); + } + @Override public com.sk89q.worldedit.world.World getWorld() { return SpongeWorldEdit.inst().getAdapter().getWorld(player.getWorld()); @@ -143,7 +156,7 @@ public class SpongePlayer extends AbstractPlayerActor { } @Override - public void setPosition(Vector pos, float pitch, float yaw) { + public void setPosition(Vector3 pos, float pitch, float yaw) { org.spongepowered.api.world.Location loc = new org.spongepowered.api.world.Location<>( this.player.getWorld(), pos.getX(), pos.getY(), pos.getZ() ); @@ -183,6 +196,23 @@ public class SpongePlayer extends AbstractPlayerActor { gameMode.getId()).get()); } + @Override + public > void sendFakeBlock(BlockVector3 pos, B block) { + org.spongepowered.api.world.Location loc = player.getWorld().getLocation(pos.getX(), pos.getY(), pos.getZ()); + if (block == null) { + player.sendBlockChange(loc.getBlockPosition(), loc.getBlock()); + } else { + // TODO +// player.sendBlockChange(loc, BukkitAdapter.adapt(block)); +// if (block instanceof BaseBlock && ((BaseBlock) block).hasNbtData()) { +// BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); +// if (adapter != null) { +// adapter.sendFakeNBT(player, pos, ((BaseBlock) block).getNbtData()); +// } +// } + } + } + @Override public SessionKey getSessionKey() { return new SessionKeyImpl(player.getUniqueId(), player.getName()); @@ -224,4 +254,7 @@ public class SpongePlayer extends AbstractPlayerActor { } + public Player getPlayer() { + return player; + } } diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorld.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorld.java index fe3db9e16..fa088ee86 100644 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorld.java +++ b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorld.java @@ -24,18 +24,20 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.flowpowered.math.vector.Vector3d; import com.flowpowered.math.vector.Vector3i; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.Entity; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.world.AbstractWorld; import com.sk89q.worldedit.world.biome.BaseBiome; +import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.item.ItemTypes; import com.sk89q.worldedit.world.weather.WeatherType; @@ -134,7 +136,7 @@ public abstract class SpongeWorld extends AbstractWorld { private static final BlockSnapshot.Builder builder = BlockSnapshot.builder(); @Override - public boolean setBlock(Vector position, BlockStateHolder block, boolean notifyAndLight) throws WorldEditException { + public > boolean setBlock(BlockVector3 position, B block, boolean notifyAndLight) throws WorldEditException { checkNotNull(position); checkNotNull(block); @@ -161,13 +163,19 @@ public abstract class SpongeWorld extends AbstractWorld { return true; } + @Override + public boolean notifyAndLightBlock(BlockVector3 position, com.sk89q.worldedit.world.block.BlockState previousType) throws WorldEditException { + // TODO Move this to adapter + return false; + } + @Override public boolean regenerate(Region region, EditSession editSession) { return false; } @Override - public int getBlockLightLevel(Vector position) { + public int getBlockLightLevel(BlockVector3 position) { checkNotNull(position); BlockState state = getWorld().getBlock(new Vector3i(position.getX(), position.getY(), position.getZ())); @@ -185,13 +193,13 @@ public abstract class SpongeWorld extends AbstractWorld { } @Override - public BaseBiome getBiome(Vector2D position) { + public BaseBiome getBiome(BlockVector2 position) { checkNotNull(position); return new BaseBiome(SpongeWorldEdit.inst().getAdapter().resolve(getWorld().getBiome(position.getBlockX(), 0, position.getBlockZ()))); } @Override - public boolean setBiome(Vector2D position, BaseBiome biome) { + public boolean setBiome(BlockVector2 position, BaseBiome biome) { checkNotNull(position); checkNotNull(biome); @@ -200,7 +208,7 @@ public abstract class SpongeWorld extends AbstractWorld { } @Override - public void dropItem(Vector position, BaseItemStack item) { + public void dropItem(Vector3 position, BaseItemStack item) { checkNotNull(position); checkNotNull(item); @@ -218,7 +226,7 @@ public abstract class SpongeWorld extends AbstractWorld { } @Override - public void simulateBlockMine(Vector position) { + public void simulateBlockMine(BlockVector3 position) { // TODO } @@ -247,7 +255,7 @@ public abstract class SpongeWorld extends AbstractWorld { List entities = new ArrayList<>(); for (org.spongepowered.api.entity.Entity entity : getWorld().getEntities()) { org.spongepowered.api.world.Location loc = entity.getLocation(); - if (region.contains(new Vector(loc.getX(), loc.getY(), loc.getZ()))) { + if (region.contains(BlockVector3.at(loc.getX(), loc.getY(), loc.getZ()))) { entities.add(new SpongeEntity(entity)); } } @@ -279,7 +287,7 @@ public abstract class SpongeWorld extends AbstractWorld { } // Overwrite any data set by the NBT application - Vector dir = location.getDirection(); + Vector3 dir = location.getDirection(); newEnt.setLocationAndRotation( new org.spongepowered.api.world.Location<>(getWorld(), pos), @@ -313,6 +321,11 @@ public abstract class SpongeWorld extends AbstractWorld { getWorld().setWeather(Sponge.getRegistry().getType(Weather.class, weatherType.getId()).get(), duration); } + @Override + public BlockVector3 getSpawnPosition() { + return SpongeAdapter.asBlockVector(getWorld().getSpawnLocation()); + } + /** * Thrown when the reference to the world is lost. */ diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorldEdit.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorldEdit.java index 6c494c56f..0e1e79b32 100644 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorldEdit.java +++ b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/SpongeWorldEdit.java @@ -34,6 +34,7 @@ import com.sk89q.worldedit.sponge.adapter.SpongeImplAdapter; import com.sk89q.worldedit.sponge.adapter.SpongeImplLoader; import com.sk89q.worldedit.sponge.config.SpongeConfiguration; import com.sk89q.worldedit.world.item.ItemTypes; +import org.bstats.sponge.Metrics2; import org.slf4j.Logger; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockSnapshot; @@ -75,6 +76,9 @@ public class SpongeWorldEdit { @Inject private Logger logger; + @Inject + private Metrics2 metrics; + public static final String MOD_ID = "worldedit"; private SpongePermissionsProvider provider; @@ -135,11 +139,17 @@ public class SpongeWorldEdit { for (BlockType blockType : Sponge.getRegistry().getAllOf(BlockType.class)) { // TODO Handle blockstate stuff - com.sk89q.worldedit.world.block.BlockTypes.register(new com.sk89q.worldedit.world.block.BlockType(blockType.getId())); + String id = blockType.getId(); + if (!com.sk89q.worldedit.world.block.BlockType.REGISTRY.keySet().contains(id)) { + com.sk89q.worldedit.world.block.BlockTypes.register(new com.sk89q.worldedit.world.block.BlockType(id)); + } } for (ItemType itemType : Sponge.getRegistry().getAllOf(ItemType.class)) { - ItemTypes.register(new com.sk89q.worldedit.world.item.ItemType(itemType.getId())); + String id = itemType.getId(); + if (!com.sk89q.worldedit.world.item.ItemType.REGISTRY.keySet().contains(id)) { + ItemTypes.register(new com.sk89q.worldedit.world.item.ItemType(id)); + } } WorldEdit.getInstance().getPlatformManager().register(platform); @@ -211,7 +221,7 @@ public class SpongeWorldEdit { BlockType interactedType = targetBlock.getState().getType(); if (event instanceof InteractBlockEvent.Primary) { - if (!interactedType.getMaterial().isAir()) { + if (interactedType != BlockTypes.AIR) { if (!optLoc.isPresent()) { return; } @@ -233,7 +243,7 @@ public class SpongeWorldEdit { } } } else if (event instanceof InteractBlockEvent.Secondary) { - if (!interactedType.getMaterial().isAir()) { + if (interactedType != BlockTypes.AIR) { if (!optLoc.isPresent()) { return; } diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplAdapter.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplAdapter.java index a134e1ac3..d6cb96f8e 100644 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplAdapter.java +++ b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplAdapter.java @@ -20,11 +20,12 @@ package com.sk89q.worldedit.sponge.adapter; import com.flowpowered.math.vector.Vector3d; -import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.entity.BaseEntity; +import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.sponge.SpongeWorld; import com.sk89q.worldedit.util.Location; + import org.spongepowered.api.entity.Entity; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.world.World; @@ -56,7 +57,7 @@ public interface SpongeImplAdapter { } default Location adapt(org.spongepowered.api.world.Location loc, Vector3d rot) { - Vector position = new Vector(loc.getX(), loc.getY(), loc.getZ()); + Vector3 position = Vector3.at(loc.getX(), loc.getY(), loc.getZ()); return new Location(getWorld(loc.getExtent()), position, (float) rot.getY(), (float) rot.getX()); } diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplLoader.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplLoader.java index 17c9800ce..dac72425e 100644 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplLoader.java +++ b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/adapter/SpongeImplLoader.java @@ -85,7 +85,7 @@ public class SpongeImplLoader { Closer closer = Closer.create(); JarFile jar = closer.register(new JarFile(file)); try { - Enumeration entries = jar.entries(); + Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = (JarEntry) entries.nextElement(); diff --git a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/config/ConfigurateConfiguration.java b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/config/ConfigurateConfiguration.java index e38140bb4..6e1786132 100644 --- a/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/config/ConfigurateConfiguration.java +++ b/worldedit-sponge/src/main/java/com/sk89q/worldedit/sponge/config/ConfigurateConfiguration.java @@ -23,6 +23,7 @@ import com.google.common.reflect.TypeToken; import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.session.SessionManager; +import com.sk89q.worldedit.util.report.Unreported; import com.sk89q.worldedit.world.registry.LegacyMapper; import com.sk89q.worldedit.world.snapshot.SnapshotRepository; import ninja.leaping.configurate.ConfigurationOptions; @@ -36,10 +37,10 @@ import java.util.HashSet; public class ConfigurateConfiguration extends LocalConfiguration { - protected final ConfigurationLoader config; - protected final Logger logger; + @Unreported protected final ConfigurationLoader config; + @Unreported protected final Logger logger; - protected CommentedConfigurationNode node; + @Unreported protected CommentedConfigurationNode node; public ConfigurateConfiguration(ConfigurationLoader config, Logger logger) { this.config = config;