From 75653087b92ff4adc87db5b39644c08ef22470c6 Mon Sep 17 00:00:00 2001 From: MattBDev <4009945+MattBDev@users.noreply.github.com> Date: Wed, 5 Feb 2020 00:37:42 -0500 Subject: [PATCH] Remove FAWE-Piston Disables a lot of previous functionality in FAWE until replacements can be made. This commit was untested and may cause major issues. --- buildSrc/build.gradle.kts | 17 - buildSrc/src/main/kotlin/CommonConfig.kt | 1 - buildSrc/src/main/kotlin/Versions.kt | 2 +- .../bukkit/listener/BukkitImageListener.java | 295 +- .../bukkit/listener/CFIPacketListener.java | 9 +- .../src/main/java/com/boydti/fawe/Fawe.java | 16 +- .../com/boydti/fawe/command/CFICommand.java | 177 +- .../com/boydti/fawe/command/CFICommands.java | 2609 +++++++++-------- .../boydti/fawe/command/CommandProcessor.java | 93 - .../com/boydti/fawe/command/FaweParser.java | 227 +- .../com/boydti/fawe/command/PlotLoader.java | 165 +- .../fawe/object/brush/BrushSettings.java | 119 +- .../java/com/boydti/fawe/util/BrushCache.java | 35 +- .../worldedit/command/BrushCommands.java | 74 +- .../sk89q/worldedit/command/MaskCommands.java | 895 +++--- .../worldedit/command/PatternCommands.java | 805 ++--- .../worldedit/command/ToolUtilCommands.java | 69 +- .../worldedit/command/TransformCommands.java | 209 +- .../command/argument/RegistryConverter.java | 1 - .../worldedit/command/tool/BrushTool.java | 65 +- .../command/util/AsyncCommandBuilder.java | 2 +- .../CommandPermissionsConditionGenerator.java | 1 - .../command/util/DelegateCommandManager.java | 83 - .../worldedit/command/util/EntityRemover.java | 2 +- .../worldedit/command/util/HookMode.java | 2 +- ... ticking by default, __watchdog to turn on | 24 - .../command/util/PermissionCondition.java | 1 - .../command/util/PrintCommandHelp.java | 5 +- .../command/util/SuggestionHelper.java | 6 +- .../factory/DefaultTransformParser.java | 271 +- .../extension/factory/MaskFactory.java | 17 +- .../extension/factory/PatternFactory.java | 9 +- .../factory/parser/DefaultBlockParser.java | 93 +- .../parser/mask/BlockStateMaskParser.java | 2 - .../parser/mask/DefaultMaskParser.java | 407 +-- .../parser/pattern/DefaultPatternParser.java | 363 +-- .../platform/PlatformCommandManager.java | 127 +- .../platform/binding/PrimitiveBindings.java | 57 +- .../platform/binding/ProvideBindings.java | 1 - .../command/CommandLoggingHandler.java | 3 +- .../command/CommandRegistrationHandler.java | 1 - .../internal/command/CommandUtil.java | 126 +- .../internal/command/ConfirmHandler.java | 8 +- .../WorldEditExceptionConverter.java | 5 +- worldedit-libs/core/ap/build.gradle.kts | 3 - worldedit-libs/core/build.gradle.kts | 8 +- 46 files changed, 3643 insertions(+), 3867 deletions(-) delete mode 100644 worldedit-core/src/main/java/com/boydti/fawe/command/CommandProcessor.java delete mode 100644 worldedit-core/src/main/java/com/sk89q/worldedit/command/util/DelegateCommandManager.java delete mode 100644 worldedit-core/src/main/java/com/sk89q/worldedit/command/util/HookMode.java~7e3fc6c8e... Disable watchdog ticking by default, __watchdog to turn on diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 230be5156..ad4989477 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -8,18 +8,6 @@ plugins { repositories { jcenter() gradlePluginPortal() -// maven { -// name = "Forge Maven" -// url = uri("https://files.minecraftforge.net/maven") -// } -// maven { -// name = "Fabric" -// url = uri("https://maven.fabricmc.net/") -// } -// maven { -// name = "sponge" -// url = uri("https://repo.spongepowered.org/maven") -// } } configurations.all { @@ -43,15 +31,10 @@ val mixinVersion: String = properties.getProperty("mixin.version") dependencies { implementation(gradleApi()) -// implementation("gradle.plugin.net.minecrell:licenser:0.4.1") implementation("org.ajoberstar.grgit:grgit-gradle:3.1.1") implementation("com.github.jengelman.gradle.plugins:shadow:5.1.0") implementation("net.ltgt.apt-eclipse:net.ltgt.apt-eclipse.gradle.plugin:0.21") implementation("net.ltgt.apt-idea:net.ltgt.apt-idea.gradle.plugin:0.21") implementation("org.jfrog.buildinfo:build-info-extractor-gradle:4.9.7") -// implementation("gradle.plugin.org.spongepowered:spongegradle:0.9.0") -// implementation("net.minecraftforge.gradle:ForgeGradle:3.0.143") -// implementation("net.fabricmc:fabric-loom:$loomVersion") -// implementation("net.fabricmc:sponge-mixin:$mixinVersion") implementation("gradle.plugin.com.mendhak.gradlecrowdin:plugin:0.1.0") } diff --git a/buildSrc/src/main/kotlin/CommonConfig.kt b/buildSrc/src/main/kotlin/CommonConfig.kt index 72c5b934d..df1886ac0 100644 --- a/buildSrc/src/main/kotlin/CommonConfig.kt +++ b/buildSrc/src/main/kotlin/CommonConfig.kt @@ -13,7 +13,6 @@ fun Project.applyCommonConfiguration() { maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots/") } maven { url = uri("http://empcraft.com/maven2") } maven { url = uri("https://repo.destroystokyo.com/repository/maven-public") } - maven { url = uri("https://ci.athion.net/job/FAWE-Piston/ws/") } ivy { url = uri("https://ci.athion.net/job") patternLayout { artifact("/[organisation]/[revision]/artifact/[module].[ext]") diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index 838ee35c8..1dc0e3b37 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -3,7 +3,7 @@ import org.gradle.api.Project object Versions { const val TEXT = "3.0.1" const val TEXT_EXTRAS = "3.0.2" - const val PISTON = "0.5.3-SNAPSHOT" + const val PISTON = "0.5.2" const val AUTO_VALUE = "1.6.5" const val JUNIT = "5.5.0" const val MOCKITO = "3.0.0" 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 ebbf41fb3..507594edf 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 @@ -2,7 +2,6 @@ package com.boydti.fawe.bukkit.listener; import com.boydti.fawe.beta.IQueueExtent; import com.boydti.fawe.bukkit.util.image.BukkitImageViewer; -import com.boydti.fawe.command.CFICommands; import com.boydti.fawe.object.brush.BrushSettings; import com.boydti.fawe.object.brush.visualization.cfi.HeightMapMCAGenerator; import com.boydti.fawe.util.EditSessionBuilder; @@ -57,31 +56,32 @@ public class BukkitImageListener implements Listener { Bukkit.getPluginManager().registerEvents(this, plugin); } - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onPlayerInteractEntity(AsyncPlayerChatEvent event) { - Set recipients = event.getRecipients(); - Iterator iter = recipients.iterator(); - while (iter.hasNext()) { - Player player = iter.next(); - BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player); - CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings"); - if (player.equals(event.getPlayer()) || !bukkitPlayer.hasMeta() || settings == null || !settings.hasGenerator()) { - continue; - } - - String name = player.getName().toLowerCase(); - if (!event.getMessage().toLowerCase().contains(name)) { - ArrayDeque buffered = bukkitPlayer.getMeta("CFIBufferedMessages"); - if (buffered == null) { - bukkitPlayer.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque<>()); - } - String full = String.format(event.getFormat(), event.getPlayer().getDisplayName(), - event.getMessage()); - buffered.add(full); - iter.remove(); - } - } - } + //TODO Fix along with CFI code 2020-02-04 +// @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) +// public void onPlayerInteractEntity(AsyncPlayerChatEvent event) { +// Set recipients = event.getRecipients(); +// Iterator iter = recipients.iterator(); +// while (iter.hasNext()) { +// Player player = iter.next(); +// BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player); +// CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings"); +// if (player.equals(event.getPlayer()) || !bukkitPlayer.hasMeta() || settings == null || !settings.hasGenerator()) { +// continue; +// } +// +// String name = player.getName().toLowerCase(); +// if (!event.getMessage().toLowerCase().contains(name)) { +// ArrayDeque buffered = bukkitPlayer.getMeta("CFIBufferedMessages"); +// if (buffered == null) { +// bukkitPlayer.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque<>()); +// } +// String full = String.format(event.getFormat(), event.getPlayer().getDisplayName(), +// event.getMessage()); +// buffered.add(full); +// iter.remove(); +// } +// } +// } @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) public void onHangingBreakByEntity(HangingBreakByEntityEvent event) { @@ -184,126 +184,127 @@ public class BukkitImageListener implements Listener { } private void handleInteract(Event event, Player player, Entity entity, boolean primary) { - if (!(entity instanceof ItemFrame)) { - return; - } - ItemFrame itemFrame = (ItemFrame) entity; - - BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player); - CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings"); - HeightMapMCAGenerator generator = settings == null ? null : settings.getGenerator(); - BukkitImageViewer viewer = get(generator); - if (viewer == null) { - return; - } - - if (itemFrame.getRotation() != Rotation.NONE) { - itemFrame.setRotation(Rotation.NONE); - } - - LocalSession session = bukkitPlayer.getSession(); - BrushTool tool; - try { - tool = session.getBrushTool(bukkitPlayer, false); - } catch (InvalidToolBindException e) { - return; - } - - ItemFrame[][] frames = viewer.getItemFrames(); - if (frames == null || tool == null) { - viewer.selectFrame(itemFrame); - player.updateInventory(); - TaskManager.IMP.laterAsync(() -> viewer.view(generator), 1); - return; - } - - BrushSettings context = primary ? tool.getPrimary() : tool.getSecondary(); - Brush brush = context.getBrush(); - if (brush == null) { - return; - } - tool.setContext(context); - - if (event instanceof Cancellable) { - ((Cancellable) event).setCancelled(true); - } - - Location target = itemFrame.getLocation(); - Location source = player.getLocation(); - - double yawRad = Math.toRadians(source.getYaw() + 90d); - double pitchRad = Math.toRadians(-source.getPitch()); - - double a = Math.cos(pitchRad); - double xRat = Math.cos(yawRad) * a; - double zRat = Math.sin(yawRad) * a; - - BlockFace facing = itemFrame.getFacing(); - double thickness = 1 / 32D + 1 / 128D; - double modX = facing.getModX(); - double modZ = facing.getModZ(); - double dx = source.getX() - target.getX() - modX * thickness; - double dy = source.getY() + player.getEyeHeight() - target.getY(); - double dz = source.getZ() - target.getZ() - modZ * thickness; - - double offset; - double localX; - if (modX != 0) { - offset = dx / xRat; - localX = (-modX) * (dz - offset * zRat); - } else { - offset = dz / zRat; - localX = (modZ) * (dx - offset * xRat); - } - double localY = dy - offset * Math.sin(pitchRad); - int localPixelX = (int) ((localX + 0.5) * 128); - int localPixelY = (int) ((localY + 0.5) * 128); - - UUID uuid = itemFrame.getUniqueId(); - for (int blockX = 0; blockX < frames.length; blockX++) { - for (int blockY = 0; blockY < frames[0].length; blockY++) { - if (uuid.equals(frames[blockX][blockY].getUniqueId())) { - int pixelX = localPixelX + blockX * 128; - int pixelY = (128 * frames[0].length) - (localPixelY + blockY * 128 + 1); - - int width = generator.getWidth(); - int length = generator.getLength(); - int worldX = (int) (pixelX * width / (frames.length * 128d)); - int worldZ = (int) (pixelY * length / (frames[0].length * 128d)); - - if (worldX < 0 || worldX > width || worldZ < 0 || worldZ > length) { - return; - } - - bukkitPlayer.runAction(() -> { - BlockVector3 wPos = BlockVector3.at(worldX, 0, worldZ); - viewer.refresh(); - int topY = generator - .getNearestSurfaceTerrainBlock(wPos.getBlockX(), wPos.getBlockZ(), 255, - 0, 255); - wPos = wPos.withY(topY); - - EditSession es = new EditSessionBuilder(bukkitPlayer.getWorld()).player(bukkitPlayer) - .combineStages(false).autoQueue(false).blockBag(null).limitUnlimited() - .build(); - ExtentTraverser last = new ExtentTraverser(es.getExtent()).last(); - Extent extent = last.get(); - if (extent instanceof IQueueExtent) { - last = last.previous(); - } - last.setNext(generator); - try { - brush.build(es, wPos, context.getMaterial(), context.getSize()); - } catch (WorldEditException e) { - e.printStackTrace(); - } - es.flushQueue(); - viewer.view(generator); - }, true, true); - - return; - } - } - } + //todo fix with cfi code 2020-02-04 +// if (!(entity instanceof ItemFrame)) { +// return; +// } +// ItemFrame itemFrame = (ItemFrame) entity; +// +// BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player); +// CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings"); +// HeightMapMCAGenerator generator = settings == null ? null : settings.getGenerator(); +// BukkitImageViewer viewer = get(generator); +// if (viewer == null) { +// return; +// } +// +// if (itemFrame.getRotation() != Rotation.NONE) { +// itemFrame.setRotation(Rotation.NONE); +// } +// +// LocalSession session = bukkitPlayer.getSession(); +// BrushTool tool; +// try { +// tool = session.getBrushTool(bukkitPlayer, false); +// } catch (InvalidToolBindException e) { +// return; +// } +// +// ItemFrame[][] frames = viewer.getItemFrames(); +// if (frames == null || tool == null) { +// viewer.selectFrame(itemFrame); +// player.updateInventory(); +// TaskManager.IMP.laterAsync(() -> viewer.view(generator), 1); +// return; +// } +// +// BrushSettings context = primary ? tool.getPrimary() : tool.getSecondary(); +// Brush brush = context.getBrush(); +// if (brush == null) { +// return; +// } +// tool.setContext(context); +// +// if (event instanceof Cancellable) { +// ((Cancellable) event).setCancelled(true); +// } +// +// Location target = itemFrame.getLocation(); +// Location source = player.getLocation(); +// +// double yawRad = Math.toRadians(source.getYaw() + 90d); +// double pitchRad = Math.toRadians(-source.getPitch()); +// +// double a = Math.cos(pitchRad); +// double xRat = Math.cos(yawRad) * a; +// double zRat = Math.sin(yawRad) * a; +// +// BlockFace facing = itemFrame.getFacing(); +// double thickness = 1 / 32D + 1 / 128D; +// double modX = facing.getModX(); +// double modZ = facing.getModZ(); +// double dx = source.getX() - target.getX() - modX * thickness; +// double dy = source.getY() + player.getEyeHeight() - target.getY(); +// double dz = source.getZ() - target.getZ() - modZ * thickness; +// +// double offset; +// double localX; +// if (modX != 0) { +// offset = dx / xRat; +// localX = (-modX) * (dz - offset * zRat); +// } else { +// offset = dz / zRat; +// localX = (modZ) * (dx - offset * xRat); +// } +// double localY = dy - offset * Math.sin(pitchRad); +// int localPixelX = (int) ((localX + 0.5) * 128); +// int localPixelY = (int) ((localY + 0.5) * 128); +// +// UUID uuid = itemFrame.getUniqueId(); +// for (int blockX = 0; blockX < frames.length; blockX++) { +// for (int blockY = 0; blockY < frames[0].length; blockY++) { +// if (uuid.equals(frames[blockX][blockY].getUniqueId())) { +// int pixelX = localPixelX + blockX * 128; +// int pixelY = (128 * frames[0].length) - (localPixelY + blockY * 128 + 1); +// +// int width = generator.getWidth(); +// int length = generator.getLength(); +// int worldX = (int) (pixelX * width / (frames.length * 128d)); +// int worldZ = (int) (pixelY * length / (frames[0].length * 128d)); +// +// if (worldX < 0 || worldX > width || worldZ < 0 || worldZ > length) { +// return; +// } +// +// bukkitPlayer.runAction(() -> { +// BlockVector3 wPos = BlockVector3.at(worldX, 0, worldZ); +// viewer.refresh(); +// int topY = generator +// .getNearestSurfaceTerrainBlock(wPos.getBlockX(), wPos.getBlockZ(), 255, +// 0, 255); +// wPos = wPos.withY(topY); +// +// EditSession es = new EditSessionBuilder(bukkitPlayer.getWorld()).player(bukkitPlayer) +// .combineStages(false).autoQueue(false).blockBag(null).limitUnlimited() +// .build(); +// ExtentTraverser last = new ExtentTraverser(es.getExtent()).last(); +// Extent extent = last.get(); +// if (extent instanceof IQueueExtent) { +// last = last.previous(); +// } +// last.setNext(generator); +// try { +// brush.build(es, wPos, context.getMaterial(), context.getSize()); +// } catch (WorldEditException e) { +// e.printStackTrace(); +// } +// es.flushQueue(); +// viewer.view(generator); +// }, true, true); +// +// return; +// } +// } +// } } } 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 84d84bbda..6d2679df3 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 @@ -1,7 +1,6 @@ package com.boydti.fawe.bukkit.listener; import com.boydti.fawe.FaweCache; -import com.boydti.fawe.command.CFICommands; import com.boydti.fawe.object.RunnableVal3; import com.boydti.fawe.object.brush.visualization.VirtualWorld; import com.comphenix.protocol.PacketType; @@ -262,10 +261,10 @@ public class CFIPacketListener implements Listener { BukkitPlayer bukkitPlayer = BukkitAdapter.adapt(player); VirtualWorld vw = bukkitPlayer.getSession().getVirtualWorld(); if (vw != null) return vw; - CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings"); - if (settings != null && settings.hasGenerator() && settings.getGenerator().hasPacketViewer()) { - return settings.getGenerator(); - } + // CFICommands.CFISettings settings = bukkitPlayer.getMeta("CFISettings"); +// if (settings != null && settings.hasGenerator() && settings.getGenerator().hasPacketViewer()) { +// return settings.getGenerator(); +// } return null; } diff --git a/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java b/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java index 0d692550f..e810f9a5f 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/Fawe.java @@ -15,7 +15,6 @@ import com.boydti.fawe.util.TextureUtil; import com.boydti.fawe.util.WEManager; import com.github.luben.zstd.util.Native; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.extension.factory.DefaultTransformParser; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.session.request.Request; import java.io.BufferedReader; @@ -92,7 +91,8 @@ public class Fawe { private FaweVersion version; private VisualQueue visualQueue; private TextureUtil textures; - private DefaultTransformParser transformParser; + // TODO: Ping @MattBDev to reimplement 2020-02-04 +// private DefaultTransformParser transformParser; private QueueHandler queueHandler; @@ -184,7 +184,8 @@ public class Fawe { // Delayed worldedit setup TaskManager.IMP.later(() -> { try { - transformParser = new DefaultTransformParser(getWorldEdit()); + // TODO: Ping @MattBDev to reimplement 2020-02-04 +// transformParser = new DefaultTransformParser(getWorldEdit()); visualQueue = new VisualQueue(3); WEManager.IMP.managers.addAll(Fawe.this.IMP.getMaskManagers()); WEManager.IMP.managers.add(new PlotSquaredFeature()); @@ -208,10 +209,11 @@ public class Fawe { } return queueHandler; } - - public DefaultTransformParser getTransformParser() { - return transformParser; - } + + // TODO: Ping @MattBDev to reimplement 2020-02-04 +// public DefaultTransformParser getTransformParser() { +// return transformParser; +// } public TextureUtil getCachedTextureUtil(boolean randomize, int min, int max) { // TODO NOT IMPLEMENTED - optimize this by caching the default true/0/100 texture util diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/CFICommand.java b/worldedit-core/src/main/java/com/boydti/fawe/command/CFICommand.java index 1579b3604..909f30fc6 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/CFICommand.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/command/CFICommand.java @@ -1,88 +1,89 @@ -package com.boydti.fawe.command; - -import static com.sk89q.worldedit.util.formatting.text.TextComponent.newline; - -import com.boydti.fawe.command.CFICommands.CFISettings; -import com.boydti.fawe.object.brush.visualization.cfi.HeightMapMCAGenerator; -import com.boydti.fawe.object.changeset.CFIChangeSet; -import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.entity.Player; -import com.sk89q.worldedit.util.formatting.text.TextComponent; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import org.enginehub.piston.CommandManager; -import org.enginehub.piston.exception.StopExecutionException; -import org.enginehub.piston.inject.InjectedValueAccess; -import org.enginehub.piston.inject.Key; - -public class CFICommand extends CommandProcessor { - - public CFICommand(CommandManager manager) { - super(manager); - } - - @Override - public List preprocess(InjectedValueAccess context, List args) { - Player player = context.injectedValue(Key.of(Player.class)).orElseThrow(() -> new IllegalStateException("No player")); - CFICommands.CFISettings settings = CFICommands.getSettings(player); - settings.popMessages(player); - args = dispatch(player, settings, args, context); - HeightMapMCAGenerator gen = settings.getGenerator(); - if (gen != null && gen.isModified()) { - try { - gen.update(); - CFIChangeSet set = new CFIChangeSet(gen, player.getUniqueId()); - LocalSession session = player.getSession(); - session.remember(player, gen, set, player.getLimit()); - } catch (IOException e) { - throw new StopExecutionException(TextComponent.of(e.getMessage())); - } - } - return args; - } - - @Override - public Object process(InjectedValueAccess context, List args, Object result) { - return result; - } - - private List dispatch(Player player, CFISettings settings, List args, InjectedValueAccess context) { - if (!settings.hasGenerator()) { - if (args.size() == 0) { - String hmCmd = "/cfi "; - if (settings.image == null) { - hmCmd += "image"; - } else { - hmCmd = "heightmap" + " " + settings.imageArg; - } - TextComponent build = TextComponent.builder("What do you want to use as the base?") - .append(newline()) - .append("[HeightMap]")/* TODO .cmdTip(hmCmd).*/.append(" - A heightmap like ") - .append("[this]")//TODO .linkTip("http://i.imgur.com/qCd30MR.jpg") - .append(newline()) - .append("[Empty]")//TODO .cmdTip(CFICommands.alias() + " empty") - .append("- An empty map of a specific size").build(); - player.print(build); - } else { - args = new ArrayList<>(args); - switch (args.size()) { - case 1: - args.add(0, "heightmap"); - break; - case 2: - args.add(0, "empty"); - break; - } - return args; - } - } else { - if (args.isEmpty()) { - settings.setCategory(null); - CFICommands.mainMenu(player); - return null; - } - } - return args; - } -} +// TODO: Ping @MattBDev to reimplement 2020-02-04 +//package com.boydti.fawe.command; +// +//import static com.sk89q.worldedit.util.formatting.text.TextComponent.newline; +// +//import com.boydti.fawe.command.CFICommands.CFISettings; +//import com.boydti.fawe.object.brush.visualization.cfi.HeightMapMCAGenerator; +//import com.boydti.fawe.object.changeset.CFIChangeSet; +//import com.sk89q.worldedit.LocalSession; +//import com.sk89q.worldedit.entity.Player; +//import com.sk89q.worldedit.util.formatting.text.TextComponent; +//import java.io.IOException; +//import java.util.ArrayList; +//import java.util.List; +//import org.enginehub.piston.CommandManager; +//import org.enginehub.piston.exception.StopExecutionException; +//import org.enginehub.piston.inject.InjectedValueAccess; +//import org.enginehub.piston.inject.Key; +// +//public class CFICommand extends CommandProcessor { +// +// public CFICommand(CommandManager manager) { +// super(manager); +// } +// +// @Override +// public List preprocess(InjectedValueAccess context, List args) { +// Player player = context.injectedValue(Key.of(Player.class)).orElseThrow(() -> new IllegalStateException("No player")); +// CFICommands.CFISettings settings = CFICommands.getSettings(player); +// settings.popMessages(player); +// args = dispatch(player, settings, args, context); +// HeightMapMCAGenerator gen = settings.getGenerator(); +// if (gen != null && gen.isModified()) { +// try { +// gen.update(); +// CFIChangeSet set = new CFIChangeSet(gen, player.getUniqueId()); +// LocalSession session = player.getSession(); +// session.remember(player, gen, set, player.getLimit()); +// } catch (IOException e) { +// throw new StopExecutionException(TextComponent.of(e.getMessage())); +// } +// } +// return args; +// } +// +// @Override +// public Object process(InjectedValueAccess context, List args, Object result) { +// return result; +// } +// +// private List dispatch(Player player, CFISettings settings, List args, InjectedValueAccess context) { +// if (!settings.hasGenerator()) { +// if (args.size() == 0) { +// String hmCmd = "/cfi "; +// if (settings.image == null) { +// hmCmd += "image"; +// } else { +// hmCmd = "heightmap" + " " + settings.imageArg; +// } +// TextComponent build = TextComponent.builder("What do you want to use as the base?") +// .append(newline()) +// .append("[HeightMap]")/* TODO .cmdTip(hmCmd).*/.append(" - A heightmap like ") +// .append("[this]")//TODO .linkTip("http://i.imgur.com/qCd30MR.jpg") +// .append(newline()) +// .append("[Empty]")//TODO .cmdTip(CFICommands.alias() + " empty") +// .append("- An empty map of a specific size").build(); +// player.print(build); +// } else { +// args = new ArrayList<>(args); +// switch (args.size()) { +// case 1: +// args.add(0, "heightmap"); +// break; +// case 2: +// args.add(0, "empty"); +// break; +// } +// return args; +// } +// } else { +// if (args.isEmpty()) { +// settings.setCategory(null); +// CFICommands.mainMenu(player); +// return null; +// } +// } +// return args; +// } +//} 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 70c4a55c3..7ab6d1f15 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 @@ -1,1304 +1,1305 @@ -package com.boydti.fawe.command; - -import static com.boydti.fawe.util.image.ImageUtil.load; -import static com.sk89q.worldedit.command.MethodCommands.getArguments; -import static com.sk89q.worldedit.util.formatting.text.TextComponent.newline; - -import com.boydti.fawe.Fawe; -import com.boydti.fawe.FaweAPI; -import com.boydti.fawe.beta.implementation.filter.block.SingleFilterBlock; -import com.boydti.fawe.config.Caption; -import com.boydti.fawe.object.RunnableVal; -import com.boydti.fawe.object.brush.visualization.cfi.HeightMapMCAGenerator; -import com.boydti.fawe.object.clipboard.MultiClipboardHolder; -import com.boydti.fawe.util.CleanTextureUtil; -import com.boydti.fawe.util.FilteredTextureUtil; -import com.boydti.fawe.util.ImgurUtility; -import com.boydti.fawe.util.MathMan; -import com.boydti.fawe.util.StringMan; -import com.boydti.fawe.util.TaskManager; -import com.boydti.fawe.util.TextureUtil; -import com.boydti.fawe.util.image.ImageUtil; -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.sk89q.minecraft.util.commands.CommandException; -import com.sk89q.worldedit.EmptyClipboardException; -import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.command.util.CommandPermissions; -import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; -import com.sk89q.worldedit.entity.Player; -import com.sk89q.worldedit.extension.input.InputParseException; -import com.sk89q.worldedit.extension.input.ParserContext; -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.binding.ProvideBindings; -import com.sk89q.worldedit.extent.clipboard.Clipboard; -import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; -import com.sk89q.worldedit.function.mask.Mask; -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; -import com.sk89q.worldedit.util.Location; -import com.sk89q.worldedit.util.formatting.component.TextComponentProducer; -import com.sk89q.worldedit.util.formatting.text.TextComponent; -import com.sk89q.worldedit.util.formatting.text.TextComponent.Builder; -import com.sk89q.worldedit.util.formatting.text.event.ClickEvent; -import com.sk89q.worldedit.util.formatting.text.event.HoverEvent; -import com.sk89q.worldedit.util.formatting.text.format.TextColor; -import com.sk89q.worldedit.world.World; -import com.sk89q.worldedit.world.biome.BiomeType; -import com.sk89q.worldedit.world.block.BlockStateHolder; -import com.sk89q.worldedit.world.block.BlockType; -import com.sk89q.worldedit.world.block.BlockTypes; -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferInt; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.URL; -import java.nio.file.Path; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayDeque; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.stream.IntStream; -import javax.imageio.ImageIO; -import org.enginehub.piston.annotation.Command; -import org.enginehub.piston.annotation.CommandContainer; -import org.enginehub.piston.annotation.param.Arg; -import org.enginehub.piston.annotation.param.Switch; -import org.enginehub.piston.exception.StopExecutionException; -import org.enginehub.piston.inject.InjectedValueAccess; -import org.jetbrains.annotations.NotNull; - -@CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class) -public class CFICommands { - - private final WorldEdit worldEdit; - private final TextComponent doubleNewLine = TextComponent.of("\n\n"); - - /** - * Create a new instance. - * - * @param worldEdit reference to WorldEdit - */ - public CFICommands(WorldEdit worldEdit) { - this.worldEdit = worldEdit; - } - - public static File getFolder(String worldName) { - Platform platform = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING); - List worlds = platform.getWorlds(); - Path path = worlds.get(0).getStoragePath(); - return new File(path.toFile().getParentFile().getParentFile(), worldName + File.separator + "region"); - } - - @Command( - name = "heightmap", - desc = "Start CFI with a height map as a base" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void heightmap(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "double", def = "1") double yscale) { - if (yscale != 0) { - int[] raw = ((DataBufferInt) image.load().getRaster().getDataBuffer()).getData(); - int[] table = IntStream.range(0, 256).map(i -> Math.min(255, (int) (i * yscale))) - .toArray(); - for (int i = 0; i < raw.length; i++) { - int color = raw[i]; - int red = table[(color >> 16) & 0xFF]; - int green = table[(color >> 8) & 0xFF]; - int blue = table[(color >> 0) & 0xFF]; - raw[i] = (red << 16) + (green << 8) + (blue << 0); - } - } - HeightMapMCAGenerator generator = new HeightMapMCAGenerator(image.load(), getFolder(generateName())); - setup(generator, player); - } - - @Command( - name = "empty", - desc = "Start CFI with an empty map as a base" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void empty(Player player, @Arg(desc = "Map width (x)") int width, @Arg(desc = "Map length (z)") int length) { - HeightMapMCAGenerator generator = new HeightMapMCAGenerator(width, length, getFolder(generateName())); - setup(generator, player); - } - - private String generateName() { - DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH.mm.ss"); - return df.format(new Date()); - } - - private void setup(HeightMapMCAGenerator generator, Player player) { - CFISettings settings = getSettings(player).remove(); - generator.setPacketViewer(player); - settings.setGenerator(generator).bind(); - generator.setImageViewer(Fawe.imp().getImageViewer(player)); - generator.update(); - mainMenu(player); - } - - @Command( - name = "brush", - desc = "Info about using brushes with CFI" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void brush(Player player) { - CFISettings settings = assertSettings(player); - settings.popMessages(player); - @NotNull Builder msg; - if (settings.getGenerator().getImageViewer() != null) { - msg = TextComponent.builder("CFI supports using brushes during creation").append(newline()) - .append(" - Place the map on a wall of item frames").append(newline()) - .append(" - Use any WorldEdit brush on the item frames").append(newline()) - .append(" - Example: ").append(TextComponent.of("Video").clickEvent(ClickEvent.openUrl("https://goo.gl/PK4DMG"))).append(newline()); - } else { - msg = TextComponent.builder("This is not supported with your platform/version").append(newline()); - } - //TODO msg.text("< [Back]").cmdTip(alias()).send(player); - player.print(msg.build()); - } - - @Command( - name = "cancel", - aliases = {"exit"}, - desc = "Cancel creation" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void cancel(Player player) { - getSettings(player).remove(); - player.print("Cancelled!"); - } - - @Command( - name = "done", - aliases = "create", - desc = "Create the world" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void done(Player player) { - CFISettings settings = assertSettings(player); - HeightMapMCAGenerator generator = settings.getGenerator(); - - Function function = folder -> { - if (folder != null) { - try { - generator.setFolder(folder); - player.print("Generating " + folder); - generator.generate(); - generator.setPacketViewer(null); - generator.setImageViewer(null); - settings.remove(); - player.print("Done!"); - return true; - } catch (IOException e) { - throw new RuntimeException(e); - } - } else { - player.print("Unable to generate world... (see console)?"); - } - return false; - }; - - try { - new PlotLoader().load(player, settings, function); - } catch (Throwable e) { - e.printStackTrace(); - function.apply(generator.getFolder().getParentFile()); - } - - File folder = generator.getFolder(); - if (folder != null) { - World world = FaweAPI.getWorld(folder.getName()); - if (world != null) { - if (player.getWorld() != world) { - TaskManager.IMP.sync(new RunnableVal() { - @Override - public void run(Object value) { - Location spawn = new Location(world, world.getSpawnPosition().toVector3()); - player.setPosition(spawn); - } - }); - } - } else { - player.print("Unable to import world (" + folder.getName() + ") please do so manually"); - } - } - } - - @Command( - name = "column", - desc = "Set the floor and main block" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void column(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ - HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); - if (image != null) { - gen.setColumn(load(image), pattern, !disableWhiteOnly); - } else if (mask != null) { - gen.setColumn(mask, pattern); - } else { - gen.setColumn(pattern); - } - player.print("Set column!"); - assertSettings(player).resetComponent(); - component(player); - } - - @Command( - name = "floor", - desc = "Set the floor (default: grass)" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void floorCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ - floor(player, pattern, image, mask, disableWhiteOnly); - player.print("Set floor!"); - assertSettings(player).resetComponent(); - component(player); - } - - private void floor(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) { - HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); - if (image != null) { - gen.setFloor(load(image), pattern, !disableWhiteOnly); - } else if (mask != null) { - gen.setFloor(mask, pattern); - } else { - gen.setFloor(pattern); - } - } - - @Command( - name = "main", - desc = "Set the main block (default: stone)" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void mainCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ - main(player, pattern, image, maskOpt, disableWhiteOnly); - player.print("Set main!"); - assertSettings(player).resetComponent(); - component(player); - } - - public void main(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ - HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); - if (image != null) { - gen.setMain(load(image), pattern, !disableWhiteOnly); - } else if (maskOpt != null) { - gen.setMain(maskOpt, pattern); - } else { - gen.setMain(pattern); - } - } - - @Command( - name = "overlay", - aliases = {"setoverlay"}, - desc = "Set the overlay block", - descFooter = "Change the block directly above the floor (default: air)\n" + - "e.g., Tallgrass" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void overlay(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ - HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); - if (image != null) { - gen.setOverlay(load(image), pattern, !disableWhiteOnly); - } else if (mask != null) { - gen.setOverlay(mask, pattern); - } else { - gen.setOverlay(pattern); - } - player.print("Set overlay!"); - component(player); - } - - @Command( - name = "smooth", - desc = "Smooth the terrain", - descFooter = "Smooth terrain within an image-mask, or worldedit mask\n" + - " - You can use !0 as the mask to smooth everything\n" + - " - This supports smoothing snow layers (set the floor to 78:7)\n" + - " - A good value for radius and iterations would be 1 8." - ) - @CommandPermissions("worldedit.anvil.cfi") - public void smoothCmd(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ - smooth(player, radius, iterations, image, mask, disableWhiteOnly); - assertSettings(player).resetComponent(); - component(player); - } - - private void smooth(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ - HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); - if (image != null) { - gen.smooth(load(image), !disableWhiteOnly, radius, iterations); - } else { - gen.smooth(mask, radius, iterations); - } - } - - @Command( - name = "snow", - desc = "Create some snow" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void snow(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ - HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); - floor(player, BlockTypes.SNOW.getDefaultState().with(PropertyKey.LAYERS, 7), image, mask, disableWhiteOnly); - main(player, BlockTypes.SNOW_BLOCK, image, mask, disableWhiteOnly); - smooth(player, 1, 8, image, mask, disableWhiteOnly); - player.print(TextComponent.of("Added snow!")); - assertSettings(player).resetComponent(); - component(player); - } - - @Command( - name = "biomepriority", - desc = "Set the biome priority", - descFooter = "Increase or decrease biome priority when using blockBiomeColor.\n" + - "A value of 50 is the default\n" + - "Above 50 will prefer to color with biomes\n" + - "Below 50 will prefer to color with blocks" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void biomepriority(Player player, int value) { - assertSettings(player).getGenerator().setBiomePriority(value); - coloring(player); - } - - @Command( - name = "paletteblocks", - desc = "Set the blocks used for coloring", - descFooter = "Allow only specific blocks to be used for coloring\n" + - "`blocks` is a list of blocks e.g., stone,bedrock,wool\n" + - "`#clipboard` will only use the blocks present in your clipboard." - ) - @CommandPermissions("worldedit.anvil.cfi") - public void paletteblocks(Player player, LocalSession session, @Arg(name = "arg", desc = "String", def = "") String argOpt) throws EmptyClipboardException, InputParseException, FileNotFoundException { - if (argOpt == null) { - TextComponent build = TextComponent.builder("What blocks do you want to color with?") - .append(newline()) - .append(TextComponent.of("[All]") - .clickEvent(ClickEvent.runCommand("/cfi PaletteBlocks *"))) - .append(" - All available blocks") - .append(newline()) - .append(TextComponent.of("[Clipboard]") - .clickEvent(ClickEvent.runCommand("/cfi PaletteBlocks #clipboard"))) - .append(" - The blocks in your clipboard") - .append(newline()) - .append(TextComponent.of("[List]") - .clickEvent(ClickEvent.runCommand("/cfi PaletteBlocks stone,gravel"))) - .append(" - A comma separated list of blocks") - .append(newline()) - .append(TextComponent.of("[Complexity]") - .clickEvent(ClickEvent.runCommand("/cfi Complexity"))) - .append(" - Block textures within a complexity range") - .append(newline()) - .append(TextComponent.of("< [Back]").clickEvent(ClickEvent - .runCommand("/cfi coloring"))) - .build(); - player.print(build); - return; - } - HeightMapMCAGenerator generator = assertSettings(player).getGenerator(); - ParserContext context = new ParserContext(); - context.setActor(player); - context.setWorld(player.getWorld()); - context.setSession(player.getSession()); - context.setExtent(generator); - Request.request().setExtent(generator); - - Set blocks; - switch (argOpt.toLowerCase()) { - case "true": - case "*": { - generator.setTextureUtil(Fawe.get().getTextureUtil()); - return; - } - case "#clipboard": { - ClipboardHolder holder = player.getSession().getClipboard(); - Clipboard clipboard = holder.getClipboard(); - boolean[] ids = new boolean[BlockTypes.size()]; - for (BlockVector3 pt : clipboard.getRegion()) { - ids[clipboard.getBlock(pt).getBlockType().getInternalId()] = true; - } - blocks = new HashSet<>(); - for (int combined = 0; combined < ids.length; combined++) { - if (ids[combined]) { - blocks.add(BlockTypes.get(combined)); - } - } - break; - } - default: { - blocks = new HashSet<>(); - SingleFilterBlock extent = new SingleFilterBlock(); - ParserContext parserContext = new ParserContext(); - parserContext.setActor(player); - parserContext.setWorld(player.getWorld()); - parserContext.setSession(session); - parserContext.setExtent(extent); - Request.request().setExtent(extent); - Mask mask = worldEdit.getMaskFactory().parseFromInput(argOpt, parserContext); - TextureUtil tu = Fawe.get().getTextureUtil(); - for (int typeId : tu.getValidBlockIds()) { - BlockType type = BlockTypes.get(typeId); - extent.init(0, 0, 0, type.getDefaultState().toBaseBlock()); - if (mask.test(extent, extent)) { - blocks.add(type); - } - } - break; - } - } - generator.setTextureUtil(new FilteredTextureUtil(Fawe.get().getTextureUtil(), blocks)); - coloring(player); - } - - @Command( - name = "randomization", - desc = "Set whether randomization is enabled", - descFooter = "This is enabled by default, randomization will add some random variation in the blocks used to closer match the provided image.\n" + - "If disabled, the closest block to the color will always be used.\n" + - "Randomization will allow mixing biomes when coloring with biomes" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void randomization(Player player, boolean enabled) { - assertSettings(player).getGenerator().setTextureRandomVariation(enabled); - coloring(player); - } - - @Command( - name = "complexity", - desc = "Set the complexity for coloring", - descFooter = "Set the complexity for coloring\n" + - "Filter out blocks to use based on their complexity, which is a measurement of how much color variation there is in the texture for that block.\n" + - "Glazed terracotta is complex, and not very pleasant for terrain, whereas stone and wool are simpler textures.\n" + - "Using 0 73 for the min/max would use the simplest 73% of blocks for coloring, and is a reasonable value." - ) - @CommandPermissions("worldedit.anvil.cfi") - public void complexity(Player player, int min, int max) throws FileNotFoundException { - HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); - if (min == 0 && max == 100) { - gen.setTextureUtil(Fawe.get().getTextureUtil()); - } else { - gen.setTextureUtil(new CleanTextureUtil(Fawe.get().getTextureUtil(), min, max)); - } - coloring(player); - } - - @Command( - name = "schem", - desc = "Populate schematics", - descFooter = "Populate a schematic on the terrain\n" + - " - Change the mask (e.g. angle mask) to only place the schematic in specific locations.\n" + - " - The rarity is a value between 0 and 100.\n" + - " - The distance is the spacing between each schematic" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void schem(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask") Mask mask, String schematic, int rarity, int distance, boolean rotate)throws IOException, WorldEditException { - HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); - - World world = player.getWorld(); - MultiClipboardHolder multi = ClipboardFormats.loadAllFromInput(player, schematic, null, true); - if (multi == null) { - return; - } - if (imageMask == null) { - gen.addSchems(mask, multi.getHolders(), rarity, distance, rotate); - } else { - gen.addSchems(load(imageMask), mask, multi.getHolders(), rarity, distance, rotate); - } - player.print(TextComponent.of("Added schematics!")); - populate(player); - } - - @Command( - name = "biome", - desc = "Set the biome", - descFooter = "Set the biome in specific parts of the map.\n" + - " - If an image is used, the biome will have a chance to be set based on how white the pixel is (white #FFF = 100% chance)" + - " - The whiteOnly parameter determines if only white values on the image are set" + - " - If a mask is used, the biome will be set anywhere the mask applies" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void biome(Player player, @Arg(desc = "Biome type") BiomeType biome, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ - HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); - if (image != null) { - gen.setBiome(load(image), biome, !disableWhiteOnly); - } else if (mask != null) { - gen.setBiome(mask, biome); - } else { - gen.setBiome(biome); - } - player.print(TextComponent.of("Set biome!")); - assertSettings(player).resetComponent(); - component(player); - } - - @Command( - name = "caves", - desc = "Generate vanilla caves" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void caves(Player player) throws WorldEditException { - assertSettings(player).getGenerator().addCaves(); - player.print(TextComponent.of("Added caves!")); - populate(player); - } - - @Command( - name = "ore", - desc = "Add an ore", - descFooter = "Use a specific pattern and settings to generate ore" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void ore(Player player, @Arg(desc = "Mask") Mask mask, @Arg(desc = "Pattern") Pattern pattern, int size, int frequency, int rarity, int minY, int maxY) throws WorldEditException { - assertSettings(player).getGenerator().addOre(mask, pattern, size, frequency, rarity, minY, maxY); - player.print(TextComponent.of("Added ore!")); - populate(player); - } - - @Command( - name = "ores", - desc = "Generate the vanilla ores" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void ores(Player player, @Arg(desc = "Mask") Mask mask) throws WorldEditException { - assertSettings(player).getGenerator().addDefaultOres(mask); - player.print(TextComponent.of("Added ores!")); - populate(player); - } - - @Command( - name = "height", - desc = "Set the height", - descFooter = "Set the terrain height either based on an image heightmap, or a numeric value." - ) - @CommandPermissions("worldedit.anvil.cfi") - public void height(Player player, @Arg(name = "height", desc = "Int height, or image") String imageStr) throws WorldEditException { - HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); - if (!MathMan.isInteger(imageStr)) { - gen.setHeight(ImageUtil.getImage(imageStr)); - } else { - gen.setHeights(Integer.parseInt(imageStr)); - } - player.print("Set Height!"); - component(player); - } - - @Command( - name = "water", - desc = "Change the block used for water\n e.g., Lava" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void waterId(Player player, @Arg(desc = "block") BlockStateHolder block) throws WorldEditException { - CFISettings settings = assertSettings(player); - settings.getGenerator().setWater(block.toImmutableState()); - - player.print("Set water id!"); - settings.resetComponent(); - component(player); - } - - @Command( - name = "baseid", - aliases = {"bedrockid"}, - desc = "Change the block used for the base\ne.g. Bedrock" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void baseId(Player player, @Arg(desc = "block") BlockStateHolder block) throws WorldEditException { - CFISettings settings = assertSettings(player); - settings.getGenerator().setBedrock(block.toImmutableState()); - player.print(TextComponent.of("Set base id!")); - settings.resetComponent(); - component(player); - } - - @Command( - name = "worldthickness", - aliases = {"width", "thickness"}, - desc = "Set the thickness of the generated world\n" + - " - A value of 0 is the default and will not modify the height" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void worldthickness(Player player, @Arg(desc = "brush height") int height) throws WorldEditException { - assertSettings(player).getGenerator().setWorldThickness(height); - player.print("Set world thickness!"); - component(player); - } - - @Command( - name = "floorthickness", - aliases = {"floorheight", "floorwidth"}, - desc = "Set the thickness of the top layer\n" + - " - A value of 0 is the default and will only set the top block" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void floorthickness(Player player, @Arg( desc = "brush height") int height) throws WorldEditException { - assertSettings(player).getGenerator().setFloorThickness(height); - player.print("Set floor thickness!"); - component(player); - } - - @Command( - name = "update", - aliases = {"refresh", "resend"}, - desc = "Resend the CFI chunks" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void update(Player player) throws WorldEditException { - assertSettings(player).getGenerator().update(); - player.print("Chunks refreshed!"); - mainMenu(player); - } - - @Command( - name = "tp", - aliases = {"visit", "home"}, - desc = "Teleport to the CFI virtual world" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void tp(Player player) throws WorldEditException { - HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); - player.print("Teleporting..."); - Vector3 origin = gen.getOrigin(); - player.setPosition(origin.subtract(16, 0, 16)); - player.findFreePosition(); - mainMenu(player); - } - - @Command( - name = "waterheight", - aliases = {"sealevel", "setwaterheight"}, - desc = "Set the level water is generated at\n" + - "Set the level water is generated at\n" + - " - By default water is disabled (with a value of 0)" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void waterheight(Player player, @Arg(desc = "brush height") int height) throws WorldEditException { - assertSettings(player).getGenerator().setWaterHeight(height); - player.print("Set water height!"); - component(player); - } - - @Command( - name = "glass", - aliases = {"glasscolor", "setglasscolor"}, - desc = "Color terrain using glass" - ) - // ![79,174,212,5:3,5:4,18,161,20] - @CommandPermissions("worldedit.anvil.cfi") - public void glass(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException { - CFISettings settings = assertSettings(player); - settings.getGenerator().setColorWithGlass(load(image)); - player.print("Set color with glass!"); - settings.resetColoring(); - mainMenu(player); - } - - @Command( - name = "color", - aliases = {"setcolor", "blockcolor", "blocks"}, - desc = "Set the color with blocks and biomes", - descFooter = "Color the terrain using only blocks\n" + - "Provide an image, or worldedit mask for the 2nd argument to restrict what areas are colored\n" + - "The -w (disableWhiteOnly) will randomly apply depending on the pixel luminance" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void color(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException { - CFISettings settings = assertSettings(player); - HeightMapMCAGenerator gen = settings.getGenerator(); - if (imageMask != null) { - gen.setColor(load(image), load(imageMask), !disableWhiteOnly); - } else if (mask != null) { - gen.setColor(load(image), mask); - } else { - gen.setColor(load(image)); - } - settings.resetColoring(); - player.print("Set color with blocks!"); - mainMenu(player); - } - - @Command( - name = "blockbiomecolor", - aliases = {"setblockandbiomecolor", "blockandbiome"}, - desc = "Set the color with blocks and biomes", - descFooter = "Color the terrain using blocks and biomes.\n" + - "Provide an image, or worldedit mask to restrict what areas are colored\n" + - "The -w (disableWhiteOnly) will randomly apply depending on the pixel luminance" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void blockbiome(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException { - CFISettings settings = assertSettings(player); - settings.getGenerator().setBlockAndBiomeColor(load(image), mask, load(imageMask), !disableWhiteOnly); - player.print(TextComponent.of("Set color with blocks and biomes!")); - settings.resetColoring(); - mainMenu(player); - } - - @Command( - name = "biomecolor", - aliases = {"setbiomecolor", "biomes"}, - desc = "Color the terrain using biomes.\n" + - "Note: Biome coloring does not change blocks:\n" + - " - If you changed the block to something other than grass you will not see anything." - ) - @CommandPermissions("worldedit.anvil.cfi") - public void biomecolor(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException { - CFISettings settings = assertSettings(player); - settings.getGenerator().setBiomeColor(load(image)); - player.print(TextComponent.of("Set color with biomes!")); - settings.resetColoring(); - mainMenu(player); - } - - - @Command( - name = "coloring", - aliases = {"palette"}, - desc = "Color the world using an image" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void coloring(Player player) { - CFISettings settings = assertSettings(player); - settings.popMessages(player); - settings.setCategory(this::coloring); - HeightMapMCAGenerator gen = settings.getGenerator(); - boolean rand = gen.getTextureRandomVariation(); - String mask; - if (settings.imageMask != null) { - mask = settings.imageMaskArg; - } else if (settings.mask != null) { - mask = settings.maskArg; - } else { - mask = "NONE"; - } - TextureUtil tu = gen.getRawTextureUtil(); - String blocks; - if (tu.getClass() == TextureUtil.class) { - blocks = "All"; - } else if (tu.getClass() == CleanTextureUtil.class) { - CleanTextureUtil clean = (CleanTextureUtil) tu; - blocks = "Complexity(" + clean.getMin() + "," + clean.getMax() + ")"; - } else if (tu.getClass() == FilteredTextureUtil.class) { - blocks = "Selected"; - } else { - blocks = "Undefined"; - } - - Set materials = new HashSet<>(); - int[] blockArray = tu.getValidBlockIds(); - for (int typeId : blockArray) { - BlockType type = BlockTypes.get(typeId); - String name = type.getName(); - if (name.contains(":")) { - name = name.split(":")[1]; - } - materials.add(name); - } - String blockList = materials.size() > 100 ? materials.size() + " blocks" : StringMan.join(materials, ','); - - int biomePriority = gen.getBiomePriority(); - TextComponent.empty().clickEvent(ClickEvent.runCommand( - "/cfi randomization " + !rand)).hoverEvent(HoverEvent.showText( - TextComponent.of("/cfi randomization " + !rand))); - @NotNull Builder builder = TextComponent.builder(">> Current Settings <<"); - builder.append(newline()); - builder.append(TextComponent.of("Randomization [" + Boolean.toString(rand).toUpperCase() + "]") - .clickEvent(ClickEvent.runCommand( - "/cfi randomization " + !rand)).hoverEvent(HoverEvent.showText( - TextComponent.of("/cfi randomization " + !rand)))); - builder.append(newline()); - builder.append(TextComponent.of("Mask [" + mask + "]").clickEvent(ClickEvent.runCommand( - "/cfi mask")).hoverEvent(HoverEvent.showText( - TextComponent.of("/cfi mask")))); - builder.append(newline()); - builder.append(TextComponent.of("Blocks [" + blocks + "]").clickEvent(ClickEvent.runCommand( - "/cfi mask")).hoverEvent(HoverEvent.showText( - TextComponent.of("/cfi mask")))); - builder.append(newline()); - builder.append(TextComponent.of("Biome Priority [" + biomePriority + "]").clickEvent(ClickEvent.runCommand( - "/cfi mask")).hoverEvent(HoverEvent.showText( - TextComponent.of("/cfi biomepriority")))); - builder.append(newline()); - - if (settings.image != null) { - StringBuilder colorArgs = new StringBuilder(" " + settings.imageArg); - if (settings.imageMask != null) { - colorArgs.append(" ").append(settings.imageMaskArg); - } - if (settings.mask != null) { - colorArgs.append(" ").append(settings.maskArg); - } - if (!settings.whiteOnly) { - colorArgs.append(" -w"); - } - - //TODO - builder.append("Image: ") - .append("[" + settings.imageArg + "]")//.cmdTip("/cfi " + Commands.getAlias(CFICommands.class, "image")) - .append(newline()).append(newline()) - .append("Let's Color: ") - //.cmdOptions("/cfi ", colorArgs.toString(), "Biomes", "Blocks", "BlockAndBiome", "Glass") - .append(newline()); - } else { - builder.append(newline()).append("You can color a world using an image like ") - .append(TextComponent.of("[This]").clickEvent(ClickEvent.openUrl("http://i.imgur.com/vJYinIU.jpg"))).append(newline()) - .append("You MUST provide an image: ") - .append("[None]");//.cmdTip("/cfi " + Commands.getAlias(Command.class, "image")).append(newline()); - } - builder.append("< [Back]");//.cmdTip(alias()).send(player); - player.print(builder.build()); - } - - @Command( - name = "mask", - desc = "Select a mask" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void mask(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly, InjectedValueAccess context){ - CFISettings settings = assertSettings(player); - String[] split = getArguments(context).split(" "); - int index = 2; - settings.imageMask = imageMask; - settings.imageMaskArg = imageMask != null ? split[index++] : null; - settings.mask = mask; - settings.maskArg = mask != null ? split[index++] : null; - settings.whiteOnly = !disableWhiteOnly; - - String s = "/cfi mask http://"; - String s1 = "/cfi mask "; - String s2 = "/cfi " + settings.getCategory(); - TextComponent build = TextComponent.builder(">> Current Settings <<") - .append(newline()) - .append("Image Mask ").append( - TextComponent.of("[" + settings.imageMaskArg + "]") - .hoverEvent(HoverEvent.showText(TextComponent.of(s))) - .clickEvent(ClickEvent.suggestCommand("/cfi mask http://"))) - .append(newline()) - .append("WorldEdit Mask ").append(TextComponent.of("[" + settings.maskArg + "]") - .hoverEvent(HoverEvent.showText(TextComponent.of(s1))) - .clickEvent(ClickEvent.suggestCommand(s1))) - .append(newline()) - .append( - TextComponent.of("< [Back]").hoverEvent(HoverEvent.showText(TextComponent.of(s2))) - .clickEvent(ClickEvent.runCommand(s2))).build(); - player.print(build); - } - - @Command( - name = "pattern", - desc = "Select a pattern" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void pattern(Player player, @Arg(desc = "Pattern", def = "") Pattern pattern, InjectedValueAccess context)throws CommandException { - CFISettings settings = assertSettings(player); - String[] split = getArguments(context).split(" "); - int index = 2; - settings.pattern = pattern; - settings.patternArg = pattern == null ? null : split[index++]; - - StringBuilder cmd = new StringBuilder("/cfi pattern "); - - if (pattern != null) { - settings.getCategory().accept(player); - } else { - String s = cmd + " stone"; - String s1 = "/cfi " + settings.getCategory(); - TextComponent build = TextComponent.builder(">> Current Settings <<").append(newline()) - .append("Pattern ").append(TextComponent.of("[Click Here]") - .hoverEvent(HoverEvent.showText(TextComponent.of(s))) - .clickEvent(ClickEvent.suggestCommand(s))) - .append(newline()) - .append(TextComponent.of("< [Back]") - .hoverEvent(HoverEvent.showText(TextComponent.of(s1))) - .clickEvent(ClickEvent.runCommand(s1))).build(); - player.print(build); - } - } - - @Command( - name = "download", - desc = "Download the current image" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void download(Player player)throws IOException { - CFISettings settings = assertSettings(player); - BufferedImage image = settings.getGenerator().draw(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ImageIO.write(image, "jpg", baos); - byte[] data = baos.toByteArray(); - player.print("Please wait..."); - String json = ImgurUtility.getImgurContent(ImgurUtility.CLIENT_ID, data); - Gson gson = new Gson(); - JsonObject obj = gson.fromJson(json, JsonObject.class); - JsonObject data1 = obj.get("data").getAsJsonObject(); - String link = data1.get("link").getAsString(); - URL url = new URL(link); - player.print(Caption.of("fawe.web.download.link" , url)); - } - - @Command( - name = "image", - desc = "Select an image" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void image(Player player, @Arg(desc = "image url or filename", def = "") ProvideBindings.ImageUri image, InjectedValueAccess context)throws CommandException { - CFISettings settings = getSettings(player); - String[] split = getArguments(context).split(" "); - int index = 2; - - settings.image = image; - settings.imageArg = image != null ? split[index++] : null; - - if (image == null) { - TextComponent build = TextComponent.builder("Please provide an image:") - .append(newline()) - .append("From a URL: ").append(TextComponent.of("[Click Here]").clickEvent(ClickEvent.suggestCommand("/cfi image http://"))) - .append(newline()) - .append("From a file: ").append(TextComponent.of("[Click Here]").clickEvent(ClickEvent.suggestCommand("/cfi image file://"))) - .build(); - player.print(build); - } else { - if (settings.hasGenerator()) { - coloring(player); - } else { - heightmap(player, image, 1); - } - } - } - - @Command( - name = "populate", - desc = "" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void populate(Player player) { - CFISettings settings = assertSettings(player); - settings.popMessages(player); - settings.setCategory(this::populate); - TextComponent build = TextComponent.builder("What would you like to populate?") - .append(newline()) - .append("(You will need to type these commands)").append(newline()) - //TODO .cmdOptions("/cfi ", "", "Ores", "Ore", "Caves", "Schematics", "Smooth") - .append(newline()) - .append(TextComponent.of("< [Back]").clickEvent(ClickEvent.runCommand("/cfi"))) - .build(); - player.print(build); - } - - @Command( - name = "component", - aliases = {"components"}, - desc = "Components menu" - ) - @CommandPermissions("worldedit.anvil.cfi") - public void component(Player player) { - CFISettings settings = assertSettings(player); - settings.popMessages(player); - settings.setCategory(this::component); - - String mask; - if (settings.imageMask != null) { - mask = settings.imageMaskArg; - } else if (settings.mask != null) { - mask = settings.maskArg; - } else { - mask = "NONE"; - } - - String pattern = settings.pattern == null ? "NONE" : settings.patternArg; - - StringBuilder maskArgs = new StringBuilder(); - if (settings.imageMask != null) { - maskArgs.append(" ").append(settings.imageMaskArg); - } - if (settings.mask != null) { - maskArgs.append(" ").append(settings.maskArg); - } - if (!settings.whiteOnly) { - maskArgs.append(" -w"); - } - - String height = "/cfi height"; - String waterHeight = "/cfi waterheight"; - String snow = "/cfi snow"; - - //TODO - @NotNull Builder msg = TextComponent.builder(">> Current Settings <<").append(newline()) - .append("Mask ").append(TextComponent.of("[" + mask + "]") - .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi mask"))) - .clickEvent(ClickEvent.runCommand("/cfi mask"))) - .append(newline()) - .append("Pattern ").append(TextComponent.of("[" + pattern + "]") - .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi pattern"))) - .clickEvent(ClickEvent.runCommand("/cfi pattern"))) - .append(doubleNewLine) - .append(">> Components <<") - .append(newline()) - .append(TextComponent.of("[Height]") - .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi height 120"))) - .clickEvent(ClickEvent.suggestCommand("/cfi height 120"))).append(" - Terrain height for whole map") - .append(newline()) - .append(TextComponent.of("[WaterHeight]") - .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi waterheight 60"))) - .clickEvent(ClickEvent.suggestCommand("/cfi waterheight 60"))).append(" - Sea level for whole map") - .append(newline()) - .append(TextComponent.of("[FloorThickness]").hoverEvent(HoverEvent.showText(TextComponent.of("/cfi floorthickness 60"))) - .clickEvent(ClickEvent.suggestCommand("/cfi floorthickness 60"))).append(" - Floor thickness of entire map") - .append(newline()) - .append(TextComponent.of("[WorldThickness]").hoverEvent(HoverEvent.showText(TextComponent.of("/cfi worldthickness 60"))) - .clickEvent(ClickEvent.suggestCommand("/cfi worldthickness 60"))).append(" - World thickness of entire map") - .append(newline()) - .append(TextComponent.of("[Snow]").hoverEvent(HoverEvent.showText(TextComponent.of("/cfi snow" + maskArgs))) - .clickEvent(ClickEvent.suggestCommand("/cfi snow" + maskArgs))).append(" - Set snow in the masked areas") - .append(newline()); - - if (pattern != null) { - String disabled = "You must specify a pattern"; - msg.append(TextComponent.of("[WaterId]", TextColor.RED) - .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); - msg.append(newline()); - msg.append(TextComponent.of("[BedrockId]", TextColor.RED) - .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); - msg.append(doubleNewLine); - msg.append(TextComponent.of("[Floor]", TextColor.RED) - .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); - msg.append(doubleNewLine); - msg.append(TextComponent.of("[Main]", TextColor.RED) - .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); - msg.append(doubleNewLine); - msg.append(TextComponent.of("[Column]", TextColor.RED) - .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); - msg.append(doubleNewLine); - msg.append(TextComponent.of("[Overlay]", TextColor.RED) - .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); - msg.append(doubleNewLine); - } else { - StringBuilder compArgs = new StringBuilder(); - compArgs.append(" " + settings.patternArg + maskArgs); - - msg.append(TextComponent.of("[WaterId]") - .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi waterId " + pattern))) - .clickEvent(ClickEvent.runCommand("/cfi waterId " + pattern))); - msg.append(" - Water id for whole map"); - msg.append(newline()); - msg.append(TextComponent.of("[BedrockId]") - .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi baseId " + pattern))) - .clickEvent(ClickEvent.runCommand("/cfi baseId " + pattern))); - msg.append(TextComponent.of(" - Bedrock id for whole map")); - msg.append(newline()); - msg.append(TextComponent.of("[Floor]") - .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi floor " + compArgs))) - .clickEvent(ClickEvent.runCommand("/cfi floor " + compArgs))); - msg.append(TextComponent.of(" - Set the floor in the masked areas")); - msg.append(newline()); - msg.append(TextComponent.of("[Main]") - .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi main " + compArgs))) - .clickEvent(ClickEvent.runCommand("/cfi main " + compArgs))); - msg.append(TextComponent.of(" - Set the main block in the masked areas")); - msg.append(newline()); - msg.append(TextComponent.of("[Column]") - .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi column" + compArgs))) - .clickEvent(ClickEvent.runCommand("/cfi column" + compArgs))); - msg.append(" - Set the columns in the masked areas"); - msg.append(newline()); - msg.append(TextComponent.of("[Overlay]") - .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi overlay" + compArgs))) - .clickEvent(ClickEvent.runCommand("/cfi overlay" + compArgs))); - msg.append(" - Set the overlay in the masked areas"); - msg.append(newline()); - } - - msg.append(newline()) - .append(TextComponent.of("< [Back]").hoverEvent(HoverEvent.showText(TextComponent.of("/cfi"))).clickEvent(ClickEvent.runCommand("/cfi"))); - player.print(msg.build()); - } - - private static CFISettings assertSettings(Player player) { - CFISettings settings = getSettings(player); - if (!settings.hasGenerator()) { - throw new StopExecutionException(TextComponent.of("Please use /cfi")); - } - return settings; - } - - - protected static CFISettings getSettings(Player player) { - CFISettings settings = player.getMeta("CFISettings"); - if (settings == null) { - settings = new CFISettings(player); - } - return settings; - } - - public static class CFISettings { - private final Player player; - - private HeightMapMCAGenerator generator; - - protected ProvideBindings.ImageUri image; - protected String imageArg; - protected Mask mask; - protected ProvideBindings.ImageUri imageMask; - protected boolean whiteOnly = true; - protected String maskArg; - protected String imageMaskArg; - - protected Pattern pattern; - protected String patternArg; - - protected Consumer category; - - private boolean bound; - - public CFISettings(Player player) { - this.player = player; - } - - public boolean hasGenerator() { - return generator != null; - } - - public HeightMapMCAGenerator getGenerator() { - return generator; - } - - public void setMask(Mask mask, String arg) { - this.mask = mask; - this.maskArg = arg; - } - - public void setImage(ProvideBindings.ImageUri image, String arg) { - this.image = image; - } - - public void setImageMask(ProvideBindings.ImageUri imageMask, String arg) { - this.imageMask = imageMask; - this.imageMaskArg = arg; - } - - public void resetColoring() { - image = null; - imageArg = null; - mask = null; - imageMask = null; - whiteOnly = true; - maskArg = null; - imageMaskArg = null; - generator.setTextureUtil(Fawe.get().getTextureUtil()); - } - - public void resetComponent() { - mask = null; - imageMask = null; - whiteOnly = true; - maskArg = null; - imageMaskArg = null; - patternArg = null; - pattern = null; - } - - public Consumer getCategory() { - return category; - } - - public void setCategory(Consumer methodRef) { - this.category = category; - } - - public CFISettings setGenerator(HeightMapMCAGenerator generator) { - this.generator = generator; - if (bound) { - player.getSession().setVirtualWorld(generator); - } - return this; - } - - public CFISettings bind() { - if (generator != null) { - player.getSession().setVirtualWorld(generator); - } - bound = true; - player.setMeta("CFISettings", this); - return this; - } - - public void popMessages(Player player) { - ArrayDeque messages = player.deleteMeta("CFIBufferedMessages"); - if (messages != null) { - for (String message : messages) { - player.print(message); - } - } - } - - public CFISettings remove() { - player.deleteMeta("CFISettings"); - HeightMapMCAGenerator gen = this.generator; - if (gen != null) { - player.getSession().setVirtualWorld(null); - } - popMessages(player); - bound = false; - generator = null; - image = null; - imageArg = null; - mask = null; - imageMask = null; - whiteOnly = true; - maskArg = null; - imageMaskArg = null; - return this; - } - } - - @SuppressWarnings("unused") - protected static void mainMenu(Actor actor) { - TextComponentProducer producer = new TextComponentProducer(); - producer.append(TextComponent.of("What do you want to do now?")); - producer.newline(); - String prefix = "/cfi "; - String[] options = {"Coloring", "Component", "Populate", "Brush"}; - for (int i = 0; i < options.length; i++) { - if (i != 0) { - producer.append(TextComponent.of(" | ", TextColor.DARK_GRAY)); - } - String option = options[i]; - String cmd = prefix + option; - producer.append(TextComponent.of(option, TextColor.GREEN) - .clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, cmd)) - .hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of(option)))); - } - producer.newline(); - producer.newline(); - producer.append(TextComponent.of("<> [View]", TextColor.DARK_AQUA) - .clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, prefix + "download")) - .hoverEvent(HoverEvent - .of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("View full res image")))); - producer.newline(); - producer.append(TextComponent.of(">< [Cancel]", TextColor.RED) - .clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, prefix + "cancel")) - .hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("cancel")))); - producer.newline(); - producer.append(TextComponent.of(">> [Done]", TextColor.DARK_GREEN) - .clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, prefix + "done")) - .hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("done")))); - - actor.print(producer.create()); - } -} +// TODO: Ping @MattBDev to reimplement 2020-02-04 +// package com.boydti.fawe.command; +// +//import static com.boydti.fawe.util.image.ImageUtil.load; +//import static com.sk89q.worldedit.command.MethodCommands.getArguments; +//import static com.sk89q.worldedit.util.formatting.text.TextComponent.newline; +// +//import com.boydti.fawe.Fawe; +//import com.boydti.fawe.FaweAPI; +//import com.boydti.fawe.beta.implementation.filter.block.SingleFilterBlock; +//import com.boydti.fawe.config.Caption; +//import com.boydti.fawe.object.RunnableVal; +//import com.boydti.fawe.object.brush.visualization.cfi.HeightMapMCAGenerator; +//import com.boydti.fawe.object.clipboard.MultiClipboardHolder; +//import com.boydti.fawe.util.CleanTextureUtil; +//import com.boydti.fawe.util.FilteredTextureUtil; +//import com.boydti.fawe.util.ImgurUtility; +//import com.boydti.fawe.util.MathMan; +//import com.boydti.fawe.util.StringMan; +//import com.boydti.fawe.util.TaskManager; +//import com.boydti.fawe.util.TextureUtil; +//import com.boydti.fawe.util.image.ImageUtil; +//import com.google.gson.Gson; +//import com.google.gson.JsonObject; +//import com.sk89q.minecraft.util.commands.CommandException; +//import com.sk89q.worldedit.EmptyClipboardException; +//import com.sk89q.worldedit.LocalSession; +//import com.sk89q.worldedit.WorldEdit; +//import com.sk89q.worldedit.WorldEditException; +//import com.sk89q.worldedit.command.util.CommandPermissions; +//import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; +//import com.sk89q.worldedit.entity.Player; +//import com.sk89q.worldedit.extension.input.InputParseException; +//import com.sk89q.worldedit.extension.input.ParserContext; +//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.binding.ProvideBindings; +//import com.sk89q.worldedit.extent.clipboard.Clipboard; +//import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; +//import com.sk89q.worldedit.function.mask.Mask; +//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; +//import com.sk89q.worldedit.util.Location; +//import com.sk89q.worldedit.util.formatting.component.TextComponentProducer; +//import com.sk89q.worldedit.util.formatting.text.TextComponent; +//import com.sk89q.worldedit.util.formatting.text.TextComponent.Builder; +//import com.sk89q.worldedit.util.formatting.text.event.ClickEvent; +//import com.sk89q.worldedit.util.formatting.text.event.HoverEvent; +//import com.sk89q.worldedit.util.formatting.text.format.TextColor; +//import com.sk89q.worldedit.world.World; +//import com.sk89q.worldedit.world.biome.BiomeType; +//import com.sk89q.worldedit.world.block.BlockStateHolder; +//import com.sk89q.worldedit.world.block.BlockType; +//import com.sk89q.worldedit.world.block.BlockTypes; +//import java.awt.image.BufferedImage; +//import java.awt.image.DataBufferInt; +//import java.io.ByteArrayOutputStream; +//import java.io.File; +//import java.io.FileNotFoundException; +//import java.io.IOException; +//import java.net.URL; +//import java.nio.file.Path; +//import java.text.DateFormat; +//import java.text.SimpleDateFormat; +//import java.util.ArrayDeque; +//import java.util.Date; +//import java.util.HashSet; +//import java.util.List; +//import java.util.Set; +//import java.util.function.Consumer; +//import java.util.function.Function; +//import java.util.stream.IntStream; +//import javax.imageio.ImageIO; +//import org.enginehub.piston.annotation.Command; +//import org.enginehub.piston.annotation.CommandContainer; +//import org.enginehub.piston.annotation.param.Arg; +//import org.enginehub.piston.annotation.param.Switch; +//import org.enginehub.piston.exception.StopExecutionException; +//import org.enginehub.piston.inject.InjectedValueAccess; +//import org.jetbrains.annotations.NotNull; +// +//@CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class) +//public class CFICommands { +// +// private final WorldEdit worldEdit; +// private final TextComponent doubleNewLine = TextComponent.of("\n\n"); +// +// /** +// * Create a new instance. +// * +// * @param worldEdit reference to WorldEdit +// */ +// public CFICommands(WorldEdit worldEdit) { +// this.worldEdit = worldEdit; +// } +// +// public static File getFolder(String worldName) { +// Platform platform = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING); +// List worlds = platform.getWorlds(); +// Path path = worlds.get(0).getStoragePath(); +// return new File(path.toFile().getParentFile().getParentFile(), worldName + File.separator + "region"); +// } +// +// @Command( +// name = "heightmap", +// desc = "Start CFI with a height map as a base" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void heightmap(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "double", def = "1") double yscale) { +// if (yscale != 0) { +// int[] raw = ((DataBufferInt) image.load().getRaster().getDataBuffer()).getData(); +// int[] table = IntStream.range(0, 256).map(i -> Math.min(255, (int) (i * yscale))) +// .toArray(); +// for (int i = 0; i < raw.length; i++) { +// int color = raw[i]; +// int red = table[(color >> 16) & 0xFF]; +// int green = table[(color >> 8) & 0xFF]; +// int blue = table[(color >> 0) & 0xFF]; +// raw[i] = (red << 16) + (green << 8) + (blue << 0); +// } +// } +// HeightMapMCAGenerator generator = new HeightMapMCAGenerator(image.load(), getFolder(generateName())); +// setup(generator, player); +// } +// +// @Command( +// name = "empty", +// desc = "Start CFI with an empty map as a base" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void empty(Player player, @Arg(desc = "Map width (x)") int width, @Arg(desc = "Map length (z)") int length) { +// HeightMapMCAGenerator generator = new HeightMapMCAGenerator(width, length, getFolder(generateName())); +// setup(generator, player); +// } +// +// private String generateName() { +// DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH.mm.ss"); +// return df.format(new Date()); +// } +// +// private void setup(HeightMapMCAGenerator generator, Player player) { +// CFISettings settings = getSettings(player).remove(); +// generator.setPacketViewer(player); +// settings.setGenerator(generator).bind(); +// generator.setImageViewer(Fawe.imp().getImageViewer(player)); +// generator.update(); +// mainMenu(player); +// } +// +// @Command( +// name = "brush", +// desc = "Info about using brushes with CFI" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void brush(Player player) { +// CFISettings settings = assertSettings(player); +// settings.popMessages(player); +// @NotNull Builder msg; +// if (settings.getGenerator().getImageViewer() != null) { +// msg = TextComponent.builder("CFI supports using brushes during creation").append(newline()) +// .append(" - Place the map on a wall of item frames").append(newline()) +// .append(" - Use any WorldEdit brush on the item frames").append(newline()) +// .append(" - Example: ").append(TextComponent.of("Video").clickEvent(ClickEvent.openUrl("https://goo.gl/PK4DMG"))).append(newline()); +// } else { +// msg = TextComponent.builder("This is not supported with your platform/version").append(newline()); +// } +// //TODO msg.text("< [Back]").cmdTip(alias()).send(player); +// player.print(msg.build()); +// } +// +// @Command( +// name = "cancel", +// aliases = {"exit"}, +// desc = "Cancel creation" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void cancel(Player player) { +// getSettings(player).remove(); +// player.print("Cancelled!"); +// } +// +// @Command( +// name = "done", +// aliases = "create", +// desc = "Create the world" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void done(Player player) { +// CFISettings settings = assertSettings(player); +// HeightMapMCAGenerator generator = settings.getGenerator(); +// +// Function function = folder -> { +// if (folder != null) { +// try { +// generator.setFolder(folder); +// player.print("Generating " + folder); +// generator.generate(); +// generator.setPacketViewer(null); +// generator.setImageViewer(null); +// settings.remove(); +// player.print("Done!"); +// return true; +// } catch (IOException e) { +// throw new RuntimeException(e); +// } +// } else { +// player.print("Unable to generate world... (see console)?"); +// } +// return false; +// }; +// +// try { +// new PlotLoader().load(player, settings, function); +// } catch (Throwable e) { +// e.printStackTrace(); +// function.apply(generator.getFolder().getParentFile()); +// } +// +// File folder = generator.getFolder(); +// if (folder != null) { +// World world = FaweAPI.getWorld(folder.getName()); +// if (world != null) { +// if (player.getWorld() != world) { +// TaskManager.IMP.sync(new RunnableVal() { +// @Override +// public void run(Object value) { +// Location spawn = new Location(world, world.getSpawnPosition().toVector3()); +// player.setPosition(spawn); +// } +// }); +// } +// } else { +// player.print("Unable to import world (" + folder.getName() + ") please do so manually"); +// } +// } +// } +// +// @Command( +// name = "column", +// desc = "Set the floor and main block" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void column(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); +// if (image != null) { +// gen.setColumn(load(image), pattern, !disableWhiteOnly); +// } else if (mask != null) { +// gen.setColumn(mask, pattern); +// } else { +// gen.setColumn(pattern); +// } +// player.print("Set column!"); +// assertSettings(player).resetComponent(); +// component(player); +// } +// +// @Command( +// name = "floor", +// desc = "Set the floor (default: grass)" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void floorCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// floor(player, pattern, image, mask, disableWhiteOnly); +// player.print("Set floor!"); +// assertSettings(player).resetComponent(); +// component(player); +// } +// +// private void floor(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) { +// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); +// if (image != null) { +// gen.setFloor(load(image), pattern, !disableWhiteOnly); +// } else if (mask != null) { +// gen.setFloor(mask, pattern); +// } else { +// gen.setFloor(pattern); +// } +// } +// +// @Command( +// name = "main", +// desc = "Set the main block (default: stone)" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void mainCmd(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// main(player, pattern, image, maskOpt, disableWhiteOnly); +// player.print("Set main!"); +// assertSettings(player).resetComponent(); +// component(player); +// } +// +// public void main(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask maskOpt, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); +// if (image != null) { +// gen.setMain(load(image), pattern, !disableWhiteOnly); +// } else if (maskOpt != null) { +// gen.setMain(maskOpt, pattern); +// } else { +// gen.setMain(pattern); +// } +// } +// +// @Command( +// name = "overlay", +// aliases = {"setoverlay"}, +// desc = "Set the overlay block", +// descFooter = "Change the block directly above the floor (default: air)\n" + +// "e.g., Tallgrass" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void overlay(Player player, @Arg(desc = "Pattern") Pattern pattern, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); +// if (image != null) { +// gen.setOverlay(load(image), pattern, !disableWhiteOnly); +// } else if (mask != null) { +// gen.setOverlay(mask, pattern); +// } else { +// gen.setOverlay(pattern); +// } +// player.print("Set overlay!"); +// component(player); +// } +// +// @Command( +// name = "smooth", +// desc = "Smooth the terrain", +// descFooter = "Smooth terrain within an image-mask, or worldedit mask\n" + +// " - You can use !0 as the mask to smooth everything\n" + +// " - This supports smoothing snow layers (set the floor to 78:7)\n" + +// " - A good value for radius and iterations would be 1 8." +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void smoothCmd(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// smooth(player, radius, iterations, image, mask, disableWhiteOnly); +// assertSettings(player).resetComponent(); +// component(player); +// } +// +// private void smooth(Player player, int radius, int iterations, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); +// if (image != null) { +// gen.smooth(load(image), !disableWhiteOnly, radius, iterations); +// } else { +// gen.smooth(mask, radius, iterations); +// } +// } +// +// @Command( +// name = "snow", +// desc = "Create some snow" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void snow(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); +// floor(player, BlockTypes.SNOW.getDefaultState().with(PropertyKey.LAYERS, 7), image, mask, disableWhiteOnly); +// main(player, BlockTypes.SNOW_BLOCK, image, mask, disableWhiteOnly); +// smooth(player, 1, 8, image, mask, disableWhiteOnly); +// player.print(TextComponent.of("Added snow!")); +// assertSettings(player).resetComponent(); +// component(player); +// } +// +// @Command( +// name = "biomepriority", +// desc = "Set the biome priority", +// descFooter = "Increase or decrease biome priority when using blockBiomeColor.\n" + +// "A value of 50 is the default\n" + +// "Above 50 will prefer to color with biomes\n" + +// "Below 50 will prefer to color with blocks" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void biomepriority(Player player, int value) { +// assertSettings(player).getGenerator().setBiomePriority(value); +// coloring(player); +// } +// +// @Command( +// name = "paletteblocks", +// desc = "Set the blocks used for coloring", +// descFooter = "Allow only specific blocks to be used for coloring\n" + +// "`blocks` is a list of blocks e.g., stone,bedrock,wool\n" + +// "`#clipboard` will only use the blocks present in your clipboard." +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void paletteblocks(Player player, LocalSession session, @Arg(name = "arg", desc = "String", def = "") String argOpt) throws EmptyClipboardException, InputParseException, FileNotFoundException { +// if (argOpt == null) { +// TextComponent build = TextComponent.builder("What blocks do you want to color with?") +// .append(newline()) +// .append(TextComponent.of("[All]") +// .clickEvent(ClickEvent.runCommand("/cfi PaletteBlocks *"))) +// .append(" - All available blocks") +// .append(newline()) +// .append(TextComponent.of("[Clipboard]") +// .clickEvent(ClickEvent.runCommand("/cfi PaletteBlocks #clipboard"))) +// .append(" - The blocks in your clipboard") +// .append(newline()) +// .append(TextComponent.of("[List]") +// .clickEvent(ClickEvent.runCommand("/cfi PaletteBlocks stone,gravel"))) +// .append(" - A comma separated list of blocks") +// .append(newline()) +// .append(TextComponent.of("[Complexity]") +// .clickEvent(ClickEvent.runCommand("/cfi Complexity"))) +// .append(" - Block textures within a complexity range") +// .append(newline()) +// .append(TextComponent.of("< [Back]").clickEvent(ClickEvent +// .runCommand("/cfi coloring"))) +// .build(); +// player.print(build); +// return; +// } +// HeightMapMCAGenerator generator = assertSettings(player).getGenerator(); +// ParserContext context = new ParserContext(); +// context.setActor(player); +// context.setWorld(player.getWorld()); +// context.setSession(player.getSession()); +// context.setExtent(generator); +// Request.request().setExtent(generator); +// +// Set blocks; +// switch (argOpt.toLowerCase()) { +// case "true": +// case "*": { +// generator.setTextureUtil(Fawe.get().getTextureUtil()); +// return; +// } +// case "#clipboard": { +// ClipboardHolder holder = player.getSession().getClipboard(); +// Clipboard clipboard = holder.getClipboard(); +// boolean[] ids = new boolean[BlockTypes.size()]; +// for (BlockVector3 pt : clipboard.getRegion()) { +// ids[clipboard.getBlock(pt).getBlockType().getInternalId()] = true; +// } +// blocks = new HashSet<>(); +// for (int combined = 0; combined < ids.length; combined++) { +// if (ids[combined]) { +// blocks.add(BlockTypes.get(combined)); +// } +// } +// break; +// } +// default: { +// blocks = new HashSet<>(); +// SingleFilterBlock extent = new SingleFilterBlock(); +// ParserContext parserContext = new ParserContext(); +// parserContext.setActor(player); +// parserContext.setWorld(player.getWorld()); +// parserContext.setSession(session); +// parserContext.setExtent(extent); +// Request.request().setExtent(extent); +// Mask mask = worldEdit.getMaskFactory().parseFromInput(argOpt, parserContext); +// TextureUtil tu = Fawe.get().getTextureUtil(); +// for (int typeId : tu.getValidBlockIds()) { +// BlockType type = BlockTypes.get(typeId); +// extent.init(0, 0, 0, type.getDefaultState().toBaseBlock()); +// if (mask.test(extent, extent)) { +// blocks.add(type); +// } +// } +// break; +// } +// } +// generator.setTextureUtil(new FilteredTextureUtil(Fawe.get().getTextureUtil(), blocks)); +// coloring(player); +// } +// +// @Command( +// name = "randomization", +// desc = "Set whether randomization is enabled", +// descFooter = "This is enabled by default, randomization will add some random variation in the blocks used to closer match the provided image.\n" + +// "If disabled, the closest block to the color will always be used.\n" + +// "Randomization will allow mixing biomes when coloring with biomes" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void randomization(Player player, boolean enabled) { +// assertSettings(player).getGenerator().setTextureRandomVariation(enabled); +// coloring(player); +// } +// +// @Command( +// name = "complexity", +// desc = "Set the complexity for coloring", +// descFooter = "Set the complexity for coloring\n" + +// "Filter out blocks to use based on their complexity, which is a measurement of how much color variation there is in the texture for that block.\n" + +// "Glazed terracotta is complex, and not very pleasant for terrain, whereas stone and wool are simpler textures.\n" + +// "Using 0 73 for the min/max would use the simplest 73% of blocks for coloring, and is a reasonable value." +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void complexity(Player player, int min, int max) throws FileNotFoundException { +// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); +// if (min == 0 && max == 100) { +// gen.setTextureUtil(Fawe.get().getTextureUtil()); +// } else { +// gen.setTextureUtil(new CleanTextureUtil(Fawe.get().getTextureUtil(), min, max)); +// } +// coloring(player); +// } +// +// @Command( +// name = "schem", +// desc = "Populate schematics", +// descFooter = "Populate a schematic on the terrain\n" + +// " - Change the mask (e.g. angle mask) to only place the schematic in specific locations.\n" + +// " - The rarity is a value between 0 and 100.\n" + +// " - The distance is the spacing between each schematic" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void schem(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask") Mask mask, String schematic, int rarity, int distance, boolean rotate)throws IOException, WorldEditException { +// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); +// +// World world = player.getWorld(); +// MultiClipboardHolder multi = ClipboardFormats.loadAllFromInput(player, schematic, null, true); +// if (multi == null) { +// return; +// } +// if (imageMask == null) { +// gen.addSchems(mask, multi.getHolders(), rarity, distance, rotate); +// } else { +// gen.addSchems(load(imageMask), mask, multi.getHolders(), rarity, distance, rotate); +// } +// player.print(TextComponent.of("Added schematics!")); +// populate(player); +// } +// +// @Command( +// name = "biome", +// desc = "Set the biome", +// descFooter = "Set the biome in specific parts of the map.\n" + +// " - If an image is used, the biome will have a chance to be set based on how white the pixel is (white #FFF = 100% chance)" + +// " - The whiteOnly parameter determines if only white values on the image are set" + +// " - If a mask is used, the biome will be set anywhere the mask applies" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void biome(Player player, @Arg(desc = "Biome type") BiomeType biome, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly){ +// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); +// if (image != null) { +// gen.setBiome(load(image), biome, !disableWhiteOnly); +// } else if (mask != null) { +// gen.setBiome(mask, biome); +// } else { +// gen.setBiome(biome); +// } +// player.print(TextComponent.of("Set biome!")); +// assertSettings(player).resetComponent(); +// component(player); +// } +// +// @Command( +// name = "caves", +// desc = "Generate vanilla caves" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void caves(Player player) throws WorldEditException { +// assertSettings(player).getGenerator().addCaves(); +// player.print(TextComponent.of("Added caves!")); +// populate(player); +// } +// +// @Command( +// name = "ore", +// desc = "Add an ore", +// descFooter = "Use a specific pattern and settings to generate ore" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void ore(Player player, @Arg(desc = "Mask") Mask mask, @Arg(desc = "Pattern") Pattern pattern, int size, int frequency, int rarity, int minY, int maxY) throws WorldEditException { +// assertSettings(player).getGenerator().addOre(mask, pattern, size, frequency, rarity, minY, maxY); +// player.print(TextComponent.of("Added ore!")); +// populate(player); +// } +// +// @Command( +// name = "ores", +// desc = "Generate the vanilla ores" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void ores(Player player, @Arg(desc = "Mask") Mask mask) throws WorldEditException { +// assertSettings(player).getGenerator().addDefaultOres(mask); +// player.print(TextComponent.of("Added ores!")); +// populate(player); +// } +// +// @Command( +// name = "height", +// desc = "Set the height", +// descFooter = "Set the terrain height either based on an image heightmap, or a numeric value." +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void height(Player player, @Arg(name = "height", desc = "Int height, or image") String imageStr) throws WorldEditException { +// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); +// if (!MathMan.isInteger(imageStr)) { +// gen.setHeight(ImageUtil.getImage(imageStr)); +// } else { +// gen.setHeights(Integer.parseInt(imageStr)); +// } +// player.print("Set Height!"); +// component(player); +// } +// +// @Command( +// name = "water", +// desc = "Change the block used for water\n e.g., Lava" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void waterId(Player player, @Arg(desc = "block") BlockStateHolder block) throws WorldEditException { +// CFISettings settings = assertSettings(player); +// settings.getGenerator().setWater(block.toImmutableState()); +// +// player.print("Set water id!"); +// settings.resetComponent(); +// component(player); +// } +// +// @Command( +// name = "baseid", +// aliases = {"bedrockid"}, +// desc = "Change the block used for the base\ne.g. Bedrock" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void baseId(Player player, @Arg(desc = "block") BlockStateHolder block) throws WorldEditException { +// CFISettings settings = assertSettings(player); +// settings.getGenerator().setBedrock(block.toImmutableState()); +// player.print(TextComponent.of("Set base id!")); +// settings.resetComponent(); +// component(player); +// } +// +// @Command( +// name = "worldthickness", +// aliases = {"width", "thickness"}, +// desc = "Set the thickness of the generated world\n" + +// " - A value of 0 is the default and will not modify the height" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void worldthickness(Player player, @Arg(desc = "brush height") int height) throws WorldEditException { +// assertSettings(player).getGenerator().setWorldThickness(height); +// player.print("Set world thickness!"); +// component(player); +// } +// +// @Command( +// name = "floorthickness", +// aliases = {"floorheight", "floorwidth"}, +// desc = "Set the thickness of the top layer\n" + +// " - A value of 0 is the default and will only set the top block" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void floorthickness(Player player, @Arg( desc = "brush height") int height) throws WorldEditException { +// assertSettings(player).getGenerator().setFloorThickness(height); +// player.print("Set floor thickness!"); +// component(player); +// } +// +// @Command( +// name = "update", +// aliases = {"refresh", "resend"}, +// desc = "Resend the CFI chunks" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void update(Player player) throws WorldEditException { +// assertSettings(player).getGenerator().update(); +// player.print("Chunks refreshed!"); +// mainMenu(player); +// } +// +// @Command( +// name = "tp", +// aliases = {"visit", "home"}, +// desc = "Teleport to the CFI virtual world" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void tp(Player player) throws WorldEditException { +// HeightMapMCAGenerator gen = assertSettings(player).getGenerator(); +// player.print("Teleporting..."); +// Vector3 origin = gen.getOrigin(); +// player.setPosition(origin.subtract(16, 0, 16)); +// player.findFreePosition(); +// mainMenu(player); +// } +// +// @Command( +// name = "waterheight", +// aliases = {"sealevel", "setwaterheight"}, +// desc = "Set the level water is generated at\n" + +// "Set the level water is generated at\n" + +// " - By default water is disabled (with a value of 0)" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void waterheight(Player player, @Arg(desc = "brush height") int height) throws WorldEditException { +// assertSettings(player).getGenerator().setWaterHeight(height); +// player.print("Set water height!"); +// component(player); +// } +// +// @Command( +// name = "glass", +// aliases = {"glasscolor", "setglasscolor"}, +// desc = "Color terrain using glass" +// ) +// // ![79,174,212,5:3,5:4,18,161,20] +// @CommandPermissions("worldedit.anvil.cfi") +// public void glass(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException { +// CFISettings settings = assertSettings(player); +// settings.getGenerator().setColorWithGlass(load(image)); +// player.print("Set color with glass!"); +// settings.resetColoring(); +// mainMenu(player); +// } +// +// @Command( +// name = "color", +// aliases = {"setcolor", "blockcolor", "blocks"}, +// desc = "Set the color with blocks and biomes", +// descFooter = "Color the terrain using only blocks\n" + +// "Provide an image, or worldedit mask for the 2nd argument to restrict what areas are colored\n" + +// "The -w (disableWhiteOnly) will randomly apply depending on the pixel luminance" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void color(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException { +// CFISettings settings = assertSettings(player); +// HeightMapMCAGenerator gen = settings.getGenerator(); +// if (imageMask != null) { +// gen.setColor(load(image), load(imageMask), !disableWhiteOnly); +// } else if (mask != null) { +// gen.setColor(load(image), mask); +// } else { +// gen.setColor(load(image)); +// } +// settings.resetColoring(); +// player.print("Set color with blocks!"); +// mainMenu(player); +// } +// +// @Command( +// name = "blockbiomecolor", +// aliases = {"setblockandbiomecolor", "blockandbiome"}, +// desc = "Set the color with blocks and biomes", +// descFooter = "Color the terrain using blocks and biomes.\n" + +// "Provide an image, or worldedit mask to restrict what areas are colored\n" + +// "The -w (disableWhiteOnly) will randomly apply depending on the pixel luminance" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void blockbiome(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException { +// CFISettings settings = assertSettings(player); +// settings.getGenerator().setBlockAndBiomeColor(load(image), mask, load(imageMask), !disableWhiteOnly); +// player.print(TextComponent.of("Set color with blocks and biomes!")); +// settings.resetColoring(); +// mainMenu(player); +// } +// +// @Command( +// name = "biomecolor", +// aliases = {"setbiomecolor", "biomes"}, +// desc = "Color the terrain using biomes.\n" + +// "Note: Biome coloring does not change blocks:\n" + +// " - If you changed the block to something other than grass you will not see anything." +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void biomecolor(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri image, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly) throws WorldEditException { +// CFISettings settings = assertSettings(player); +// settings.getGenerator().setBiomeColor(load(image)); +// player.print(TextComponent.of("Set color with biomes!")); +// settings.resetColoring(); +// mainMenu(player); +// } +// +// +// @Command( +// name = "coloring", +// aliases = {"palette"}, +// desc = "Color the world using an image" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void coloring(Player player) { +// CFISettings settings = assertSettings(player); +// settings.popMessages(player); +// settings.setCategory(this::coloring); +// HeightMapMCAGenerator gen = settings.getGenerator(); +// boolean rand = gen.getTextureRandomVariation(); +// String mask; +// if (settings.imageMask != null) { +// mask = settings.imageMaskArg; +// } else if (settings.mask != null) { +// mask = settings.maskArg; +// } else { +// mask = "NONE"; +// } +// TextureUtil tu = gen.getRawTextureUtil(); +// String blocks; +// if (tu.getClass() == TextureUtil.class) { +// blocks = "All"; +// } else if (tu.getClass() == CleanTextureUtil.class) { +// CleanTextureUtil clean = (CleanTextureUtil) tu; +// blocks = "Complexity(" + clean.getMin() + "," + clean.getMax() + ")"; +// } else if (tu.getClass() == FilteredTextureUtil.class) { +// blocks = "Selected"; +// } else { +// blocks = "Undefined"; +// } +// +// Set materials = new HashSet<>(); +// int[] blockArray = tu.getValidBlockIds(); +// for (int typeId : blockArray) { +// BlockType type = BlockTypes.get(typeId); +// String name = type.getName(); +// if (name.contains(":")) { +// name = name.split(":")[1]; +// } +// materials.add(name); +// } +// String blockList = materials.size() > 100 ? materials.size() + " blocks" : StringMan.join(materials, ','); +// +// int biomePriority = gen.getBiomePriority(); +// TextComponent.empty().clickEvent(ClickEvent.runCommand( +// "/cfi randomization " + !rand)).hoverEvent(HoverEvent.showText( +// TextComponent.of("/cfi randomization " + !rand))); +// @NotNull Builder builder = TextComponent.builder(">> Current Settings <<"); +// builder.append(newline()); +// builder.append(TextComponent.of("Randomization [" + Boolean.toString(rand).toUpperCase() + "]") +// .clickEvent(ClickEvent.runCommand( +// "/cfi randomization " + !rand)).hoverEvent(HoverEvent.showText( +// TextComponent.of("/cfi randomization " + !rand)))); +// builder.append(newline()); +// builder.append(TextComponent.of("Mask [" + mask + "]").clickEvent(ClickEvent.runCommand( +// "/cfi mask")).hoverEvent(HoverEvent.showText( +// TextComponent.of("/cfi mask")))); +// builder.append(newline()); +// builder.append(TextComponent.of("Blocks [" + blocks + "]").clickEvent(ClickEvent.runCommand( +// "/cfi mask")).hoverEvent(HoverEvent.showText( +// TextComponent.of("/cfi mask")))); +// builder.append(newline()); +// builder.append(TextComponent.of("Biome Priority [" + biomePriority + "]").clickEvent(ClickEvent.runCommand( +// "/cfi mask")).hoverEvent(HoverEvent.showText( +// TextComponent.of("/cfi biomepriority")))); +// builder.append(newline()); +// +// if (settings.image != null) { +// StringBuilder colorArgs = new StringBuilder(" " + settings.imageArg); +// if (settings.imageMask != null) { +// colorArgs.append(" ").append(settings.imageMaskArg); +// } +// if (settings.mask != null) { +// colorArgs.append(" ").append(settings.maskArg); +// } +// if (!settings.whiteOnly) { +// colorArgs.append(" -w"); +// } +// +// //TODO +// builder.append("Image: ") +// .append("[" + settings.imageArg + "]")//.cmdTip("/cfi " + Commands.getAlias(CFICommands.class, "image")) +// .append(newline()).append(newline()) +// .append("Let's Color: ") +// //.cmdOptions("/cfi ", colorArgs.toString(), "Biomes", "Blocks", "BlockAndBiome", "Glass") +// .append(newline()); +// } else { +// builder.append(newline()).append("You can color a world using an image like ") +// .append(TextComponent.of("[This]").clickEvent(ClickEvent.openUrl("http://i.imgur.com/vJYinIU.jpg"))).append(newline()) +// .append("You MUST provide an image: ") +// .append("[None]");//.cmdTip("/cfi " + Commands.getAlias(Command.class, "image")).append(newline()); +// } +// builder.append("< [Back]");//.cmdTip(alias()).send(player); +// player.print(builder.build()); +// } +// +// @Command( +// name = "mask", +// desc = "Select a mask" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void mask(Player player, @Arg(def = "", desc = "image url or filename") ProvideBindings.ImageUri imageMask, @Arg(desc = "Mask", def = "") Mask mask, @Switch(name = 'w', desc = "TODO") boolean disableWhiteOnly, InjectedValueAccess context){ +// CFISettings settings = assertSettings(player); +// String[] split = getArguments(context).split(" "); +// int index = 2; +// settings.imageMask = imageMask; +// settings.imageMaskArg = imageMask != null ? split[index++] : null; +// settings.mask = mask; +// settings.maskArg = mask != null ? split[index++] : null; +// settings.whiteOnly = !disableWhiteOnly; +// +// String s = "/cfi mask http://"; +// String s1 = "/cfi mask "; +// String s2 = "/cfi " + settings.getCategory(); +// TextComponent build = TextComponent.builder(">> Current Settings <<") +// .append(newline()) +// .append("Image Mask ").append( +// TextComponent.of("[" + settings.imageMaskArg + "]") +// .hoverEvent(HoverEvent.showText(TextComponent.of(s))) +// .clickEvent(ClickEvent.suggestCommand("/cfi mask http://"))) +// .append(newline()) +// .append("WorldEdit Mask ").append(TextComponent.of("[" + settings.maskArg + "]") +// .hoverEvent(HoverEvent.showText(TextComponent.of(s1))) +// .clickEvent(ClickEvent.suggestCommand(s1))) +// .append(newline()) +// .append( +// TextComponent.of("< [Back]").hoverEvent(HoverEvent.showText(TextComponent.of(s2))) +// .clickEvent(ClickEvent.runCommand(s2))).build(); +// player.print(build); +// } +// +// @Command( +// name = "pattern", +// desc = "Select a pattern" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void pattern(Player player, @Arg(desc = "Pattern", def = "") Pattern pattern, InjectedValueAccess context)throws CommandException { +// CFISettings settings = assertSettings(player); +// String[] split = getArguments(context).split(" "); +// int index = 2; +// settings.pattern = pattern; +// settings.patternArg = pattern == null ? null : split[index++]; +// +// StringBuilder cmd = new StringBuilder("/cfi pattern "); +// +// if (pattern != null) { +// settings.getCategory().accept(player); +// } else { +// String s = cmd + " stone"; +// String s1 = "/cfi " + settings.getCategory(); +// TextComponent build = TextComponent.builder(">> Current Settings <<").append(newline()) +// .append("Pattern ").append(TextComponent.of("[Click Here]") +// .hoverEvent(HoverEvent.showText(TextComponent.of(s))) +// .clickEvent(ClickEvent.suggestCommand(s))) +// .append(newline()) +// .append(TextComponent.of("< [Back]") +// .hoverEvent(HoverEvent.showText(TextComponent.of(s1))) +// .clickEvent(ClickEvent.runCommand(s1))).build(); +// player.print(build); +// } +// } +// +// @Command( +// name = "download", +// desc = "Download the current image" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void download(Player player)throws IOException { +// CFISettings settings = assertSettings(player); +// BufferedImage image = settings.getGenerator().draw(); +// ByteArrayOutputStream baos = new ByteArrayOutputStream(); +// ImageIO.write(image, "jpg", baos); +// byte[] data = baos.toByteArray(); +// player.print("Please wait..."); +// String json = ImgurUtility.getImgurContent(ImgurUtility.CLIENT_ID, data); +// Gson gson = new Gson(); +// JsonObject obj = gson.fromJson(json, JsonObject.class); +// JsonObject data1 = obj.get("data").getAsJsonObject(); +// String link = data1.get("link").getAsString(); +// URL url = new URL(link); +// player.print(Caption.of("fawe.web.download.link" , url)); +// } +// +// @Command( +// name = "image", +// desc = "Select an image" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void image(Player player, @Arg(desc = "image url or filename", def = "") ProvideBindings.ImageUri image, InjectedValueAccess context)throws CommandException { +// CFISettings settings = getSettings(player); +// String[] split = getArguments(context).split(" "); +// int index = 2; +// +// settings.image = image; +// settings.imageArg = image != null ? split[index++] : null; +// +// if (image == null) { +// TextComponent build = TextComponent.builder("Please provide an image:") +// .append(newline()) +// .append("From a URL: ").append(TextComponent.of("[Click Here]").clickEvent(ClickEvent.suggestCommand("/cfi image http://"))) +// .append(newline()) +// .append("From a file: ").append(TextComponent.of("[Click Here]").clickEvent(ClickEvent.suggestCommand("/cfi image file://"))) +// .build(); +// player.print(build); +// } else { +// if (settings.hasGenerator()) { +// coloring(player); +// } else { +// heightmap(player, image, 1); +// } +// } +// } +// +// @Command( +// name = "populate", +// desc = "" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void populate(Player player) { +// CFISettings settings = assertSettings(player); +// settings.popMessages(player); +// settings.setCategory(this::populate); +// TextComponent build = TextComponent.builder("What would you like to populate?") +// .append(newline()) +// .append("(You will need to type these commands)").append(newline()) +// //TODO .cmdOptions("/cfi ", "", "Ores", "Ore", "Caves", "Schematics", "Smooth") +// .append(newline()) +// .append(TextComponent.of("< [Back]").clickEvent(ClickEvent.runCommand("/cfi"))) +// .build(); +// player.print(build); +// } +// +// @Command( +// name = "component", +// aliases = {"components"}, +// desc = "Components menu" +// ) +// @CommandPermissions("worldedit.anvil.cfi") +// public void component(Player player) { +// CFISettings settings = assertSettings(player); +// settings.popMessages(player); +// settings.setCategory(this::component); +// +// String mask; +// if (settings.imageMask != null) { +// mask = settings.imageMaskArg; +// } else if (settings.mask != null) { +// mask = settings.maskArg; +// } else { +// mask = "NONE"; +// } +// +// String pattern = settings.pattern == null ? "NONE" : settings.patternArg; +// +// StringBuilder maskArgs = new StringBuilder(); +// if (settings.imageMask != null) { +// maskArgs.append(" ").append(settings.imageMaskArg); +// } +// if (settings.mask != null) { +// maskArgs.append(" ").append(settings.maskArg); +// } +// if (!settings.whiteOnly) { +// maskArgs.append(" -w"); +// } +// +// String height = "/cfi height"; +// String waterHeight = "/cfi waterheight"; +// String snow = "/cfi snow"; +// +// //TODO +// @NotNull Builder msg = TextComponent.builder(">> Current Settings <<").append(newline()) +// .append("Mask ").append(TextComponent.of("[" + mask + "]") +// .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi mask"))) +// .clickEvent(ClickEvent.runCommand("/cfi mask"))) +// .append(newline()) +// .append("Pattern ").append(TextComponent.of("[" + pattern + "]") +// .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi pattern"))) +// .clickEvent(ClickEvent.runCommand("/cfi pattern"))) +// .append(doubleNewLine) +// .append(">> Components <<") +// .append(newline()) +// .append(TextComponent.of("[Height]") +// .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi height 120"))) +// .clickEvent(ClickEvent.suggestCommand("/cfi height 120"))).append(" - Terrain height for whole map") +// .append(newline()) +// .append(TextComponent.of("[WaterHeight]") +// .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi waterheight 60"))) +// .clickEvent(ClickEvent.suggestCommand("/cfi waterheight 60"))).append(" - Sea level for whole map") +// .append(newline()) +// .append(TextComponent.of("[FloorThickness]").hoverEvent(HoverEvent.showText(TextComponent.of("/cfi floorthickness 60"))) +// .clickEvent(ClickEvent.suggestCommand("/cfi floorthickness 60"))).append(" - Floor thickness of entire map") +// .append(newline()) +// .append(TextComponent.of("[WorldThickness]").hoverEvent(HoverEvent.showText(TextComponent.of("/cfi worldthickness 60"))) +// .clickEvent(ClickEvent.suggestCommand("/cfi worldthickness 60"))).append(" - World thickness of entire map") +// .append(newline()) +// .append(TextComponent.of("[Snow]").hoverEvent(HoverEvent.showText(TextComponent.of("/cfi snow" + maskArgs))) +// .clickEvent(ClickEvent.suggestCommand("/cfi snow" + maskArgs))).append(" - Set snow in the masked areas") +// .append(newline()); +// +// if (pattern != null) { +// String disabled = "You must specify a pattern"; +// msg.append(TextComponent.of("[WaterId]", TextColor.RED) +// .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); +// msg.append(newline()); +// msg.append(TextComponent.of("[BedrockId]", TextColor.RED) +// .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); +// msg.append(doubleNewLine); +// msg.append(TextComponent.of("[Floor]", TextColor.RED) +// .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); +// msg.append(doubleNewLine); +// msg.append(TextComponent.of("[Main]", TextColor.RED) +// .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); +// msg.append(doubleNewLine); +// msg.append(TextComponent.of("[Column]", TextColor.RED) +// .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); +// msg.append(doubleNewLine); +// msg.append(TextComponent.of("[Overlay]", TextColor.RED) +// .hoverEvent(HoverEvent.showText(TextComponent.of(disabled)))); +// msg.append(doubleNewLine); +// } else { +// StringBuilder compArgs = new StringBuilder(); +// compArgs.append(" " + settings.patternArg + maskArgs); +// +// msg.append(TextComponent.of("[WaterId]") +// .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi waterId " + pattern))) +// .clickEvent(ClickEvent.runCommand("/cfi waterId " + pattern))); +// msg.append(" - Water id for whole map"); +// msg.append(newline()); +// msg.append(TextComponent.of("[BedrockId]") +// .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi baseId " + pattern))) +// .clickEvent(ClickEvent.runCommand("/cfi baseId " + pattern))); +// msg.append(TextComponent.of(" - Bedrock id for whole map")); +// msg.append(newline()); +// msg.append(TextComponent.of("[Floor]") +// .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi floor " + compArgs))) +// .clickEvent(ClickEvent.runCommand("/cfi floor " + compArgs))); +// msg.append(TextComponent.of(" - Set the floor in the masked areas")); +// msg.append(newline()); +// msg.append(TextComponent.of("[Main]") +// .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi main " + compArgs))) +// .clickEvent(ClickEvent.runCommand("/cfi main " + compArgs))); +// msg.append(TextComponent.of(" - Set the main block in the masked areas")); +// msg.append(newline()); +// msg.append(TextComponent.of("[Column]") +// .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi column" + compArgs))) +// .clickEvent(ClickEvent.runCommand("/cfi column" + compArgs))); +// msg.append(" - Set the columns in the masked areas"); +// msg.append(newline()); +// msg.append(TextComponent.of("[Overlay]") +// .hoverEvent(HoverEvent.showText(TextComponent.of("/cfi overlay" + compArgs))) +// .clickEvent(ClickEvent.runCommand("/cfi overlay" + compArgs))); +// msg.append(" - Set the overlay in the masked areas"); +// msg.append(newline()); +// } +// +// msg.append(newline()) +// .append(TextComponent.of("< [Back]").hoverEvent(HoverEvent.showText(TextComponent.of("/cfi"))).clickEvent(ClickEvent.runCommand("/cfi"))); +// player.print(msg.build()); +// } +// +// private static CFISettings assertSettings(Player player) { +// CFISettings settings = getSettings(player); +// if (!settings.hasGenerator()) { +// throw new StopExecutionException(TextComponent.of("Please use /cfi")); +// } +// return settings; +// } +// +// +// protected static CFISettings getSettings(Player player) { +// CFISettings settings = player.getMeta("CFISettings"); +// if (settings == null) { +// settings = new CFISettings(player); +// } +// return settings; +// } +// +// public static class CFISettings { +// private final Player player; +// +// private HeightMapMCAGenerator generator; +// +// protected ProvideBindings.ImageUri image; +// protected String imageArg; +// protected Mask mask; +// protected ProvideBindings.ImageUri imageMask; +// protected boolean whiteOnly = true; +// protected String maskArg; +// protected String imageMaskArg; +// +// protected Pattern pattern; +// protected String patternArg; +// +// protected Consumer category; +// +// private boolean bound; +// +// public CFISettings(Player player) { +// this.player = player; +// } +// +// public boolean hasGenerator() { +// return generator != null; +// } +// +// public HeightMapMCAGenerator getGenerator() { +// return generator; +// } +// +// public void setMask(Mask mask, String arg) { +// this.mask = mask; +// this.maskArg = arg; +// } +// +// public void setImage(ProvideBindings.ImageUri image, String arg) { +// this.image = image; +// } +// +// public void setImageMask(ProvideBindings.ImageUri imageMask, String arg) { +// this.imageMask = imageMask; +// this.imageMaskArg = arg; +// } +// +// public void resetColoring() { +// image = null; +// imageArg = null; +// mask = null; +// imageMask = null; +// whiteOnly = true; +// maskArg = null; +// imageMaskArg = null; +// generator.setTextureUtil(Fawe.get().getTextureUtil()); +// } +// +// public void resetComponent() { +// mask = null; +// imageMask = null; +// whiteOnly = true; +// maskArg = null; +// imageMaskArg = null; +// patternArg = null; +// pattern = null; +// } +// +// public Consumer getCategory() { +// return category; +// } +// +// public void setCategory(Consumer methodRef) { +// this.category = category; +// } +// +// public CFISettings setGenerator(HeightMapMCAGenerator generator) { +// this.generator = generator; +// if (bound) { +// player.getSession().setVirtualWorld(generator); +// } +// return this; +// } +// +// public CFISettings bind() { +// if (generator != null) { +// player.getSession().setVirtualWorld(generator); +// } +// bound = true; +// player.setMeta("CFISettings", this); +// return this; +// } +// +// public void popMessages(Player player) { +// ArrayDeque messages = player.deleteMeta("CFIBufferedMessages"); +// if (messages != null) { +// for (String message : messages) { +// player.print(message); +// } +// } +// } +// +// public CFISettings remove() { +// player.deleteMeta("CFISettings"); +// HeightMapMCAGenerator gen = this.generator; +// if (gen != null) { +// player.getSession().setVirtualWorld(null); +// } +// popMessages(player); +// bound = false; +// generator = null; +// image = null; +// imageArg = null; +// mask = null; +// imageMask = null; +// whiteOnly = true; +// maskArg = null; +// imageMaskArg = null; +// return this; +// } +// } +// +// @SuppressWarnings("unused") +// protected static void mainMenu(Actor actor) { +// TextComponentProducer producer = new TextComponentProducer(); +// producer.append(TextComponent.of("What do you want to do now?")); +// producer.newline(); +// String prefix = "/cfi "; +// String[] options = {"Coloring", "Component", "Populate", "Brush"}; +// for (int i = 0; i < options.length; i++) { +// if (i != 0) { +// producer.append(TextComponent.of(" | ", TextColor.DARK_GRAY)); +// } +// String option = options[i]; +// String cmd = prefix + option; +// producer.append(TextComponent.of(option, TextColor.GREEN) +// .clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, cmd)) +// .hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of(option)))); +// } +// producer.newline(); +// producer.newline(); +// producer.append(TextComponent.of("<> [View]", TextColor.DARK_AQUA) +// .clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, prefix + "download")) +// .hoverEvent(HoverEvent +// .of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("View full res image")))); +// producer.newline(); +// producer.append(TextComponent.of(">< [Cancel]", TextColor.RED) +// .clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, prefix + "cancel")) +// .hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("cancel")))); +// producer.newline(); +// producer.append(TextComponent.of(">> [Done]", TextColor.DARK_GREEN) +// .clickEvent(ClickEvent.of(ClickEvent.Action.RUN_COMMAND, prefix + "done")) +// .hoverEvent(HoverEvent.of(HoverEvent.Action.SHOW_TEXT, TextComponent.of("done")))); +// +// actor.print(producer.create()); +// } +//} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/CommandProcessor.java b/worldedit-core/src/main/java/com/boydti/fawe/command/CommandProcessor.java deleted file mode 100644 index daf63f372..000000000 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/CommandProcessor.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.boydti.fawe.command; - -import com.google.common.collect.ImmutableSet; -import org.enginehub.piston.Command; -import org.enginehub.piston.CommandManager; -import org.enginehub.piston.CommandParseResult; -import org.enginehub.piston.converter.ArgumentConverter; -import org.enginehub.piston.inject.InjectedValueAccess; -import org.enginehub.piston.inject.Key; -import org.enginehub.piston.suggestion.Suggestion; - -import java.util.List; -import java.util.Optional; -import java.util.function.Consumer; -import java.util.stream.Stream; - -public abstract class CommandProcessor implements CommandManager { - private final CommandManager parent; - - public CommandProcessor(CommandManager parent) { - this.parent = parent; - } - - @Override - public final Command.Builder newCommand(String s) { - return parent.newCommand(s); - } - - @Override - public final void register(Command command) { - parent.register(command); - } - - @Override - public final void register(String name, Consumer registrationProcess) { - parent.register(name, registrationProcess); - } - - @Override - public final void registerManager(CommandManager manager) { - parent.registerManager(manager); - } - - @Override - public final Stream getAllCommands() { - return parent.getAllCommands(); - } - - @Override - public final boolean containsCommand(String name) { - return parent.containsCommand(name); - } - - @Override - public final Optional getCommand(String s) { - return parent.getCommand(s); - } - - @Override - public final ImmutableSet getSuggestions(InjectedValueAccess injectedValueAccess, List list) { - return parent.getSuggestions(injectedValueAccess, list); - } - - @Override - public final CommandParseResult parse(InjectedValueAccess injectedValueAccess, List list) { - return parent.parse(injectedValueAccess, list); - } - - @Override - public final Object execute(InjectedValueAccess context, List args) { - args = preprocess(context, args); - if (args != null) { - Object result = parent.execute(context, args); - return process(context, args, result); // TODO NOT IMPLEMENTED (recompile piston) - } else { - return null; - } - } - - @Override - public final void registerConverter(Key key, ArgumentConverter argumentConverter) { - parent.registerConverter(key, argumentConverter); - } - - @Override - public final Optional> getConverter(Key key) { - return parent.getConverter(key); - } - - public abstract List preprocess(InjectedValueAccess context, List args); - - public abstract Object process(InjectedValueAccess context, List args, Object result); -} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/FaweParser.java b/worldedit-core/src/main/java/com/boydti/fawe/command/FaweParser.java index caafa0c18..324885e03 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/FaweParser.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/command/FaweParser.java @@ -1,113 +1,114 @@ -package com.boydti.fawe.command; - -import com.boydti.fawe.util.StringMan; -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.extension.input.InputParseException; -import com.sk89q.worldedit.extension.input.ParserContext; -import com.sk89q.worldedit.extension.platform.PlatformCommandManager; -import com.sk89q.worldedit.internal.registry.InputParser; -import org.enginehub.piston.inject.InjectedValueAccess; - -import java.util.*; - -public abstract class FaweParser extends InputParser { - - private final String prefix; - - protected FaweParser(WorldEdit worldEdit, String prefix) { - super(worldEdit); - this.prefix = prefix; - } - - public PlatformCommandManager getPlatform() { - return PlatformCommandManager.getInstance(); - } - - public T parse(String input, ParserContext context) { - input = prefix + " " + input; - InjectedValueAccess injected = context.getInjected(); - if (injected != null) { - return getPlatform().parseCommand(input, injected); - } else { - return getPlatform().parseCommand(input, context.getActor()); - } - } - - public T catchSuggestion(String currentInput, String nextInput, ParserContext context) throws InputParseException { - try { - return parseFromInput(nextInput, context); - } catch (SuggestInputParseException e) { - e.prepend(currentInput.substring(0, currentInput.length() - nextInput.length())); - throw e; - } - } - - protected static class ParseEntry { - public boolean and; - public String input; - public String full; - - public ParseEntry(String full, String input, boolean type) { - this.full = full; - this.input = input; - this.and = type; - } - - @Override - public String toString() { - return input + " | " + and; - } - } - - public static List>> parse(String toParse) throws InputParseException { - List>> keys = new ArrayList<>(); - List inputs = new ArrayList<>(); - List and = new ArrayList<>(); - int last = 0; - outer: - for (int i = 0; i < toParse.length(); i++) { - char c = toParse.charAt(i); - switch (c) { - case ',': - case '&': - String result = toParse.substring(last, i); - if (!result.isEmpty()) { - inputs.add(result); - and.add(c == '&'); - } else { - throw new InputParseException("Invalid dangling character " + c); - } - last = i + 1; - continue outer; - default: - if (c == '[' && StringMan.getMatchingBracket(c) != c) { - int next = StringMan.findMatchingBracket(toParse, i); - if (next != -1) { - i = next; - } else { - toParse += "]"; - i = toParse.length(); - } - continue outer; - } - } - } - inputs.add(toParse.substring(last)); - for (int i = 0; i < inputs.size(); i++) { - String full = inputs.get(i); - String command = full; - List args = new ArrayList<>(); - while (!command.isEmpty() && command.charAt(command.length() - 1) == ']') { - int startPos = StringMan.findMatchingBracket(command, command.length() - 1); - if (startPos == -1) break; - String arg = command.substring(startPos + 1, command.length() - 1); - args.add(arg); - command = full.substring(0, startPos); - } - Collections.reverse(args); - ParseEntry entry = new ParseEntry(full, command, i > 0 ? and.get(i - 1) : false); - keys.add(new AbstractMap.SimpleEntry<>(entry, args)); - } - return keys; - } -} +// TODO: Ping @MattBDev to reimplement 2020-02-04 +//package com.boydti.fawe.command; +// +//import com.boydti.fawe.util.StringMan; +//import com.sk89q.worldedit.WorldEdit; +//import com.sk89q.worldedit.extension.input.InputParseException; +//import com.sk89q.worldedit.extension.input.ParserContext; +//import com.sk89q.worldedit.extension.platform.PlatformCommandManager; +//import com.sk89q.worldedit.internal.registry.InputParser; +//import org.enginehub.piston.inject.InjectedValueAccess; +// +//import java.util.*; +// +//public abstract class FaweParser extends InputParser { +// +// private final String prefix; +// +// protected FaweParser(WorldEdit worldEdit, String prefix) { +// super(worldEdit); +// this.prefix = prefix; +// } +// +// public PlatformCommandManager getPlatform() { +// return PlatformCommandManager.getInstance(); +// } +// +// public T parse(String input, ParserContext context) { +// input = prefix + " " + input; +// InjectedValueAccess injected = context.getInjected(); +// if (injected != null) { +// return getPlatform().parseCommand(input, injected); +// } else { +// return getPlatform().parseCommand(input, context.getActor()); +// } +// } +// +// public T catchSuggestion(String currentInput, String nextInput, ParserContext context) throws InputParseException { +// try { +// return parseFromInput(nextInput, context); +// } catch (SuggestInputParseException e) { +// e.prepend(currentInput.substring(0, currentInput.length() - nextInput.length())); +// throw e; +// } +// } +// +// protected static class ParseEntry { +// public boolean and; +// public String input; +// public String full; +// +// public ParseEntry(String full, String input, boolean type) { +// this.full = full; +// this.input = input; +// this.and = type; +// } +// +// @Override +// public String toString() { +// return input + " | " + and; +// } +// } +// +// public static List>> parse(String toParse) throws InputParseException { +// List>> keys = new ArrayList<>(); +// List inputs = new ArrayList<>(); +// List and = new ArrayList<>(); +// int last = 0; +// outer: +// for (int i = 0; i < toParse.length(); i++) { +// char c = toParse.charAt(i); +// switch (c) { +// case ',': +// case '&': +// String result = toParse.substring(last, i); +// if (!result.isEmpty()) { +// inputs.add(result); +// and.add(c == '&'); +// } else { +// throw new InputParseException("Invalid dangling character " + c); +// } +// last = i + 1; +// continue outer; +// default: +// if (c == '[' && StringMan.getMatchingBracket(c) != c) { +// int next = StringMan.findMatchingBracket(toParse, i); +// if (next != -1) { +// i = next; +// } else { +// toParse += "]"; +// i = toParse.length(); +// } +// continue outer; +// } +// } +// } +// inputs.add(toParse.substring(last)); +// for (int i = 0; i < inputs.size(); i++) { +// String full = inputs.get(i); +// String command = full; +// List args = new ArrayList<>(); +// while (!command.isEmpty() && command.charAt(command.length() - 1) == ']') { +// int startPos = StringMan.findMatchingBracket(command, command.length() - 1); +// if (startPos == -1) break; +// String arg = command.substring(startPos + 1, command.length() - 1); +// args.add(arg); +// command = full.substring(0, startPos); +// } +// Collections.reverse(args); +// ParseEntry entry = new ParseEntry(full, command, i > 0 ? and.get(i - 1) : false); +// keys.add(new AbstractMap.SimpleEntry<>(entry, args)); +// } +// return keys; +// } +//} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/command/PlotLoader.java b/worldedit-core/src/main/java/com/boydti/fawe/command/PlotLoader.java index def448466..fe4242243 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/command/PlotLoader.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/command/PlotLoader.java @@ -1,82 +1,83 @@ -package com.boydti.fawe.command; - -import com.boydti.fawe.command.CFICommands.CFISettings; -import com.boydti.fawe.object.RunnableVal; -import com.boydti.fawe.util.TaskManager; -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.sk89q.worldedit.extension.platform.Actor; -import java.io.File; -import java.io.IOException; -import java.util.function.Function; - -public class PlotLoader { - - @Deprecated - 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); - return; - } - whenDone.value = plot; - plot.owner = player.getUUID(); - DBFunc.createPlotSafe(plot, whenDone, - () -> autoClaimFromDatabase(player, area, plot.getId(), whenDone)); - } - - public void load(Actor actor, CFISettings settings, Function createTask) throws IOException { - PlotAreaManager manager = PlotSquared.get().getPlotAreaManager(); - if (manager instanceof SinglePlotAreaManager) { - SinglePlotAreaManager sManager = (SinglePlotAreaManager) manager; - SinglePlotArea area = sManager.getArea(); - PlotPlayer player = PlotPlayer.get(actor.getName()); - - actor.print("Claiming world"); - Plot plot = TaskManager.IMP.sync(new RunnableVal() { - @Override - public void run(Plot o) { - int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() - : player.getPlotCount(area.worldname); - int diff = player.getAllowedPlots() - currentPlots; - if (diff < 1) { - Captions.CANT_CLAIM_MORE_PLOTS_NUM.send(player, -diff); - return; - } - - if (area.getMeta("lastPlot") == null) { - area.setMeta("lastPlot", new PlotId(0, 0)); - } - PlotId lastId = (PlotId) area.getMeta("lastPlot"); - do { - lastId = Auto.getNextPlotId(lastId, 1); - } while (!area.canClaim(player, lastId, lastId)); - area.setMeta("lastPlot", lastId); - this.value = area.getPlot(lastId); - this.value.setOwner(player.getUUID()); - } - }); - if (plot != null) { - - File folder = CFICommands.getFolder(plot.getWorldName()); - Boolean result = createTask.apply(folder); - if (result == Boolean.TRUE) { - TaskManager.IMP.sync(() -> plot.teleportPlayer(player)); - } - return; - } - } - createTask.apply(null); - } -} +// TODO: Ping @MattBDev to reimplement 2020-02-04 +//package com.boydti.fawe.command; +// +//import com.boydti.fawe.command.CFICommands.CFISettings; +//import com.boydti.fawe.object.RunnableVal; +//import com.boydti.fawe.util.TaskManager; +//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.sk89q.worldedit.extension.platform.Actor; +//import java.io.File; +//import java.io.IOException; +//import java.util.function.Function; +// +//public class PlotLoader { +// +// @Deprecated +// 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); +// return; +// } +// whenDone.value = plot; +// plot.owner = player.getUUID(); +// DBFunc.createPlotSafe(plot, whenDone, +// () -> autoClaimFromDatabase(player, area, plot.getId(), whenDone)); +// } +// +// public void load(Actor actor, CFISettings settings, Function createTask) throws IOException { +// PlotAreaManager manager = PlotSquared.get().getPlotAreaManager(); +// if (manager instanceof SinglePlotAreaManager) { +// SinglePlotAreaManager sManager = (SinglePlotAreaManager) manager; +// SinglePlotArea area = sManager.getArea(); +// PlotPlayer player = PlotPlayer.get(actor.getName()); +// +// actor.print("Claiming world"); +// Plot plot = TaskManager.IMP.sync(new RunnableVal() { +// @Override +// public void run(Plot o) { +// int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() +// : player.getPlotCount(area.worldname); +// int diff = player.getAllowedPlots() - currentPlots; +// if (diff < 1) { +// Captions.CANT_CLAIM_MORE_PLOTS_NUM.send(player, -diff); +// return; +// } +// +// if (area.getMeta("lastPlot") == null) { +// area.setMeta("lastPlot", new PlotId(0, 0)); +// } +// PlotId lastId = (PlotId) area.getMeta("lastPlot"); +// do { +// lastId = Auto.getNextPlotId(lastId, 1); +// } while (!area.canClaim(player, lastId, lastId)); +// area.setMeta("lastPlot", lastId); +// this.value = area.getPlot(lastId); +// this.value.setOwner(player.getUUID()); +// } +// }); +// if (plot != null) { +// +// File folder = CFICommands.getFolder(plot.getWorldName()); +// Boolean result = createTask.apply(folder); +// if (result == Boolean.TRUE) { +// TaskManager.IMP.sync(() -> plot.teleportPlayer(player)); +// } +// return; +// } +// } +// createTask.apply(null); +// } +//} diff --git a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BrushSettings.java b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BrushSettings.java index 36cfa334e..24134f122 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BrushSettings.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/object/brush/BrushSettings.java @@ -58,65 +58,66 @@ public class BrushSettings { this.constructor.put(SettingType.PERMISSIONS, permissions); } - public static BrushSettings get(BrushTool tool, Player player, LocalSession session, Map settings) throws InputParseException { - PlatformCommandManager manager = PlatformCommandManager.getInstance(); - String constructor = (String) settings.get(SettingType.BRUSH.name()); - if (constructor == null) { - return new BrushSettings(); - } - BrushSettings bs = manager.parseCommand(constructor, player); - bs.constructor.put(SettingType.BRUSH, constructor); - if (settings.containsKey(SettingType.PERMISSIONS.name())) { - bs.permissions.addAll((Collection) settings.get(SettingType.PERMISSIONS.name())); - } - if (settings.containsKey(SettingType.SIZE.name())) { - try { - bs.size = Expression.compile((String) settings.getOrDefault(SettingType.SIZE.name(), -1)); - bs.size.optimize(); - } catch (ExpressionException e) { - throw new RuntimeException(e); - } - } - - ParserContext parserContext = new ParserContext(); - parserContext.setActor(player); - parserContext.setWorld(player.getWorld()); - parserContext.setSession(session); - - if (settings.containsKey(SettingType.MASK.name())) { - String maskArgs = (String) settings.get(SettingType.MASK.name()); - Mask mask = WorldEdit.getInstance().getMaskFactory().parseFromInput(maskArgs, parserContext); - bs.setMask(mask); - bs.constructor.put(SettingType.MASK, maskArgs); - } - if (settings.containsKey(SettingType.SOURCE_MASK.name())) { - String maskArgs = (String) settings.get(SettingType.SOURCE_MASK.name()); - Mask mask = WorldEdit.getInstance().getMaskFactory().parseFromInput(maskArgs, parserContext); - bs.setSourceMask(mask); - bs.constructor.put(SettingType.SOURCE_MASK, maskArgs); - } - if (settings.containsKey(SettingType.TRANSFORM.name())) { - String transformArgs = (String) settings.get(SettingType.TRANSFORM.name()); - ResettableExtent extent = Fawe.get().getTransformParser().parseFromInput(transformArgs, parserContext); - bs.setTransform(extent); - bs.constructor.put(SettingType.TRANSFORM, transformArgs); - } - if (settings.containsKey(SettingType.FILL.name())) { - String fillArgs = (String) settings.get(SettingType.FILL.name()); - Pattern pattern = WorldEdit.getInstance().getPatternFactory().parseFromInput(fillArgs, parserContext); - bs.setFill(pattern); - bs.constructor.put(SettingType.FILL, fillArgs); - } - if (settings.containsKey(SettingType.SCROLL_ACTION.name())) { - String actionArgs = (String) settings.get(SettingType.SCROLL_ACTION.name()); - Scroll action = Scroll.fromArguments(tool, player, session, actionArgs, false); - if (action != null) { - bs.setScrollAction(action); - bs.constructor.put(SettingType.SCROLL_ACTION, actionArgs); - } - } - return bs; - } + // TODO: Ping @MattBDev to reimplement 2020-02-04 +// public static BrushSettings get(BrushTool tool, Player player, LocalSession session, Map settings) throws InputParseException { +// PlatformCommandManager manager = PlatformCommandManager.getInstance(); +// String constructor = (String) settings.get(SettingType.BRUSH.name()); +// if (constructor == null) { +// return new BrushSettings(); +// } +// BrushSettings bs = manager.parseCommand(constructor, player); +// bs.constructor.put(SettingType.BRUSH, constructor); +// if (settings.containsKey(SettingType.PERMISSIONS.name())) { +// bs.permissions.addAll((Collection) settings.get(SettingType.PERMISSIONS.name())); +// } +// if (settings.containsKey(SettingType.SIZE.name())) { +// try { +// bs.size = Expression.compile((String) settings.getOrDefault(SettingType.SIZE.name(), -1)); +// bs.size.optimize(); +// } catch (ExpressionException e) { +// throw new RuntimeException(e); +// } +// } +// +// ParserContext parserContext = new ParserContext(); +// parserContext.setActor(player); +// parserContext.setWorld(player.getWorld()); +// parserContext.setSession(session); +// +// if (settings.containsKey(SettingType.MASK.name())) { +// String maskArgs = (String) settings.get(SettingType.MASK.name()); +// Mask mask = WorldEdit.getInstance().getMaskFactory().parseFromInput(maskArgs, parserContext); +// bs.setMask(mask); +// bs.constructor.put(SettingType.MASK, maskArgs); +// } +// if (settings.containsKey(SettingType.SOURCE_MASK.name())) { +// String maskArgs = (String) settings.get(SettingType.SOURCE_MASK.name()); +// Mask mask = WorldEdit.getInstance().getMaskFactory().parseFromInput(maskArgs, parserContext); +// bs.setSourceMask(mask); +// bs.constructor.put(SettingType.SOURCE_MASK, maskArgs); +// } +// if (settings.containsKey(SettingType.TRANSFORM.name())) { +// String transformArgs = (String) settings.get(SettingType.TRANSFORM.name()); +// ResettableExtent extent = Fawe.get().getTransformParser().parseFromInput(transformArgs, parserContext); +// bs.setTransform(extent); +// bs.constructor.put(SettingType.TRANSFORM, transformArgs); +// } +// if (settings.containsKey(SettingType.FILL.name())) { +// String fillArgs = (String) settings.get(SettingType.FILL.name()); +// Pattern pattern = WorldEdit.getInstance().getPatternFactory().parseFromInput(fillArgs, parserContext); +// bs.setFill(pattern); +// bs.constructor.put(SettingType.FILL, fillArgs); +// } +// if (settings.containsKey(SettingType.SCROLL_ACTION.name())) { +// String actionArgs = (String) settings.get(SettingType.SCROLL_ACTION.name()); +// Scroll action = Scroll.fromArguments(tool, player, session, actionArgs, false); +// if (action != null) { +// bs.setScrollAction(action); +// bs.constructor.put(SettingType.SCROLL_ACTION, actionArgs); +// } +// } +// return bs; +// } public BrushSettings setBrush(Brush brush) { Brush tmp = this.brush; diff --git a/worldedit-core/src/main/java/com/boydti/fawe/util/BrushCache.java b/worldedit-core/src/main/java/com/boydti/fawe/util/BrushCache.java index 8964a5ebe..4c35ccb5b 100644 --- a/worldedit-core/src/main/java/com/boydti/fawe/util/BrushCache.java +++ b/worldedit-core/src/main/java/com/boydti/fawe/util/BrushCache.java @@ -41,23 +41,24 @@ public final class BrushCache { CompoundTag nbt = item.getNbtData(); if (nbt == null) return null; StringTag json = (StringTag) nbt.getValue().get("weBrushJson"); - if (json != null) { - try { - if (RECURSION.get() != null) return null; - RECURSION.set(true); - - BrushTool tool = BrushTool.fromString(player, session, json.getValue()); - tool.setHolder(item); - brushCache.put(key, tool); - return tool; - } catch (Exception throwable) { - getLogger(BrushCache.class).debug("Invalid brush for " + player + " holding " + item.getType() + ": " + json.getValue(), throwable); - item.setNbtData(null); - brushCache.remove(key); - } finally { - RECURSION.remove(); - } - } + // TODO: Ping @MattBDev to reimplement 2020-02-04 +// if (json != null) { +// try { +// if (RECURSION.get() != null) return null; +// RECURSION.set(true); +// +// BrushTool tool = BrushTool.fromString(player, session, json.getValue()); +// tool.setHolder(item); +// brushCache.put(key, tool); +// return tool; +// } catch (Exception throwable) { +// getLogger(BrushCache.class).debug("Invalid brush for " + player + " holding " + item.getType() + ": " + json.getValue(), throwable); +// item.setNbtData(null); +// brushCache.remove(key); +// } finally { +// RECURSION.remove(); +// } +// } return null; } 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 a481bdf12..28371d41b 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 @@ -155,6 +155,15 @@ public class BrushCommands { this.worldEdit = worldEdit; } + @Command( + name = "none", + aliases = "unbind", + desc = "Unbind a bound brush from your current item" + ) + void none(Player player, LocalSession session) throws WorldEditException { + ToolCommands.setToolNone(player, session, true); + } + @Command( name = "blendball", aliases = {"bb", "blend"}, @@ -984,38 +993,39 @@ public class BrushCommands { } } - @Command( - name = "loadbrush", - aliases = {"load"}, - desc = "Load a brush" - ) - @CommandPermissions("worldedit.brush.load") - public void loadBrush(Player player, LocalSession session, @Arg(desc = "String name") String name) - throws WorldEditException, IOException { - name = FileSystems.getDefault().getPath(name).getFileName().toString(); - File folder = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes"); - name = name.endsWith(".jsgz") ? name : name + ".jsgz"; - File file = new File(folder, player.getUniqueId() + File.separator + name); - if (!file.exists()) { - file = new File(folder, name); - } - if (!file.exists()) { - File[] files = folder.listFiles(pathname -> false); - player.print(Caption.of("fawe.error.brush.not.found" , name)); - return; - } - try (DataInputStream in = new DataInputStream( - new GZIPInputStream(new FileInputStream(file)))) { - String json = in.readUTF(); - BrushTool tool = BrushTool.fromString(player, session, json); - BaseItem item = player.getItemInHand(HandSide.MAIN_HAND); - session.setTool(item, tool, player); - player.print(Caption.of("fawe.worldedit.brush.brush.equipped" , name)); - } catch (Throwable e) { - e.printStackTrace(); - player.printError(TranslatableComponent.of("fawe.error.brush.incompatible")); - } - } + // TODO: Ping @MattBDev to reimplement 2020-02-04 +// @Command( +// name = "loadbrush", +// aliases = {"load"}, +// desc = "Load a brush" +// ) +// @CommandPermissions("worldedit.brush.load") +// public void loadBrush(Player player, LocalSession session, @Arg(desc = "String name") String name) +// throws WorldEditException, IOException { +// name = FileSystems.getDefault().getPath(name).getFileName().toString(); +// File folder = MainUtil.getFile(Fawe.imp().getDirectory(), "brushes"); +// name = name.endsWith(".jsgz") ? name : name + ".jsgz"; +// File file = new File(folder, player.getUniqueId() + File.separator + name); +// if (!file.exists()) { +// file = new File(folder, name); +// } +// if (!file.exists()) { +// File[] files = folder.listFiles(pathname -> false); +// player.print(Caption.of("fawe.error.brush.not.found" , name)); +// return; +// } +// try (DataInputStream in = new DataInputStream( +// new GZIPInputStream(new FileInputStream(file)))) { +// String json = in.readUTF(); +// BrushTool tool = BrushTool.fromString(player, session, json); +// BaseItem item = player.getItemInHand(HandSide.MAIN_HAND); +// session.setTool(item, tool, player); +// player.print(Caption.of("fawe.worldedit.brush.brush.equipped" , name)); +// } catch (Throwable e) { +// e.printStackTrace(); +// player.printError(TranslatableComponent.of("fawe.error.brush.incompatible")); +// } +// } @Command( name = "/listbrush", 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 3c0fdfaa1..aebe756b9 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 @@ -1,448 +1,449 @@ -package com.sk89q.worldedit.command; - -import com.boydti.fawe.object.mask.AdjacentAnyMask; -import com.boydti.fawe.object.mask.AdjacentMask; -import com.boydti.fawe.object.mask.AngleMask; -import com.boydti.fawe.object.mask.BiomeMask; -import com.boydti.fawe.object.mask.BlockLightMask; -import com.boydti.fawe.object.mask.BrightnessMask; -import com.boydti.fawe.object.mask.DataMask; -import com.boydti.fawe.object.mask.ExtremaMask; -import com.boydti.fawe.object.mask.IdDataMask; -import com.boydti.fawe.object.mask.IdMask; -import com.boydti.fawe.object.mask.LightMask; -import com.boydti.fawe.object.mask.OpacityMask; -import com.boydti.fawe.object.mask.ROCAngleMask; -import com.boydti.fawe.object.mask.RadiusMask; -import com.boydti.fawe.object.mask.RandomMask; -import com.boydti.fawe.object.mask.SimplexMask; -import com.boydti.fawe.object.mask.SkyLightMask; -import com.boydti.fawe.object.mask.SurfaceMask; -import com.boydti.fawe.object.mask.WallMask; -import com.boydti.fawe.object.mask.XAxisMask; -import com.boydti.fawe.object.mask.YAxisMask; -import com.boydti.fawe.object.mask.ZAxisMask; -import com.sk89q.worldedit.IncompleteRegionException; -import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; -import com.sk89q.worldedit.entity.Player; -import com.sk89q.worldedit.extent.Extent; -import com.sk89q.worldedit.function.mask.BlockMaskBuilder; -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.function.mask.Masks; -import com.sk89q.worldedit.function.mask.OffsetMask; -import com.sk89q.worldedit.function.mask.RegionMask; -import com.sk89q.worldedit.function.mask.SolidBlockMask; -import com.sk89q.worldedit.internal.expression.Expression; -import com.sk89q.worldedit.internal.expression.ExpressionEnvironment; -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.world.biome.BiomeType; -import org.enginehub.piston.annotation.Command; -import org.enginehub.piston.annotation.CommandContainer; -import org.enginehub.piston.annotation.param.Arg; -import org.enginehub.piston.annotation.param.Switch; - -//@Command(aliases = {"masks"}, -// desc = "Help for the various masks. [More Info](https://git.io/v9r4K)", -// descFooter = "Masks determine if a block can be placed\n" + -// " - Use [brackets] for arguments\n" + -// " - Use , to OR multiple\n" + -// " - Use & to AND multiple\n" + -// "e.g. >[stone,dirt],#light[0][5],$jungle\n" + -// "More Info: https://git.io/v9r4K" +// TODO: Ping @MattBDev to reimplement (or remove because this class is stupid) 2020-02-04 +//package com.sk89q.worldedit.command; +// +//import com.boydti.fawe.object.mask.AdjacentAnyMask; +//import com.boydti.fawe.object.mask.AdjacentMask; +//import com.boydti.fawe.object.mask.AngleMask; +//import com.boydti.fawe.object.mask.BiomeMask; +//import com.boydti.fawe.object.mask.BlockLightMask; +//import com.boydti.fawe.object.mask.BrightnessMask; +//import com.boydti.fawe.object.mask.DataMask; +//import com.boydti.fawe.object.mask.ExtremaMask; +//import com.boydti.fawe.object.mask.IdDataMask; +//import com.boydti.fawe.object.mask.IdMask; +//import com.boydti.fawe.object.mask.LightMask; +//import com.boydti.fawe.object.mask.OpacityMask; +//import com.boydti.fawe.object.mask.ROCAngleMask; +//import com.boydti.fawe.object.mask.RadiusMask; +//import com.boydti.fawe.object.mask.RandomMask; +//import com.boydti.fawe.object.mask.SimplexMask; +//import com.boydti.fawe.object.mask.SkyLightMask; +//import com.boydti.fawe.object.mask.SurfaceMask; +//import com.boydti.fawe.object.mask.WallMask; +//import com.boydti.fawe.object.mask.XAxisMask; +//import com.boydti.fawe.object.mask.YAxisMask; +//import com.boydti.fawe.object.mask.ZAxisMask; +//import com.sk89q.worldedit.IncompleteRegionException; +//import com.sk89q.worldedit.LocalSession; +//import com.sk89q.worldedit.WorldEdit; +//import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; +//import com.sk89q.worldedit.entity.Player; +//import com.sk89q.worldedit.extent.Extent; +//import com.sk89q.worldedit.function.mask.BlockMaskBuilder; +//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.function.mask.Masks; +//import com.sk89q.worldedit.function.mask.OffsetMask; +//import com.sk89q.worldedit.function.mask.RegionMask; +//import com.sk89q.worldedit.function.mask.SolidBlockMask; +//import com.sk89q.worldedit.internal.expression.Expression; +//import com.sk89q.worldedit.internal.expression.ExpressionEnvironment; +//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.world.biome.BiomeType; +//import org.enginehub.piston.annotation.Command; +//import org.enginehub.piston.annotation.CommandContainer; +//import org.enginehub.piston.annotation.param.Arg; +//import org.enginehub.piston.annotation.param.Switch; +// +////@Command(aliases = {"masks"}, +//// desc = "Help for the various masks. [More Info](https://git.io/v9r4K)", +//// descFooter = "Masks determine if a block can be placed\n" + +//// " - Use [brackets] for arguments\n" + +//// " - Use , to OR multiple\n" + +//// " - Use & to AND multiple\n" + +//// "e.g. >[stone,dirt],#light[0][5],$jungle\n" + +//// "More Info: https://git.io/v9r4K" +////) +//@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class) +//public class MaskCommands { +// private final WorldEdit worldEdit; +// +// public MaskCommands(WorldEdit worldEdit) { +// this.worldEdit = worldEdit; +// } +// +// @Command( +// name = "#simplex", +// desc = "Use simplex noise as the mask" +// ) +// public Mask simplex(@Arg(desc = "double scale") double scale, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { +// scale = 1d / Math.max(1, scale); +// minInt = (minInt - 50) / 50; +// maxInt = (maxInt - 50) / 50; +// return new SimplexMask(scale, minInt, maxInt); +// } +// +// @Command( +// name = "#light", +// desc = "Restrict to specific light levels" +// ) +// public Mask light(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { +// return new LightMask(extent, (int) minInt, (int) maxInt); +// } +// +// @Command( +// name = "#false", +// desc = "Always false" +// ) +// public Mask falseMask(Extent extent) { +// return Masks.alwaysFalse(); +// } +// +// @Command( +// name = "#true", +// desc = "Always true" +// ) +// public Mask trueMask(Extent extent) { +// return Masks.alwaysTrue(); +// } +// +// @Command( +// name = "#skylight", +// desc = "Restrict to specific sky light levels" +// ) +// public Mask skylight(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { +// return new SkyLightMask(extent, (int) minInt, (int) maxInt); +// } +// +// @Command( +// name = "#blocklight", +// aliases = {"#emittedlight"}, +// desc = "Restrict to specific block light levels" +// ) +// public Mask blocklight(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { +// return new BlockLightMask(extent, (int) minInt, (int) maxInt); +// } +// +// @Command( +// name = "#opacity", +// desc = "Restrict to specific opacity levels" +// ) +// public Mask opacity(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { +// return new OpacityMask(extent, (int) minInt, (int) maxInt); +// } +// +// @Command( +// name = "#brightness", +// desc = "Restrict to specific block brightness" +// ) +// public Mask brightness(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { +// return new BrightnessMask(extent, (int) minInt, (int) maxInt); +// } +// +// @Command( +// name = "#offset", +// desc = "Offset a mask" +// ) +// public Mask offset(@Arg(desc = "double x") double x, @Arg(desc = "double y") double y, @Arg(desc = "double z") double z, @Arg(desc = "Mask") Mask mask) { +// return new OffsetMask(mask, BlockVector3.at(x, y, z)); +// } +// +// @Command( +// name = "#haslight", +// desc = "Restricts to blocks with light (sky or emitted)" +// ) +// public Mask haslight(Extent extent) { +// return new LightMask(extent, 1, Integer.MAX_VALUE); +// } +// +// @Command( +// name = "#nolight", +// desc = "Restrict to blocks without light (sky or emitted)" +// ) +// public Mask nolight(Extent extent) { +// return new LightMask(extent, 0, 0); +// } +// +// @Command( +// name = "#existing", +// desc = "If there is a non air block" +// ) +// public Mask existing(Extent extent) { +// return new ExistingBlockMask(extent); +// } +// +// @Command( +// name = "#solid", +// desc = "If there is a solid block" +// ) +// public Mask solid(Extent extent) { +// return new SolidBlockMask(extent); +// } +// +// @Command( +// name = "#liquid", +// desc = "If there is a solid block" +// ) +// public Mask liquid(Extent extent) { +// return new BlockMaskBuilder().addAll(b -> b.getMaterial().isLiquid()).build(extent); +// } +// +// @Command( +// name = "#dregion", +// aliases = {"#dselection", "#dsel"}, +// desc = "inside the player's selection" +// ) +// public Mask dregion() { +// return new RegionMask(new RequestSelection()); +// } +// +// @Command( +// name = "#region", +// aliases = {"#selection", "#sel"}, +// desc = "inside the provided selection" +// ) +// public Mask selection(Player player, LocalSession session) throws IncompleteRegionException { +// return new RegionMask(session.getSelection(player.getWorld()).clone()); +// } +// +// @Command( +// name = "#xaxis", +// desc = "Restrict to initial x axis" +// ) +// public Mask xaxis() { +// return new XAxisMask(); +// } +// +// @Command( +// name = "#yaxis", +// desc = "Restrict to initial y axis" +// ) +// public Mask yaxis() { +// return new YAxisMask(); +// } +// +// @Command( +// name = "#zaxis", +// desc = "Restrict to initial z axis" +// ) +// public Mask zaxis() { +// return new ZAxisMask(); +// } +// +// @Command( +// name = "#id", +// desc = "Restrict to initial id" +// ) +// public Mask id(Extent extent) { +// return new IdMask(extent); +// } +// +// @Command( +// name = "#data", +// desc = "Restrict to initial data" +// ) +// public Mask data(Extent extent) { +// return new DataMask(extent); +// } +// +// @Command( +// name = "#iddata", +// desc = "Restrict to initial block id and data" +// ) +// public Mask iddata(Extent extent) { +// return new IdDataMask(extent); +// } +// +// @Command( +// name = "#air", +// desc = "Restrict to types of air" +// ) +// public Mask air(Extent extent) { +// return new BlockMaskBuilder().addAll(b -> b.getMaterial().isAir()).build(extent); +// } +// +// @Command( +// name = "#wall", +// desc = "Restrict to walls (any block n,e,s,w of air)" +// ) +// public Mask wall(Extent extent) { +// Mask blockMask = air(extent); +// return new MaskUnion(new ExistingBlockMask(extent), new WallMask(blockMask, 1, 8)); +// } +// +// @Command( +// name = "#surface", +// desc = "Restrict to surfaces (any solid block touching air)" +// ) +// public Mask surface(Extent extent) { +// return new SurfaceMask(extent); +// } +// +// @Command( +// name = "\\", +// aliases = {"/", "#angle", "#\\", "#/"}, +// desc = "Restrict to specific terrain angle", +// descFooter = "Restrict to specific terrain angle\n" + +// "The -o flag will only overlay\n" + +// "Example: /[0d][45d]\n" + +// "Explanation: Allows any block where the adjacent block is between 0 and 45 degrees.\n" + +// "Example: /[3][20]\n" + +// "Explanation: Allows any block where the adjacent block is between 3 and 20 blocks below" //) -@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class) -public class MaskCommands { - private final WorldEdit worldEdit; - - public MaskCommands(WorldEdit worldEdit) { - this.worldEdit = worldEdit; - } - - @Command( - name = "#simplex", - desc = "Use simplex noise as the mask" - ) - public Mask simplex(@Arg(desc = "double scale") double scale, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { - scale = 1d / Math.max(1, scale); - minInt = (minInt - 50) / 50; - maxInt = (maxInt - 50) / 50; - return new SimplexMask(scale, minInt, maxInt); - } - - @Command( - name = "#light", - desc = "Restrict to specific light levels" - ) - public Mask light(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { - return new LightMask(extent, (int) minInt, (int) maxInt); - } - - @Command( - name = "#false", - desc = "Always false" - ) - public Mask falseMask(Extent extent) { - return Masks.alwaysFalse(); - } - - @Command( - name = "#true", - desc = "Always true" - ) - public Mask trueMask(Extent extent) { - return Masks.alwaysTrue(); - } - - @Command( - name = "#skylight", - desc = "Restrict to specific sky light levels" - ) - public Mask skylight(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { - return new SkyLightMask(extent, (int) minInt, (int) maxInt); - } - - @Command( - name = "#blocklight", - aliases = {"#emittedlight"}, - desc = "Restrict to specific block light levels" - ) - public Mask blocklight(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { - return new BlockLightMask(extent, (int) minInt, (int) maxInt); - } - - @Command( - name = "#opacity", - desc = "Restrict to specific opacity levels" - ) - public Mask opacity(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { - return new OpacityMask(extent, (int) minInt, (int) maxInt); - } - - @Command( - name = "#brightness", - desc = "Restrict to specific block brightness" - ) - public Mask brightness(Extent extent, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) { - return new BrightnessMask(extent, (int) minInt, (int) maxInt); - } - - @Command( - name = "#offset", - desc = "Offset a mask" - ) - public Mask offset(@Arg(desc = "double x") double x, @Arg(desc = "double y") double y, @Arg(desc = "double z") double z, @Arg(desc = "Mask") Mask mask) { - return new OffsetMask(mask, BlockVector3.at(x, y, z)); - } - - @Command( - name = "#haslight", - desc = "Restricts to blocks with light (sky or emitted)" - ) - public Mask haslight(Extent extent) { - return new LightMask(extent, 1, Integer.MAX_VALUE); - } - - @Command( - name = "#nolight", - desc = "Restrict to blocks without light (sky or emitted)" - ) - public Mask nolight(Extent extent) { - return new LightMask(extent, 0, 0); - } - - @Command( - name = "#existing", - desc = "If there is a non air block" - ) - public Mask existing(Extent extent) { - return new ExistingBlockMask(extent); - } - - @Command( - name = "#solid", - desc = "If there is a solid block" - ) - public Mask solid(Extent extent) { - return new SolidBlockMask(extent); - } - - @Command( - name = "#liquid", - desc = "If there is a solid block" - ) - public Mask liquid(Extent extent) { - return new BlockMaskBuilder().addAll(b -> b.getMaterial().isLiquid()).build(extent); - } - - @Command( - name = "#dregion", - aliases = {"#dselection", "#dsel"}, - desc = "inside the player's selection" - ) - public Mask dregion() { - return new RegionMask(new RequestSelection()); - } - - @Command( - name = "#region", - aliases = {"#selection", "#sel"}, - desc = "inside the provided selection" - ) - public Mask selection(Player player, LocalSession session) throws IncompleteRegionException { - return new RegionMask(session.getSelection(player.getWorld()).clone()); - } - - @Command( - name = "#xaxis", - desc = "Restrict to initial x axis" - ) - public Mask xaxis() { - return new XAxisMask(); - } - - @Command( - name = "#yaxis", - desc = "Restrict to initial y axis" - ) - public Mask yaxis() { - return new YAxisMask(); - } - - @Command( - name = "#zaxis", - desc = "Restrict to initial z axis" - ) - public Mask zaxis() { - return new ZAxisMask(); - } - - @Command( - name = "#id", - desc = "Restrict to initial id" - ) - public Mask id(Extent extent) { - return new IdMask(extent); - } - - @Command( - name = "#data", - desc = "Restrict to initial data" - ) - public Mask data(Extent extent) { - return new DataMask(extent); - } - - @Command( - name = "#iddata", - desc = "Restrict to initial block id and data" - ) - public Mask iddata(Extent extent) { - return new IdDataMask(extent); - } - - @Command( - name = "#air", - desc = "Restrict to types of air" - ) - public Mask air(Extent extent) { - return new BlockMaskBuilder().addAll(b -> b.getMaterial().isAir()).build(extent); - } - - @Command( - name = "#wall", - desc = "Restrict to walls (any block n,e,s,w of air)" - ) - public Mask wall(Extent extent) { - Mask blockMask = air(extent); - return new MaskUnion(new ExistingBlockMask(extent), new WallMask(blockMask, 1, 8)); - } - - @Command( - name = "#surface", - desc = "Restrict to surfaces (any solid block touching air)" - ) - public Mask surface(Extent extent) { - return new SurfaceMask(extent); - } - - @Command( - name = "\\", - aliases = {"/", "#angle", "#\\", "#/"}, - desc = "Restrict to specific terrain angle", - descFooter = "Restrict to specific terrain angle\n" + - "The -o flag will only overlay\n" + - "Example: /[0d][45d]\n" + - "Explanation: Allows any block where the adjacent block is between 0 and 45 degrees.\n" + - "Example: /[3][20]\n" + - "Explanation: Allows any block where the adjacent block is between 3 and 20 blocks below" -) - public Mask angle(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "1") int distanceOpt) throws ExpressionException { - double y1, y2; - boolean override; - if (maxStr.endsWith("d")) { - double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate(); - double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate(); - y1 = Math.tan(y1d * (Math.PI / 180)); - y2 = Math.tan(y2d * (Math.PI / 180)); - } else { - y1 = Expression.compile(minStr).evaluate(); - y2 = Expression.compile(maxStr).evaluate(); - } - return new AngleMask(extent, y1, y2, overlay, distanceOpt); - } - - @Command( - name = "(", - aliases = {")", "#roc", "#(", "#)"}, - desc = "Restrict to near specific terrain slope rate of change", - descFooter = "Restrict to near specific terrain slope rate of change\n" + - "The -o flag will only overlay\n" + - "Example: ([0d][45d][5]\n" + - "Explanation: Restrict near where the angle changes between 0-45 degrees within 5 blocks\n" + - "Note: Use negatives for decreasing slope" -) - public Mask roc(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "4") int distanceOpt) throws ExpressionException { - double y1, y2; - boolean override; - if (maxStr.endsWith("d")) { - double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate(); - double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate(); - y1 = Math.tan(y1d * (Math.PI / 180)); - y2 = Math.tan(y2d * (Math.PI / 180)); - } else { - y1 = Expression.compile(minStr).evaluate(); - y2 = Expression.compile(maxStr).evaluate(); - } - return new ROCAngleMask(extent, y1, y2, overlay, distanceOpt); - } - - @Command( - name = "^", - aliases = {"#extrema", "#^"}, - desc = "Restrict to near specific terrain extrema", - descFooter = "Restrict to near specific terrain extrema\n" + - "The -o flag will only overlay\n" + - "Example: ([0d][45d][5]\n" + - "Explanation: Restrict to near 45 degrees of local maxima\n" + - "Note: Use negatives for local minima" -) - public Mask extrema(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "4") int distanceOpt) throws ExpressionException { - double y1, y2; - boolean override; - if (maxStr.endsWith("d")) { - double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate(); - double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate(); - y1 = Math.tan(y1d * (Math.PI / 180)); - y2 = Math.tan(y2d * (Math.PI / 180)); - } else { - y1 = Expression.compile(minStr).evaluate(); - y2 = Expression.compile(maxStr).evaluate(); - } - return new ExtremaMask(extent, y1, y2, overlay, distanceOpt); - } - - @Command( - name = "{", - aliases = {"#{"}, - desc = "Restricts blocks to within a specific radius range of the initial block" -) - public Mask radius(@Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) throws ExpressionException { - return new RadiusMask((int) minInt, (int) maxInt); - } - - @Command( - name = "|", - aliases = {"#|", "#side"}, - desc = "sides with a specific number of other blocks" -) - public Mask wall(@Arg(desc = "Mask") Mask mask, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) throws ExpressionException { - return new WallMask(mask, (int) minInt, (int) maxInt); - } - - @Command( - name = "~", - aliases = {"#~", "#adjacent"}, - desc = "Adjacent to a specific number of other blocks" -) - public Mask adjacent(@Arg(desc = "Mask") Mask mask, @Arg(name = "min", desc = "double", def = "-1") double min, @Arg(name = "max", desc = "double", def = "-1") double max) throws ExpressionException { - if (min == -1 && max == -1) { - min = 1; - max = 8; - } else if (max == -1) max = min; - if (max >= 8 && min == 1) { - return new AdjacentAnyMask(mask); - } - return new AdjacentMask(mask, (int) min, (int) max); - } - - @Command( - name = "<", - aliases = {"#<", "#below"}, - desc = "below a specific block" -) - public Mask below(@Arg(desc = "Mask") Mask mask) throws ExpressionException { - OffsetMask offsetMask = new OffsetMask(mask, BlockVector3.at(0, 1, 0)); - return new MaskIntersection(offsetMask, Masks.negate(mask)); - } - - @Command( - name = ">", - aliases = {"#>", "#above"}, - desc = "above a specific block" -) - public Mask above(@Arg(desc = "Mask") Mask mask) throws ExpressionException { - OffsetMask offsetMask = new OffsetMask(mask, BlockVector3.at(0, -1, 0)); - return new MaskIntersection(offsetMask, Masks.negate(mask)); - } - - @Command( - name = "$", - aliases = {"#biome", "#$"}, - desc = "in a specific biome", - descFooter = "in a specific biome. For a list of biomes use //biomelist" -) - public Mask biome(Extent extent, @Arg(desc = "BiomeType") BiomeType biome) throws ExpressionException { - return new BiomeMask(extent, biome); - } - - @Command( - name = "%", - aliases = {"#%", "#percent"}, - desc = "percentage chance" -) - public Mask random(@Arg(desc = "double chance") double chance) throws ExpressionException { - chance = chance / 100; - return new RandomMask(chance); - } - - @Command( - name = "=", - aliases = {"#=", "#expression"}, - desc = "expression mask" -) - public Mask expression(Extent extent, @Arg(desc = "String expression") String input) throws ExpressionException { - Expression exp = Expression.compile(input, "x", "y", "z"); - ExpressionEnvironment env = new WorldEditExpressionEnvironment(extent, Vector3.ONE, Vector3.ZERO); - exp.setEnvironment(env); - return new ExpressionMask(exp); - } - - @Command( - name = "!", - aliases = {"#not", "#negate", "#!"}, - desc = "Negate another mask" -) - public Mask negate(@Arg(desc = "Mask") Mask mask) throws ExpressionException { - return Masks.negate(mask); - } -} +// public Mask angle(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "1") int distanceOpt) throws ExpressionException { +// double y1, y2; +// boolean override; +// if (maxStr.endsWith("d")) { +// double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate(); +// double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate(); +// y1 = Math.tan(y1d * (Math.PI / 180)); +// y2 = Math.tan(y2d * (Math.PI / 180)); +// } else { +// y1 = Expression.compile(minStr).evaluate(); +// y2 = Expression.compile(maxStr).evaluate(); +// } +// return new AngleMask(extent, y1, y2, overlay, distanceOpt); +// } +// +// @Command( +// name = "(", +// aliases = {")", "#roc", "#(", "#)"}, +// desc = "Restrict to near specific terrain slope rate of change", +// descFooter = "Restrict to near specific terrain slope rate of change\n" + +// "The -o flag will only overlay\n" + +// "Example: ([0d][45d][5]\n" + +// "Explanation: Restrict near where the angle changes between 0-45 degrees within 5 blocks\n" + +// "Note: Use negatives for decreasing slope" +//) +// public Mask roc(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "4") int distanceOpt) throws ExpressionException { +// double y1, y2; +// boolean override; +// if (maxStr.endsWith("d")) { +// double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate(); +// double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate(); +// y1 = Math.tan(y1d * (Math.PI / 180)); +// y2 = Math.tan(y2d * (Math.PI / 180)); +// } else { +// y1 = Expression.compile(minStr).evaluate(); +// y2 = Expression.compile(maxStr).evaluate(); +// } +// return new ROCAngleMask(extent, y1, y2, overlay, distanceOpt); +// } +// +// @Command( +// name = "^", +// aliases = {"#extrema", "#^"}, +// desc = "Restrict to near specific terrain extrema", +// descFooter = "Restrict to near specific terrain extrema\n" + +// "The -o flag will only overlay\n" + +// "Example: ([0d][45d][5]\n" + +// "Explanation: Restrict to near 45 degrees of local maxima\n" + +// "Note: Use negatives for local minima" +//) +// public Mask extrema(Extent extent, @Arg(name="min", desc = "min angle") String minStr, @Arg(name="max", desc = "max angle") String maxStr, @Switch(name = 'o', desc = "TODO") boolean overlay, @Arg(name = "distance", desc = "int", def = "4") int distanceOpt) throws ExpressionException { +// double y1, y2; +// boolean override; +// if (maxStr.endsWith("d")) { +// double y1d = Expression.compile(minStr.substring(0, minStr.length() - 1)).evaluate(); +// double y2d = Expression.compile(maxStr.substring(0, maxStr.length() - 1)).evaluate(); +// y1 = Math.tan(y1d * (Math.PI / 180)); +// y2 = Math.tan(y2d * (Math.PI / 180)); +// } else { +// y1 = Expression.compile(minStr).evaluate(); +// y2 = Expression.compile(maxStr).evaluate(); +// } +// return new ExtremaMask(extent, y1, y2, overlay, distanceOpt); +// } +// +// @Command( +// name = "{", +// aliases = {"#{"}, +// desc = "Restricts blocks to within a specific radius range of the initial block" +//) +// public Mask radius(@Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) throws ExpressionException { +// return new RadiusMask((int) minInt, (int) maxInt); +// } +// +// @Command( +// name = "|", +// aliases = {"#|", "#side"}, +// desc = "sides with a specific number of other blocks" +//) +// public Mask wall(@Arg(desc = "Mask") Mask mask, @Arg(name="mine", desc = "min light") double minInt, @Arg(name="mine", desc = "max light") double maxInt) throws ExpressionException { +// return new WallMask(mask, (int) minInt, (int) maxInt); +// } +// +// @Command( +// name = "~", +// aliases = {"#~", "#adjacent"}, +// desc = "Adjacent to a specific number of other blocks" +//) +// public Mask adjacent(@Arg(desc = "Mask") Mask mask, @Arg(name = "min", desc = "double", def = "-1") double min, @Arg(name = "max", desc = "double", def = "-1") double max) throws ExpressionException { +// if (min == -1 && max == -1) { +// min = 1; +// max = 8; +// } else if (max == -1) max = min; +// if (max >= 8 && min == 1) { +// return new AdjacentAnyMask(mask); +// } +// return new AdjacentMask(mask, (int) min, (int) max); +// } +// +// @Command( +// name = "<", +// aliases = {"#<", "#below"}, +// desc = "below a specific block" +//) +// public Mask below(@Arg(desc = "Mask") Mask mask) throws ExpressionException { +// OffsetMask offsetMask = new OffsetMask(mask, BlockVector3.at(0, 1, 0)); +// return new MaskIntersection(offsetMask, Masks.negate(mask)); +// } +// +// @Command( +// name = ">", +// aliases = {"#>", "#above"}, +// desc = "above a specific block" +//) +// public Mask above(@Arg(desc = "Mask") Mask mask) throws ExpressionException { +// OffsetMask offsetMask = new OffsetMask(mask, BlockVector3.at(0, -1, 0)); +// return new MaskIntersection(offsetMask, Masks.negate(mask)); +// } +// +// @Command( +// name = "$", +// aliases = {"#biome", "#$"}, +// desc = "in a specific biome", +// descFooter = "in a specific biome. For a list of biomes use //biomelist" +//) +// public Mask biome(Extent extent, @Arg(desc = "BiomeType") BiomeType biome) throws ExpressionException { +// return new BiomeMask(extent, biome); +// } +// +// @Command( +// name = "%", +// aliases = {"#%", "#percent"}, +// desc = "percentage chance" +//) +// public Mask random(@Arg(desc = "double chance") double chance) throws ExpressionException { +// chance = chance / 100; +// return new RandomMask(chance); +// } +// +// @Command( +// name = "=", +// aliases = {"#=", "#expression"}, +// desc = "expression mask" +//) +// public Mask expression(Extent extent, @Arg(desc = "String expression") String input) throws ExpressionException { +// Expression exp = Expression.compile(input, "x", "y", "z"); +// ExpressionEnvironment env = new WorldEditExpressionEnvironment(extent, Vector3.ONE, Vector3.ZERO); +// exp.setEnvironment(env); +// return new ExpressionMask(exp); +// } +// +// @Command( +// name = "!", +// aliases = {"#not", "#negate", "#!"}, +// desc = "Negate another mask" +//) +// public Mask negate(@Arg(desc = "Mask") Mask mask) throws ExpressionException { +// return Masks.negate(mask); +// } +//} 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 5215ee8b9..8124c52c6 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 @@ -1,403 +1,404 @@ -package com.sk89q.worldedit.command; - -import com.boydti.fawe.object.DataAnglePattern; -import com.boydti.fawe.object.clipboard.MultiClipboardHolder; -import com.boydti.fawe.object.collection.RandomCollection; -import com.boydti.fawe.object.pattern.AngleColorPattern; -import com.boydti.fawe.object.pattern.AverageColorPattern; -import com.boydti.fawe.object.pattern.BiomePattern; -import com.boydti.fawe.object.pattern.BufferedPattern; -import com.boydti.fawe.object.pattern.BufferedPattern2D; -import com.boydti.fawe.object.pattern.DataPattern; -import com.boydti.fawe.object.pattern.DesaturatePattern; -import com.boydti.fawe.object.pattern.ExistingPattern; -import com.boydti.fawe.object.pattern.ExpressionPattern; -import com.boydti.fawe.object.pattern.FullClipboardPattern; -import com.boydti.fawe.object.pattern.IdDataMaskPattern; -import com.boydti.fawe.object.pattern.IdPattern; -import com.boydti.fawe.object.pattern.Linear2DBlockPattern; -import com.boydti.fawe.object.pattern.Linear3DBlockPattern; -import com.boydti.fawe.object.pattern.LinearBlockPattern; -import com.boydti.fawe.object.pattern.MaskedPattern; -import com.boydti.fawe.object.pattern.NoXPattern; -import com.boydti.fawe.object.pattern.NoYPattern; -import com.boydti.fawe.object.pattern.NoZPattern; -import com.boydti.fawe.object.pattern.OffsetPattern; -import com.boydti.fawe.object.pattern.PropertyPattern; -import com.boydti.fawe.object.pattern.RandomFullClipboardPattern; -import com.boydti.fawe.object.pattern.RandomOffsetPattern; -import com.boydti.fawe.object.pattern.RelativePattern; -import com.boydti.fawe.object.pattern.SaturatePattern; -import com.boydti.fawe.object.pattern.ShadePattern; -import com.boydti.fawe.object.pattern.SolidRandomOffsetPattern; -import com.boydti.fawe.object.pattern.SurfaceRandomOffsetPattern; -import com.boydti.fawe.object.random.SimplexRandom; -import com.boydti.fawe.util.ColorUtil; -import com.boydti.fawe.util.TextureUtil; -import com.sk89q.worldedit.EmptyClipboardException; -import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.entity.Player; -import com.sk89q.worldedit.extension.input.InputParseException; -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.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.world.biome.BiomeType; -import java.awt.Color; -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import org.enginehub.piston.annotation.Command; -import org.enginehub.piston.annotation.CommandContainer; -import org.enginehub.piston.annotation.param.Arg; -import org.jetbrains.annotations.Range; - -//@Command(aliases = {"patterns"}, -// desc = "Help for the various patterns. [More Info](https://git.io/vSPmA)", -// descFooter = "Patterns determine what blocks are placed\n" + -// " - Use [brackets] for arguments\n" + -// " - Use , to OR multiple\n" + -// "e.g., #surfacespread[10][#existing],andesite\n" + -// "More Info: https://git.io/vSPmA" +// TODO: Ping @MattBDev to reimplement 2020-02-04 +//package com.sk89q.worldedit.command; +// +//import com.boydti.fawe.object.DataAnglePattern; +//import com.boydti.fawe.object.clipboard.MultiClipboardHolder; +//import com.boydti.fawe.object.collection.RandomCollection; +//import com.boydti.fawe.object.pattern.AngleColorPattern; +//import com.boydti.fawe.object.pattern.AverageColorPattern; +//import com.boydti.fawe.object.pattern.BiomePattern; +//import com.boydti.fawe.object.pattern.BufferedPattern; +//import com.boydti.fawe.object.pattern.BufferedPattern2D; +//import com.boydti.fawe.object.pattern.DataPattern; +//import com.boydti.fawe.object.pattern.DesaturatePattern; +//import com.boydti.fawe.object.pattern.ExistingPattern; +//import com.boydti.fawe.object.pattern.ExpressionPattern; +//import com.boydti.fawe.object.pattern.FullClipboardPattern; +//import com.boydti.fawe.object.pattern.IdDataMaskPattern; +//import com.boydti.fawe.object.pattern.IdPattern; +//import com.boydti.fawe.object.pattern.Linear2DBlockPattern; +//import com.boydti.fawe.object.pattern.Linear3DBlockPattern; +//import com.boydti.fawe.object.pattern.LinearBlockPattern; +//import com.boydti.fawe.object.pattern.MaskedPattern; +//import com.boydti.fawe.object.pattern.NoXPattern; +//import com.boydti.fawe.object.pattern.NoYPattern; +//import com.boydti.fawe.object.pattern.NoZPattern; +//import com.boydti.fawe.object.pattern.OffsetPattern; +//import com.boydti.fawe.object.pattern.PropertyPattern; +//import com.boydti.fawe.object.pattern.RandomFullClipboardPattern; +//import com.boydti.fawe.object.pattern.RandomOffsetPattern; +//import com.boydti.fawe.object.pattern.RelativePattern; +//import com.boydti.fawe.object.pattern.SaturatePattern; +//import com.boydti.fawe.object.pattern.ShadePattern; +//import com.boydti.fawe.object.pattern.SolidRandomOffsetPattern; +//import com.boydti.fawe.object.pattern.SurfaceRandomOffsetPattern; +//import com.boydti.fawe.object.random.SimplexRandom; +//import com.boydti.fawe.util.ColorUtil; +//import com.boydti.fawe.util.TextureUtil; +//import com.sk89q.worldedit.EmptyClipboardException; +//import com.sk89q.worldedit.LocalSession; +//import com.sk89q.worldedit.entity.Player; +//import com.sk89q.worldedit.extension.input.InputParseException; +//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.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.world.biome.BiomeType; +//import java.awt.Color; +//import java.io.IOException; +//import java.util.Collections; +//import java.util.List; +//import java.util.Set; +//import org.enginehub.piston.annotation.Command; +//import org.enginehub.piston.annotation.CommandContainer; +//import org.enginehub.piston.annotation.param.Arg; +//import org.jetbrains.annotations.Range; +// +////@Command(aliases = {"patterns"}, +//// desc = "Help for the various patterns. [More Info](https://git.io/vSPmA)", +//// descFooter = "Patterns determine what blocks are placed\n" + +//// " - Use [brackets] for arguments\n" + +//// " - Use , to OR multiple\n" + +//// "e.g., #surfacespread[10][#existing],andesite\n" + +//// "More Info: https://git.io/vSPmA" +////) +//@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class) +//public class PatternCommands { +// +// @Command( +// name = "#existing", +// aliases = {"#*", "*", ".*"}, +// desc = "Use the block that is already there" +// ) +// public Pattern existing(Extent extent, @Arg(desc = "String", def = "") String properties) { // TODO FIXME , @Arg(name = "properties", desc = "String", def = "") String properties +// if (properties == null) return new ExistingPattern(extent); +// return new PropertyPattern(extent).addRegex(".*[" + properties + "]"); +// } +// +// @Command( +// name = "#clipboard", +// aliases = {"#copy"}, +// desc = "Use the blocks in your clipboard as the pattern") +// public Pattern clipboard(LocalSession session) throws EmptyClipboardException { +// ClipboardHolder holder = session.getClipboard(); +// Clipboard clipboard = holder.getClipboard(); +// return new ClipboardPattern(clipboard); +// } +// +// @Command( +// name = "#simplex", +// desc = "Use simplex noise to randomize blocks. Tutorial: https://imgur.com/a/rwVAE" //) -@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class) -public class PatternCommands { - - @Command( - name = "#existing", - aliases = {"#*", "*", ".*"}, - desc = "Use the block that is already there" - ) - public Pattern existing(Extent extent, @Arg(desc = "String", def = "") String properties) { // TODO FIXME , @Arg(name = "properties", desc = "String", def = "") String properties - if (properties == null) return new ExistingPattern(extent); - return new PropertyPattern(extent).addRegex(".*[" + properties + "]"); - } - - @Command( - name = "#clipboard", - aliases = {"#copy"}, - desc = "Use the blocks in your clipboard as the pattern") - public Pattern clipboard(LocalSession session) throws EmptyClipboardException { - ClipboardHolder holder = session.getClipboard(); - Clipboard clipboard = holder.getClipboard(); - return new ClipboardPattern(clipboard); - } - - @Command( - name = "#simplex", - desc = "Use simplex noise to randomize blocks. Tutorial: https://imgur.com/a/rwVAE" -) - public Pattern simplex(@Arg(desc = "scale factor") double scale, @Arg(desc = "Pattern") Pattern other) { - if (other instanceof RandomPattern) { - scale = (1d / Math.max(1, scale)); - RandomCollection collection = ((RandomPattern) other).getCollection(); - collection.setRandom(new SimplexRandom(scale)); - } - return other; - } - - @Command( - name = "#color", - desc = "Use the block closest to a specific color" -) - public Pattern color(TextureUtil textureUtil, @Arg(desc = "String color") String color) { - Color colorObj = ColorUtil.parseColor(color); - return textureUtil.getNearestBlock(colorObj.getRGB()).getDefaultState(); - } - - @Command( - name = "#anglecolor", - desc = "A darker block based on the existing terrain angle" -) - public Pattern anglecolor(Extent extent, LocalSession session, @Arg(desc = "int", def = "1") int distance) { - return new AngleColorPattern(extent, session, distance); - } - - @Command( - name = "#angledata", - desc = "Block data based on the existing terrain angle" - ) - public Pattern angledata(Extent extent, @Arg(desc = "int", def = "1") int distance) { - return new DataAnglePattern(extent, distance); - } - - @Command( - name = "#saturate", - desc = "Saturate the existing block with a color" -) - public Pattern saturate(Extent extent, LocalSession session, @Arg(desc = "Color code") String colorStr) { - Color color = ColorUtil.parseColor(colorStr); - return new SaturatePattern(extent, color.getRGB(), session); - } - - @Command( - name = "#averagecolor", - desc = "Average between the existing block and a color" -) - public Pattern averagecolor(Extent extent, LocalSession session, @Arg(desc = "Color code") String colorStr) { - Color color = ColorUtil.parseColor(colorStr); - return new AverageColorPattern(extent, color.getRGB(), session); - } - - @Command( - name = "#desaturate", - desc = "Desaturated color of the existing block" -) - public Pattern desaturate(Extent extent, LocalSession session, @Arg(desc = "double", def = "100") double percent) { - return new DesaturatePattern(extent, percent / 100d, session); - } - - @Command( - name = "#lighten", - desc = "Lighten the existing block" -) - public Pattern lighten(Extent extent, TextureUtil util) { - return new ShadePattern(extent, false, util); - } - - @Command( - name = "#darken", - desc = "Darken the existing block" -) - public Pattern darken(Extent extent, TextureUtil util) { - return new ShadePattern(extent, true, util); - } - - @Command( - name = "#fullcopy", - desc = "Places your full clipboard at each block" -) - public Pattern fullcopy(Player player, Extent extent, LocalSession session, @Arg(desc = "String", def = "#copy") String location, @Arg(desc = "boolean", def = "false") boolean rotate, @Arg(desc = "boolean", def = "false") boolean flip) throws EmptyClipboardException, InputParseException, IOException { - List clipboards; - switch (location.toLowerCase()) { - case "#copy": - case "#clipboard": - ClipboardHolder clipboard = session.getExistingClipboard(); - if (clipboard == null) { - throw new InputParseException("To use #fullcopy, please first copy something to your clipboard"); - } - if (!rotate && !flip) { - return new FullClipboardPattern(extent, clipboard.getClipboard()); - } - clipboards = Collections.singletonList(clipboard); - break; - default: - MultiClipboardHolder multi = ClipboardFormats.loadAllFromInput(player, location, null, true); - clipboards = multi != null ? multi.getHolders() : null; - break; - } - if (clipboards == null) { - throw new InputParseException("#fullcopy:"); - } - return new RandomFullClipboardPattern(extent, clipboards, rotate, flip); - } - - @Command( - name = "#buffer", - desc = "Only place a block once while a pattern is in use", - descFooter = "Only place a block once while a pattern is in use\n" + - "Use with a brush when you don't want to apply to the same spot twice" -) - public Pattern buffer(Actor actor, @Arg(desc = "Pattern")Pattern pattern) { - return new BufferedPattern(actor, pattern); - } - - @Command( - name = "#buffer2d", - desc = "Only place a block once in a column while a pattern is in use" -) - public Pattern buffer2d(Actor actor, @Arg(desc = "Pattern")Pattern pattern) { - return new BufferedPattern2D(actor, pattern); - } - - @Command( - name = "#iddatamask", - desc = "Use the pattern's id and the existing blocks data with the provided mask", - descFooter = "Use the pattern's id and the existing blocks data with the provided mask\n" + - " - Use to replace slabs or where the data values needs to be shifted instead of set" -) - public Pattern iddatamask(Extent extent, @Range(from = 0, to = 15) @Arg(desc = "bit mask") int bitmask, @Arg(desc = "Pattern")Pattern pattern) { - - return new IdDataMaskPattern(extent, pattern, bitmask); - } - - @Command( - name = "#id", - desc = "Only change the block id" -) - public Pattern id(Extent extent, @Arg(desc = "Pattern")Pattern pattern) { - - return new IdPattern(extent, pattern); - } - - @Command( - name = "#data", - desc = "Only change the block data" -) - public Pattern data(Extent extent, @Arg(desc = "Pattern")Pattern pattern) { - - return new DataPattern(extent, pattern); - } - - @Command( - name = "#biome", - aliases = {"$"}, - desc = "Set the biome" -) - public Pattern biome(Extent extent, @Arg(desc = "Biome type") BiomeType biome) { - - return new BiomePattern(extent, biome); - } - - @Command( - name = "#relative", - aliases = {"#~", "#r", "#rel"}, - desc = "Offset the pattern to where you click" -) - public Pattern relative(@Arg(desc = "Pattern")Pattern pattern) { - - return new RelativePattern(pattern); - } - - @Command( - name = "#!x", - aliases = {"#nx", "#nox"}, - desc = "The pattern will not be provided the x axis info", - descFooter = "The pattern will not be provided the z axis info.\n" + - "Example: #!x[#!z[#~[#l3d[pattern]]]]" -) - public Pattern nox(@Arg(desc = "Pattern")Pattern pattern) { - - return new NoXPattern(pattern); - } - - @Command( - name = "#!y", - aliases = {"#ny", "#noy"}, - desc = "The pattern will not be provided the y axis info" -) - public Pattern noy(@Arg(desc = "Pattern")Pattern pattern) { - - return new NoYPattern(pattern); - } - - @Command( - name = "#!z", - aliases = {"#nz", "#noz"}, - desc = "The pattern will not be provided the z axis info" -) - public Pattern noz(@Arg(desc = "Pattern")Pattern pattern) { - - return new NoZPattern(pattern); - } - - @Command( - name = "#mask", - desc = "Apply a pattern depending on a mask" -) - public Pattern mask(@Arg(desc = "Mask") Mask mask, @Arg(desc = "Pattern")Pattern pass, @Arg(desc = "Pattern")Pattern fail) { - return new MaskedPattern(mask, pass, fail); - } - - @Command( - name = "#offset", - desc = "Offset a pattern" -) - public Pattern offset(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) { - - return new OffsetPattern(pattern, (int) x, (int) y, (int) z); - } - - @Command( - name = "#surfacespread", - desc = "Applies to only blocks on a surface. Selects a block from provided pattern with a given randomized offset `[0, )`. e.g., Use `#existing` to randomly offset blocks in the world, or `#copy` to offset blocks in your clipboard" -) - public Pattern surfacespread(@Arg(desc = "spread distance (blocks)") double distance, @Arg(desc = "Pattern")Pattern pattern) { - - return new SurfaceRandomOffsetPattern(pattern, (int) distance); - } - - @Command( - name = "#solidspread", - desc = "Randomly spread solid blocks" -) - public Pattern solidspread(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) { - - return new SolidRandomOffsetPattern(pattern, (int) x, (int) y, (int) z); - } - - @Command( - name = "#spread", - aliases = {"#randomoffset"}, - desc = "Randomly spread blocks" -) - public Pattern spread(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) { - - return new RandomOffsetPattern(pattern, (int) x, (int) y, (int) z); - } - - @Command( - name = "#linear", - aliases = {"#l"}, - desc = "Sequentially set blocks from a list of patterns" -) - public Pattern linear(@Arg(desc = "Pattern") Pattern other) { - - if (other instanceof RandomPattern) { - Set patterns = ((RandomPattern) other).getPatterns(); - return new LinearBlockPattern(patterns.toArray(new Pattern[patterns.size()])); - } - return other; - } - - @Command( - name = "#linear3d", - aliases = {"#l3d"}, - desc = "Use the x,y,z coordinate to pick a block from the list" -) - public Pattern linear3d(@Arg(desc = "Pattern") Pattern other) { - - if (other instanceof RandomPattern) { - Set patterns = ((RandomPattern) other).getPatterns(); - return new Linear3DBlockPattern(patterns.toArray(new Pattern[patterns.size()])); - } - return other; - } - - @Command( - name = "#linear2d", - aliases = {"#l2d"}, - desc = "Use the x,z coordinate to pick a block from the list" -) - public Pattern linear2d(@Arg(desc = "Pattern") Pattern other) { - - if (other instanceof RandomPattern) { - Set patterns = ((RandomPattern) other).getPatterns(); - return new Linear2DBlockPattern(patterns.toArray(new Pattern[patterns.size()])); - } - return other; - } - - @Command( - name = "=", - aliases = {"#=", "#expression"}, - desc = "Expression pattern: http://wiki.sk89q.com/wiki/WorldEdit/Expression_syntax" -) - public Pattern expression(Extent extent, @Arg(desc = "Expression") String input) throws ExpressionException { - - Expression exp = Expression.compile(input, "x", "y", "z"); - WorldEditExpressionEnvironment env = new WorldEditExpressionEnvironment(extent, Vector3.ONE, Vector3.ZERO); - exp.setEnvironment(env); - return new ExpressionPattern(exp); - } -} +// public Pattern simplex(@Arg(desc = "scale factor") double scale, @Arg(desc = "Pattern") Pattern other) { +// if (other instanceof RandomPattern) { +// scale = (1d / Math.max(1, scale)); +// RandomCollection collection = ((RandomPattern) other).getCollection(); +// collection.setRandom(new SimplexRandom(scale)); +// } +// return other; +// } +// +// @Command( +// name = "#color", +// desc = "Use the block closest to a specific color" +//) +// public Pattern color(TextureUtil textureUtil, @Arg(desc = "String color") String color) { +// Color colorObj = ColorUtil.parseColor(color); +// return textureUtil.getNearestBlock(colorObj.getRGB()).getDefaultState(); +// } +// +// @Command( +// name = "#anglecolor", +// desc = "A darker block based on the existing terrain angle" +//) +// public Pattern anglecolor(Extent extent, LocalSession session, @Arg(desc = "int", def = "1") int distance) { +// return new AngleColorPattern(extent, session, distance); +// } +// +// @Command( +// name = "#angledata", +// desc = "Block data based on the existing terrain angle" +// ) +// public Pattern angledata(Extent extent, @Arg(desc = "int", def = "1") int distance) { +// return new DataAnglePattern(extent, distance); +// } +// +// @Command( +// name = "#saturate", +// desc = "Saturate the existing block with a color" +//) +// public Pattern saturate(Extent extent, LocalSession session, @Arg(desc = "Color code") String colorStr) { +// Color color = ColorUtil.parseColor(colorStr); +// return new SaturatePattern(extent, color.getRGB(), session); +// } +// +// @Command( +// name = "#averagecolor", +// desc = "Average between the existing block and a color" +//) +// public Pattern averagecolor(Extent extent, LocalSession session, @Arg(desc = "Color code") String colorStr) { +// Color color = ColorUtil.parseColor(colorStr); +// return new AverageColorPattern(extent, color.getRGB(), session); +// } +// +// @Command( +// name = "#desaturate", +// desc = "Desaturated color of the existing block" +//) +// public Pattern desaturate(Extent extent, LocalSession session, @Arg(desc = "double", def = "100") double percent) { +// return new DesaturatePattern(extent, percent / 100d, session); +// } +// +// @Command( +// name = "#lighten", +// desc = "Lighten the existing block" +//) +// public Pattern lighten(Extent extent, TextureUtil util) { +// return new ShadePattern(extent, false, util); +// } +// +// @Command( +// name = "#darken", +// desc = "Darken the existing block" +//) +// public Pattern darken(Extent extent, TextureUtil util) { +// return new ShadePattern(extent, true, util); +// } +// +// @Command( +// name = "#fullcopy", +// desc = "Places your full clipboard at each block" +//) +// public Pattern fullcopy(Player player, Extent extent, LocalSession session, @Arg(desc = "String", def = "#copy") String location, @Arg(desc = "boolean", def = "false") boolean rotate, @Arg(desc = "boolean", def = "false") boolean flip) throws EmptyClipboardException, InputParseException, IOException { +// List clipboards; +// switch (location.toLowerCase()) { +// case "#copy": +// case "#clipboard": +// ClipboardHolder clipboard = session.getExistingClipboard(); +// if (clipboard == null) { +// throw new InputParseException("To use #fullcopy, please first copy something to your clipboard"); +// } +// if (!rotate && !flip) { +// return new FullClipboardPattern(extent, clipboard.getClipboard()); +// } +// clipboards = Collections.singletonList(clipboard); +// break; +// default: +// MultiClipboardHolder multi = ClipboardFormats.loadAllFromInput(player, location, null, true); +// clipboards = multi != null ? multi.getHolders() : null; +// break; +// } +// if (clipboards == null) { +// throw new InputParseException("#fullcopy:"); +// } +// return new RandomFullClipboardPattern(extent, clipboards, rotate, flip); +// } +// +// @Command( +// name = "#buffer", +// desc = "Only place a block once while a pattern is in use", +// descFooter = "Only place a block once while a pattern is in use\n" + +// "Use with a brush when you don't want to apply to the same spot twice" +//) +// public Pattern buffer(Actor actor, @Arg(desc = "Pattern")Pattern pattern) { +// return new BufferedPattern(actor, pattern); +// } +// +// @Command( +// name = "#buffer2d", +// desc = "Only place a block once in a column while a pattern is in use" +//) +// public Pattern buffer2d(Actor actor, @Arg(desc = "Pattern")Pattern pattern) { +// return new BufferedPattern2D(actor, pattern); +// } +// +// @Command( +// name = "#iddatamask", +// desc = "Use the pattern's id and the existing blocks data with the provided mask", +// descFooter = "Use the pattern's id and the existing blocks data with the provided mask\n" + +// " - Use to replace slabs or where the data values needs to be shifted instead of set" +//) +// public Pattern iddatamask(Extent extent, @Range(from = 0, to = 15) @Arg(desc = "bit mask") int bitmask, @Arg(desc = "Pattern")Pattern pattern) { +// +// return new IdDataMaskPattern(extent, pattern, bitmask); +// } +// +// @Command( +// name = "#id", +// desc = "Only change the block id" +//) +// public Pattern id(Extent extent, @Arg(desc = "Pattern")Pattern pattern) { +// +// return new IdPattern(extent, pattern); +// } +// +// @Command( +// name = "#data", +// desc = "Only change the block data" +//) +// public Pattern data(Extent extent, @Arg(desc = "Pattern")Pattern pattern) { +// +// return new DataPattern(extent, pattern); +// } +// +// @Command( +// name = "#biome", +// aliases = {"$"}, +// desc = "Set the biome" +//) +// public Pattern biome(Extent extent, @Arg(desc = "Biome type") BiomeType biome) { +// +// return new BiomePattern(extent, biome); +// } +// +// @Command( +// name = "#relative", +// aliases = {"#~", "#r", "#rel"}, +// desc = "Offset the pattern to where you click" +//) +// public Pattern relative(@Arg(desc = "Pattern")Pattern pattern) { +// +// return new RelativePattern(pattern); +// } +// +// @Command( +// name = "#!x", +// aliases = {"#nx", "#nox"}, +// desc = "The pattern will not be provided the x axis info", +// descFooter = "The pattern will not be provided the z axis info.\n" + +// "Example: #!x[#!z[#~[#l3d[pattern]]]]" +//) +// public Pattern nox(@Arg(desc = "Pattern")Pattern pattern) { +// +// return new NoXPattern(pattern); +// } +// +// @Command( +// name = "#!y", +// aliases = {"#ny", "#noy"}, +// desc = "The pattern will not be provided the y axis info" +//) +// public Pattern noy(@Arg(desc = "Pattern")Pattern pattern) { +// +// return new NoYPattern(pattern); +// } +// +// @Command( +// name = "#!z", +// aliases = {"#nz", "#noz"}, +// desc = "The pattern will not be provided the z axis info" +//) +// public Pattern noz(@Arg(desc = "Pattern")Pattern pattern) { +// +// return new NoZPattern(pattern); +// } +// +// @Command( +// name = "#mask", +// desc = "Apply a pattern depending on a mask" +//) +// public Pattern mask(@Arg(desc = "Mask") Mask mask, @Arg(desc = "Pattern")Pattern pass, @Arg(desc = "Pattern")Pattern fail) { +// return new MaskedPattern(mask, pass, fail); +// } +// +// @Command( +// name = "#offset", +// desc = "Offset a pattern" +//) +// public Pattern offset(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) { +// +// return new OffsetPattern(pattern, (int) x, (int) y, (int) z); +// } +// +// @Command( +// name = "#surfacespread", +// desc = "Applies to only blocks on a surface. Selects a block from provided pattern with a given randomized offset `[0, )`. e.g., Use `#existing` to randomly offset blocks in the world, or `#copy` to offset blocks in your clipboard" +//) +// public Pattern surfacespread(@Arg(desc = "spread distance (blocks)") double distance, @Arg(desc = "Pattern")Pattern pattern) { +// +// return new SurfaceRandomOffsetPattern(pattern, (int) distance); +// } +// +// @Command( +// name = "#solidspread", +// desc = "Randomly spread solid blocks" +//) +// public Pattern solidspread(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) { +// +// return new SolidRandomOffsetPattern(pattern, (int) x, (int) y, (int) z); +// } +// +// @Command( +// name = "#spread", +// aliases = {"#randomoffset"}, +// desc = "Randomly spread blocks" +//) +// public Pattern spread(@Arg(desc = "x offset") double x, @Arg(desc = "y offset") double y, @Arg(desc = "z offset") double z, @Arg(desc = "Pattern")Pattern pattern) { +// +// return new RandomOffsetPattern(pattern, (int) x, (int) y, (int) z); +// } +// +// @Command( +// name = "#linear", +// aliases = {"#l"}, +// desc = "Sequentially set blocks from a list of patterns" +//) +// public Pattern linear(@Arg(desc = "Pattern") Pattern other) { +// +// if (other instanceof RandomPattern) { +// Set patterns = ((RandomPattern) other).getPatterns(); +// return new LinearBlockPattern(patterns.toArray(new Pattern[patterns.size()])); +// } +// return other; +// } +// +// @Command( +// name = "#linear3d", +// aliases = {"#l3d"}, +// desc = "Use the x,y,z coordinate to pick a block from the list" +//) +// public Pattern linear3d(@Arg(desc = "Pattern") Pattern other) { +// +// if (other instanceof RandomPattern) { +// Set patterns = ((RandomPattern) other).getPatterns(); +// return new Linear3DBlockPattern(patterns.toArray(new Pattern[patterns.size()])); +// } +// return other; +// } +// +// @Command( +// name = "#linear2d", +// aliases = {"#l2d"}, +// desc = "Use the x,z coordinate to pick a block from the list" +//) +// public Pattern linear2d(@Arg(desc = "Pattern") Pattern other) { +// +// if (other instanceof RandomPattern) { +// Set patterns = ((RandomPattern) other).getPatterns(); +// return new Linear2DBlockPattern(patterns.toArray(new Pattern[patterns.size()])); +// } +// return other; +// } +// +// @Command( +// name = "=", +// aliases = {"#=", "#expression"}, +// desc = "Expression pattern: http://wiki.sk89q.com/wiki/WorldEdit/Expression_syntax" +//) +// public Pattern expression(Extent extent, @Arg(desc = "Expression") String input) throws ExpressionException { +// +// Expression exp = Expression.compile(input, "x", "y", "z"); +// 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/ToolUtilCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ToolUtilCommands.java index 9aa1bfbf9..62733ab96 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/ToolUtilCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/ToolUtilCommands.java @@ -84,7 +84,6 @@ public class ToolUtilCommands { if (maskOpt == null) { player.printInfo(TranslatableComponent.of("worldedit.tool.mask.disabled")); tool.setMask(null); - return; } else { BrushSettings settings = offHand ? tool.getOffHand() : tool.getContext(); String lastArg = Iterables.getLast(CommandArgParser.spaceSplit(arguments.get())) @@ -150,18 +149,7 @@ public class ToolUtilCommands { session.getBrushTool(player, false).setSize(size); player.printInfo(TranslatableComponent.of("worldedit.tool.size.set")); } - - //todo none should be moved to the same class where it is in upstream - @Command( - name = "none", - aliases = {"/none"}, - desc = "Unbind a bound tool from your current item" - ) - public void none(Player player, LocalSession session) throws WorldEditException { - session.setTool(player, null); - player.print(TranslatableComponent.of("fawe.worldedit.tool.tool.none")); - } - + @Command( name = "tracemask", aliases = {"tarmask", "tm", "targetmask"}, @@ -368,31 +356,32 @@ public class ToolUtilCommands { player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.source.mask")); } - @Command( - name = "transform", - desc = "Set the brush transform" - ) - @CommandPermissions({"worldedit.brush.options.transform", "worldedit.transform.brush"}) - public void transform(Player player, LocalSession session, EditSession editSession, - @Arg(desc = "The transform", def = "") ResettableExtent transform, - @Switch(name = 'h', desc = "TODO") - boolean offHand, - Arguments arguments) throws WorldEditException { - BrushTool tool = session.getBrushTool(player, false); - if (tool == null) { - player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.none")); - return; - } - if (transform == null) { - player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.transform.disabled")); - tool.setTransform(null); - return; - } - BrushSettings settings = offHand ? tool.getOffHand() : tool.getContext(); - String lastArg = Iterables.getLast(CommandArgParser.spaceSplit(arguments.get())).getSubstring(); - settings.addSetting(BrushSettings.SettingType.TRANSFORM, lastArg); - settings.setTransform(transform); - tool.update(); - player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.transform")); - } + // TODO: Ping @MattBDev to reimplement 2020-02-04 +// @Command( +// name = "transform", +// desc = "Set the brush transform" +// ) +// @CommandPermissions({"worldedit.brush.options.transform", "worldedit.transform.brush"}) +// public void transform(Player player, LocalSession session, EditSession editSession, +// @Arg(desc = "The transform", def = "") ResettableExtent transform, +// @Switch(name = 'h', desc = "TODO") +// boolean offHand, +// Arguments arguments) throws WorldEditException { +// BrushTool tool = session.getBrushTool(player, false); +// if (tool == null) { +// player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.none")); +// return; +// } +// if (transform == null) { +// player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.transform.disabled")); +// tool.setTransform(null); +// return; +// } +// BrushSettings settings = offHand ? tool.getOffHand() : tool.getContext(); +// String lastArg = Iterables.getLast(CommandArgParser.spaceSplit(arguments.get())).getSubstring(); +// settings.addSetting(BrushSettings.SettingType.TRANSFORM, lastArg); +// settings.setTransform(transform); +// tool.update(); +// player.print(TranslatableComponent.of("fawe.worldedit.brush.brush.transform")); +// } } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/TransformCommands.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/TransformCommands.java index dc28b2751..db631711a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/TransformCommands.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/TransformCommands.java @@ -1,104 +1,105 @@ -package com.sk89q.worldedit.command; - -import com.boydti.fawe.object.extent.Linear3DTransform; -import com.boydti.fawe.object.extent.LinearTransform; -import com.boydti.fawe.object.extent.OffsetExtent; -import com.boydti.fawe.object.extent.PatternTransform; -import com.boydti.fawe.object.extent.RandomOffsetTransform; -import com.boydti.fawe.object.extent.RandomTransform; -import com.boydti.fawe.object.extent.ResettableExtent; -import com.boydti.fawe.object.extent.ScaleTransform; -import com.boydti.fawe.object.extent.TransformExtent; -import com.boydti.fawe.util.ExtentTraverser; -import com.sk89q.worldedit.LocalSession; -import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; -import com.sk89q.worldedit.entity.Player; -import com.sk89q.worldedit.extension.platform.Actor; -import com.sk89q.worldedit.extent.transform.BlockTransformExtent; -import com.sk89q.worldedit.function.pattern.Pattern; -import com.sk89q.worldedit.math.transform.AffineTransform; -import java.util.Set; -import org.enginehub.piston.annotation.Command; -import org.enginehub.piston.annotation.CommandContainer; -import org.enginehub.piston.annotation.param.Arg; - -@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class) -public class TransformCommands { - - @Command( - name = "#linear", - aliases = {"#l"}, - desc = "Sequentially pick from a list of transform" - ) - public ResettableExtent linear(Actor actor, LocalSession session, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { - if (other instanceof RandomTransform) { - Set extents = ((RandomTransform) other).getExtents(); - return new LinearTransform(extents.toArray(new ResettableExtent[0])); - } - return other; - } - - @Command( - name = "#linear3d", - aliases = {"#l3d"}, - desc = "Use the x,y,z coordinate to pick a transform from the list" - ) - public ResettableExtent linear3d(Actor actor, LocalSession session, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { - if (other instanceof RandomTransform) { - Set extents = ((RandomTransform) other).getExtents(); - return new Linear3DTransform(extents.toArray(new ResettableExtent[0])); - } - return other; - } - - @Command( - name = "#pattern", - desc = "Always use a specific pattern" - ) - public ResettableExtent pattern(Actor actor, LocalSession session, @Arg(desc = "Pattern") Pattern pattern, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { - return new PatternTransform(other, pattern); - } - - @Command( - name = "#offset", - desc = "Offset transform" - ) - public ResettableExtent offset(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { - return new OffsetExtent(other, (int) x, (int) y, (int) z); - } - - @Command( - name = "#spread", - aliases = {"#randomoffset"}, - desc = "Random offset transform" -) - public ResettableExtent randomOffset(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { - return new RandomOffsetTransform(other, (int) x, (int) y, (int) z); - } - - @Command( - name = "#scale", - desc = "All changes will be scaled" - ) - public ResettableExtent scale(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { - return new ScaleTransform(other, x, y, z); - } - - @Command( - name = "#rotate", - desc = "All changes will be rotate around the initial position" - ) - public ResettableExtent rotate(Player player, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { - ExtentTraverser traverser = new ExtentTraverser<>(other).find(TransformExtent.class); - BlockTransformExtent affine = traverser != null ? traverser.get() : null; - if (affine == null) { - other = affine = new TransformExtent(other); - } - AffineTransform transform = (AffineTransform) affine.getTransform(); - transform = transform.rotateX(x); - transform = transform.rotateY(y); - transform = transform.rotateZ(z); - affine.setTransform(transform); - return other; - } -} +// TODO: Ping @MattBDev to reimplement 2020-02-04 +//package com.sk89q.worldedit.command; +// +//import com.boydti.fawe.object.extent.Linear3DTransform; +//import com.boydti.fawe.object.extent.LinearTransform; +//import com.boydti.fawe.object.extent.OffsetExtent; +//import com.boydti.fawe.object.extent.PatternTransform; +//import com.boydti.fawe.object.extent.RandomOffsetTransform; +//import com.boydti.fawe.object.extent.RandomTransform; +//import com.boydti.fawe.object.extent.ResettableExtent; +//import com.boydti.fawe.object.extent.ScaleTransform; +//import com.boydti.fawe.object.extent.TransformExtent; +//import com.boydti.fawe.util.ExtentTraverser; +//import com.sk89q.worldedit.LocalSession; +//import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; +//import com.sk89q.worldedit.entity.Player; +//import com.sk89q.worldedit.extension.platform.Actor; +//import com.sk89q.worldedit.extent.transform.BlockTransformExtent; +//import com.sk89q.worldedit.function.pattern.Pattern; +//import com.sk89q.worldedit.math.transform.AffineTransform; +//import java.util.Set; +//import org.enginehub.piston.annotation.Command; +//import org.enginehub.piston.annotation.CommandContainer; +//import org.enginehub.piston.annotation.param.Arg; +// +//@CommandContainer//(superTypes = CommandPermissionsConditionGenerator.Registration.class) +//public class TransformCommands { +// +// @Command( +// name = "#linear", +// aliases = {"#l"}, +// desc = "Sequentially pick from a list of transform" +// ) +// public ResettableExtent linear(Actor actor, LocalSession session, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { +// if (other instanceof RandomTransform) { +// Set extents = ((RandomTransform) other).getExtents(); +// return new LinearTransform(extents.toArray(new ResettableExtent[0])); +// } +// return other; +// } +// +// @Command( +// name = "#linear3d", +// aliases = {"#l3d"}, +// desc = "Use the x,y,z coordinate to pick a transform from the list" +// ) +// public ResettableExtent linear3d(Actor actor, LocalSession session, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { +// if (other instanceof RandomTransform) { +// Set extents = ((RandomTransform) other).getExtents(); +// return new Linear3DTransform(extents.toArray(new ResettableExtent[0])); +// } +// return other; +// } +// +// @Command( +// name = "#pattern", +// desc = "Always use a specific pattern" +// ) +// public ResettableExtent pattern(Actor actor, LocalSession session, @Arg(desc = "Pattern") Pattern pattern, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { +// return new PatternTransform(other, pattern); +// } +// +// @Command( +// name = "#offset", +// desc = "Offset transform" +// ) +// public ResettableExtent offset(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { +// return new OffsetExtent(other, (int) x, (int) y, (int) z); +// } +// +// @Command( +// name = "#spread", +// aliases = {"#randomoffset"}, +// desc = "Random offset transform" +//) +// public ResettableExtent randomOffset(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { +// return new RandomOffsetTransform(other, (int) x, (int) y, (int) z); +// } +// +// @Command( +// name = "#scale", +// desc = "All changes will be scaled" +// ) +// public ResettableExtent scale(Actor actor, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { +// return new ScaleTransform(other, x, y, z); +// } +// +// @Command( +// name = "#rotate", +// desc = "All changes will be rotate around the initial position" +// ) +// public ResettableExtent rotate(Player player, LocalSession session, double x, double y, double z, @Arg(name = "other", desc = "ResettableExtent", def = "#null") ResettableExtent other) { +// ExtentTraverser traverser = new ExtentTraverser<>(other).find(TransformExtent.class); +// BlockTransformExtent affine = traverser != null ? traverser.get() : null; +// if (affine == null) { +// other = affine = new TransformExtent(other); +// } +// AffineTransform transform = (AffineTransform) affine.getTransform(); +// transform = transform.rotateX(x); +// transform = transform.rotateY(y); +// transform = transform.rotateZ(z); +// affine.setTransform(transform); +// return other; +// } +//} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/RegistryConverter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/RegistryConverter.java index 83999afa1..71b82aef4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/RegistryConverter.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/argument/RegistryConverter.java @@ -104,7 +104,6 @@ public final class RegistryConverter implements ArgumentConvert : SuccessfulConversion.fromSingle(result); } - @Override public List getSuggestions(String input) { return SuggestionHelper.getRegistrySuggestions(registry, input).collect(Collectors.toList()); } 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 ce02f08e3..6a86136e9 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 @@ -125,38 +125,39 @@ public class BrushTool implements DoubleActionTraceTool, ScrollTool, MovableTool public BrushTool() { } - public static BrushTool fromString(Player player, LocalSession session, String json) throws CommandException, InputParseException { - Gson gson = new Gson(); - Type type = new TypeToken>() { - }.getType(); - Map root = gson.fromJson(json, type); - if (root == null) { - getLogger(BrushTool.class).debug("Failed to load " + json); - return new BrushTool(); - } - Map primary = (Map) root.get("primary"); - Map secondary = (Map) root.getOrDefault("secondary", primary); - - VisualMode visual = VisualMode.valueOf((String) root.getOrDefault("visual", "NONE")); - TargetMode target = TargetMode.valueOf((String) root.getOrDefault("target", "TARGET_BLOCK_RANGE")); - int range = ((Number) root.getOrDefault("range", -1)).intValue(); - int offset = ((Number) root.getOrDefault("offset", 0)).intValue(); - - BrushTool tool = new BrushTool(); - tool.visualMode = visual; - tool.targetMode = target; - tool.range = range; - tool.targetOffset = offset; - - BrushSettings primarySettings = BrushSettings.get(tool, player, session, primary); - tool.setPrimary(primarySettings); - if (primary != secondary) { - BrushSettings secondarySettings = BrushSettings.get(tool, player, session, secondary); - tool.setSecondary(secondarySettings); - } - - return tool; - } + // TODO: Ping @MattBDev to reimplement 2020-02-04 +// public static BrushTool fromString(Player player, LocalSession session, String json) throws CommandException, InputParseException { +// Gson gson = new Gson(); +// Type type = new TypeToken>() { +// }.getType(); +// Map root = gson.fromJson(json, type); +// if (root == null) { +// getLogger(BrushTool.class).debug("Failed to load " + json); +// return new BrushTool(); +// } +// Map primary = (Map) root.get("primary"); +// Map secondary = (Map) root.getOrDefault("secondary", primary); +// +// VisualMode visual = VisualMode.valueOf((String) root.getOrDefault("visual", "NONE")); +// TargetMode target = TargetMode.valueOf((String) root.getOrDefault("target", "TARGET_BLOCK_RANGE")); +// int range = ((Number) root.getOrDefault("range", -1)).intValue(); +// int offset = ((Number) root.getOrDefault("offset", 0)).intValue(); +// +// BrushTool tool = new BrushTool(); +// tool.visualMode = visual; +// tool.targetMode = target; +// tool.range = range; +// tool.targetOffset = offset; +// +// BrushSettings primarySettings = BrushSettings.get(tool, player, session, primary); +// tool.setPrimary(primarySettings); +// if (primary != secondary) { +// BrushSettings secondarySettings = BrushSettings.get(tool, player, session, secondary); +// tool.setSecondary(secondarySettings); +// } +// +// return tool; +// } public void setHolder(BaseItem holder) { this.holder = holder; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/AsyncCommandBuilder.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/AsyncCommandBuilder.java index 4543ac224..80622c37d 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/AsyncCommandBuilder.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/AsyncCommandBuilder.java @@ -103,7 +103,7 @@ public final class AsyncCommandBuilder { public AsyncCommandBuilder onSuccess(@Nullable String message, @Nullable Consumer consumer) { checkArgument(message != null || consumer != null, "Can't have null message AND consumer"); - this.successMessage = message == null ? null : TextComponent.of(message, TextColor.GRAY); + this.successMessage = message == null ? null : TextComponent.of(message, TextColor.LIGHT_PURPLE); this.consumer = consumer; return this; } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/CommandPermissionsConditionGenerator.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/CommandPermissionsConditionGenerator.java index 4b0a40c51..3a7528e55 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/CommandPermissionsConditionGenerator.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/CommandPermissionsConditionGenerator.java @@ -19,7 +19,6 @@ package com.sk89q.worldedit.command.util; -import com.boydti.fawe.util.StringMan; import com.google.common.collect.ImmutableSet; import org.enginehub.piston.Command; import org.enginehub.piston.gen.CommandConditionGenerator; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/DelegateCommandManager.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/DelegateCommandManager.java deleted file mode 100644 index 6985eba1d..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/DelegateCommandManager.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.sk89q.worldedit.command.util; - -import com.google.common.collect.ImmutableSet; -import org.enginehub.piston.Command; -import org.enginehub.piston.CommandManager; -import org.enginehub.piston.CommandParseResult; -import org.enginehub.piston.converter.ArgumentConverter; -import org.enginehub.piston.inject.InjectedValueAccess; -import org.enginehub.piston.inject.Key; -import org.enginehub.piston.suggestion.Suggestion; - -import java.util.List; -import java.util.Optional; -import java.util.function.Consumer; -import java.util.stream.Stream; - -public class DelegateCommandManager implements CommandManager { - @Override - public Command.Builder newCommand(String s) { - return parent.newCommand(s); - } - - @Override - public void register(Command command) { - parent.register(command); - } - - @Override - public void register(String name, Consumer registrationProcess) { - parent.register(name, registrationProcess); - } - - @Override - public void registerManager(CommandManager manager) { - parent.registerManager(manager); - } - - @Override - public Stream getAllCommands() { - return parent.getAllCommands(); - } - - @Override - public boolean containsCommand(String name) { - return parent.containsCommand(name); - } - - @Override - public Optional getCommand(String s) { - return parent.getCommand(s); - } - - @Override - public ImmutableSet getSuggestions(InjectedValueAccess injectedValueAccess, List list) { - return parent.getSuggestions(injectedValueAccess, list); - } - - @Override - public CommandParseResult parse(InjectedValueAccess injectedValueAccess, List list) { - return parent.parse(injectedValueAccess, list); - } - - @Override - public Object execute(InjectedValueAccess context, List args) { - return parent.execute(context, args); - } - - @Override - public void registerConverter(Key key, ArgumentConverter argumentConverter) { - parent.registerConverter(key, argumentConverter); - } - - @Override - public Optional> getConverter(Key key) { - return parent.getConverter(key); - } - - private final CommandManager parent; - - public DelegateCommandManager(CommandManager parent) { - this.parent = parent; - } -} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/EntityRemover.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/EntityRemover.java index 0b5fc1719..e59811b68 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/EntityRemover.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/EntityRemover.java @@ -24,9 +24,9 @@ import com.sk89q.worldedit.entity.metadata.EntityProperties; import com.sk89q.worldedit.function.EntityFunction; import javax.annotation.Nullable; +import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.regex.Pattern; /** * The implementation of /remove. diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/HookMode.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/HookMode.java index 993942615..113a45613 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/HookMode.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/HookMode.java @@ -21,4 +21,4 @@ package com.sk89q.worldedit.command.util; public enum HookMode { ACTIVE, INACTIVE -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/HookMode.java~7e3fc6c8e... Disable watchdog ticking by default, __watchdog to turn on b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/HookMode.java~7e3fc6c8e... Disable watchdog ticking by default, __watchdog to turn on deleted file mode 100644 index 113a45613..000000000 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/HookMode.java~7e3fc6c8e... Disable watchdog ticking by default, __watchdog to turn on +++ /dev/null @@ -1,24 +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.command.util; - -public enum HookMode { - ACTIVE, INACTIVE -} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/PermissionCondition.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/PermissionCondition.java index 098f309a8..a1ce3abda 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/PermissionCondition.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/PermissionCondition.java @@ -19,7 +19,6 @@ package com.sk89q.worldedit.command.util; -import com.boydti.fawe.util.StringMan; import com.sk89q.worldedit.extension.platform.Actor; import org.enginehub.piston.Command; import org.enginehub.piston.inject.InjectedValueAccess; diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/PrintCommandHelp.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/PrintCommandHelp.java index 1872cf0c0..ca7f3a394 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/PrintCommandHelp.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/PrintCommandHelp.java @@ -32,14 +32,15 @@ import com.sk89q.worldedit.util.formatting.component.CommandUsageBox; import com.sk89q.worldedit.util.formatting.component.InvalidComponentException; import com.sk89q.worldedit.util.formatting.text.TextComponent; import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; +import org.enginehub.piston.Command; +import org.enginehub.piston.CommandManager; + import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.enginehub.piston.Command; -import org.enginehub.piston.CommandManager; /** * Implementation of the //help command. diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/SuggestionHelper.java b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/SuggestionHelper.java index 57990087f..ed5e3aacb 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/SuggestionHelper.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/command/util/SuggestionHelper.java @@ -19,9 +19,6 @@ package com.sk89q.worldedit.command.util; -import static org.enginehub.piston.converter.SuggestionHelper.byPrefix; -import static org.enginehub.piston.converter.SuggestionHelper.limitByPrefix; - import com.sk89q.worldedit.registry.Keyed; import com.sk89q.worldedit.registry.NamespacedRegistry; import com.sk89q.worldedit.registry.Registry; @@ -40,6 +37,9 @@ import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; +import static org.enginehub.piston.converter.SuggestionHelper.byPrefix; +import static org.enginehub.piston.converter.SuggestionHelper.limitByPrefix; + /** * Internal class for generating common command suggestions. */ diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultTransformParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultTransformParser.java index fb4c09be9..bb7f10851 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultTransformParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/DefaultTransformParser.java @@ -1,135 +1,136 @@ -package com.sk89q.worldedit.extension.factory; - -import com.boydti.fawe.command.FaweParser; -import com.boydti.fawe.command.SuggestInputParseException; -import com.boydti.fawe.object.extent.MultiTransform; -import com.boydti.fawe.object.extent.RandomTransform; -import com.boydti.fawe.object.extent.ResettableExtent; -import com.boydti.fawe.object.random.TrueRandom; -import com.boydti.fawe.util.StringMan; -import com.google.common.collect.Iterables; -import com.sk89q.minecraft.util.commands.CommandLocals; -import com.sk89q.worldedit.WorldEdit; -//import com.sk89q.worldedit.command.TransformCommands; -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.internal.expression.Expression; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class DefaultTransformParser extends FaweParser { - - public DefaultTransformParser(WorldEdit worldEdit) { - super(worldEdit, "transforms"); - } - - @Override - public ResettableExtent parseFromInput(String input, ParserContext context) throws InputParseException { - if (input.isEmpty()) return null; - - List unionChances = new ArrayList<>(); - List intersectionChances = new ArrayList<>(); - - List intersection = new ArrayList<>(); - List union = new ArrayList<>(); - final CommandLocals locals = new CommandLocals(); - Actor actor = context != null ? context.getActor() : null; - if (actor != null) { - locals.put(Actor.class, actor); - } - try { - List>> parsed = parse(input); - for (Map.Entry> entry : parsed) { - ParseEntry pe = entry.getKey(); - String command = pe.input; - ResettableExtent transform = null; - double chance = 1; - if (command.isEmpty()) { - transform = parseFromInput(StringMan.join(entry.getValue(), ','), context); - } else { - List args = entry.getValue(); - String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " ")); - try { - transform = parse(command + cmdArgs, context); - } catch (SuggestInputParseException rethrow) { - throw rethrow; - } catch (Throwable e) { - throw new NoMatchException("See: //transforms"); - } - if (transform == null) { - // Legacy syntax - int percentIndex = command.indexOf('%'); - if (percentIndex != -1) { // Legacy percent pattern - chance = Expression.compile(command.substring(0, percentIndex)).evaluate(); - command = command.substring(percentIndex + 1); - if (!entry.getValue().isEmpty()) { - if (!command.isEmpty()) command += " "; - command += StringMan.join(entry.getValue(), " "); - } - transform = parseFromInput(command, context); - } else { - throw new NoMatchException("See: //transforms"); - } - } - if (pe.and) { // & - intersectionChances.add(chance); - intersection.add(transform); - } else { - if (!intersection.isEmpty()) { - if (intersection.size() == 1) { - throw new InputParseException("Error, floating &"); - } - MultiTransform multi = new MultiTransform(); - double total = 0; - for (int i = 0; i < intersection.size(); i++) { - Double value = intersectionChances.get(i); - total += value; - multi.add(intersection.get(i), value); - } - union.add(multi); - unionChances.add(total); - intersection.clear(); - intersectionChances.clear(); - } - unionChances.add(chance); - union.add(transform); - } - } - } - } catch (Throwable e) { - throw new InputParseException(e.getMessage(), e); - } - if (!intersection.isEmpty()) { - if (intersection.size() == 1) { - throw new InputParseException("Error, floating &"); - } - MultiTransform multi = new MultiTransform(); - double total = 0; - for (int i = 0; i < intersection.size(); i++) { - Double value = intersectionChances.get(i); - total += value; - multi.add(intersection.get(i), value); - } - union.add(multi); - unionChances.add(total); - intersection.clear(); - intersectionChances.clear(); - } - if (union.isEmpty()) { - throw new NoMatchException("See: //transforms"); - } else if (union.size() == 1) { - return union.get(0); - } else { - RandomTransform random = new RandomTransform(new TrueRandom()); - for (int i = 0; i < union.size(); i++) { - random.add(union.get(i), unionChances.get(i)); - } - return random; - } - } - - -} +// TODO: Ping @MattBDev to reimplement 2020-02-04 +//package com.sk89q.worldedit.extension.factory; +// +//import com.boydti.fawe.command.FaweParser; +//import com.boydti.fawe.command.SuggestInputParseException; +//import com.boydti.fawe.object.extent.MultiTransform; +//import com.boydti.fawe.object.extent.RandomTransform; +//import com.boydti.fawe.object.extent.ResettableExtent; +//import com.boydti.fawe.object.random.TrueRandom; +//import com.boydti.fawe.util.StringMan; +//import com.google.common.collect.Iterables; +//import com.sk89q.minecraft.util.commands.CommandLocals; +//import com.sk89q.worldedit.WorldEdit; +////import com.sk89q.worldedit.command.TransformCommands; +//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.internal.expression.Expression; +//import java.util.ArrayList; +//import java.util.List; +//import java.util.Map; +// +//public class DefaultTransformParser extends FaweParser { +// +// public DefaultTransformParser(WorldEdit worldEdit) { +// super(worldEdit, "transforms"); +// } +// +// @Override +// public ResettableExtent parseFromInput(String input, ParserContext context) throws InputParseException { +// if (input.isEmpty()) return null; +// +// List unionChances = new ArrayList<>(); +// List intersectionChances = new ArrayList<>(); +// +// List intersection = new ArrayList<>(); +// List union = new ArrayList<>(); +// final CommandLocals locals = new CommandLocals(); +// Actor actor = context != null ? context.getActor() : null; +// if (actor != null) { +// locals.put(Actor.class, actor); +// } +// try { +// List>> parsed = parse(input); +// for (Map.Entry> entry : parsed) { +// ParseEntry pe = entry.getKey(); +// String command = pe.input; +// ResettableExtent transform; +// double chance = 1; +// if (command.isEmpty()) { +// transform = parseFromInput(StringMan.join(entry.getValue(), ','), context); +// } else { +// List args = entry.getValue(); +// String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " ")); +// try { +// transform = parse(command + cmdArgs, context); +// } catch (SuggestInputParseException rethrow) { +// throw rethrow; +// } catch (Throwable e) { +// throw new NoMatchException("See: //transforms"); +// } +// if (transform == null) { +// // Legacy syntax +// int percentIndex = command.indexOf('%'); +// if (percentIndex != -1) { // Legacy percent pattern +// chance = Expression.compile(command.substring(0, percentIndex)).evaluate(); +// command = command.substring(percentIndex + 1); +// if (!entry.getValue().isEmpty()) { +// if (!command.isEmpty()) command += " "; +// command += StringMan.join(entry.getValue(), " "); +// } +// transform = parseFromInput(command, context); +// } else { +// throw new NoMatchException("See: //transforms"); +// } +// } +// if (pe.and) { // & +// intersectionChances.add(chance); +// intersection.add(transform); +// } else { +// if (!intersection.isEmpty()) { +// if (intersection.size() == 1) { +// throw new InputParseException("Error, floating &"); +// } +// MultiTransform multi = new MultiTransform(); +// double total = 0; +// for (int i = 0; i < intersection.size(); i++) { +// Double value = intersectionChances.get(i); +// total += value; +// multi.add(intersection.get(i), value); +// } +// union.add(multi); +// unionChances.add(total); +// intersection.clear(); +// intersectionChances.clear(); +// } +// unionChances.add(chance); +// union.add(transform); +// } +// } +// } +// } catch (Throwable e) { +// throw new InputParseException(e.getMessage(), e); +// } +// if (!intersection.isEmpty()) { +// if (intersection.size() == 1) { +// throw new InputParseException("Error, floating &"); +// } +// MultiTransform multi = new MultiTransform(); +// double total = 0; +// for (int i = 0; i < intersection.size(); i++) { +// Double value = intersectionChances.get(i); +// total += value; +// multi.add(intersection.get(i), value); +// } +// union.add(multi); +// unionChances.add(total); +// intersection.clear(); +// intersectionChances.clear(); +// } +// if (union.isEmpty()) { +// throw new NoMatchException("See: //transforms"); +// } else if (union.size() == 1) { +// return union.get(0); +// } else { +// RandomTransform random = new RandomTransform(new TrueRandom()); +// for (int i = 0; i < union.size(); i++) { +// random.add(union.get(i), unionChances.get(i)); +// } +// return random; +// } +// } +// +// +//} 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 ac0bcdb2a..295c48f43 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,18 @@ package com.sk89q.worldedit.extension.factory; import com.sk89q.worldedit.WorldEdit; +import com.sk89q.worldedit.extension.factory.parser.mask.BiomeMaskParser; 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.BlockStateMaskParser; +import com.sk89q.worldedit.extension.factory.parser.mask.BlocksMaskParser; +import com.sk89q.worldedit.extension.factory.parser.mask.ExistingMaskParser; +import com.sk89q.worldedit.extension.factory.parser.mask.ExpressionMaskParser; +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.OffsetMaskParser; +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; @@ -49,8 +59,6 @@ public final class MaskFactory extends AbstractFactory { * @param worldEdit the WorldEdit instance */ public MaskFactory(WorldEdit worldEdit) { - super(worldEdit, new DefaultMaskParser(worldEdit)); - /* super(worldEdit, new BlocksMaskParser(worldEdit)); register(new ExistingMaskParser(worldEdit)); @@ -62,11 +70,8 @@ public final class MaskFactory extends AbstractFactory { register(new BlockStateMaskParser(worldEdit)); register(new NegateMaskParser(worldEdit)); register(new ExpressionMaskParser(worldEdit)); - */ register(new BlockCategoryMaskParser(worldEdit)); - /* register(new BiomeMaskParser(worldEdit)); - */ } 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 6bf92d383..014229a3e 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 @@ -21,7 +21,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.DefaultPatternParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.ClipboardPatternParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.RandomPatternParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.RandomStatePatternParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.SingleBlockPatternParser; +import com.sk89q.worldedit.extension.factory.parser.pattern.TypeOrStateApplyingPatternParser; import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.internal.registry.AbstractFactory; @@ -40,8 +44,6 @@ public final class PatternFactory extends AbstractFactory { * @param worldEdit the WorldEdit instance */ public PatternFactory(WorldEdit worldEdit) { - super(worldEdit, new DefaultPatternParser(worldEdit)); - /* super(worldEdit, new SingleBlockPatternParser(worldEdit)); // split and parse each sub-pattern @@ -51,7 +53,6 @@ public final class PatternFactory extends AbstractFactory { register(new ClipboardPatternParser(worldEdit)); register(new TypeOrStateApplyingPatternParser(worldEdit)); register(new RandomStatePatternParser(worldEdit)); - */ register(new BlockCategoryPatternParser(worldEdit)); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultBlockParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultBlockParser.java index bfbef29da..eaf4fe3d1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultBlockParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/DefaultBlockParser.java @@ -43,6 +43,7 @@ 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.extension.platform.Capability; import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.SlottableBlockBag; import com.sk89q.worldedit.internal.registry.InputParser; @@ -289,8 +290,17 @@ public class DefaultBlockParser extends InputParser { if (typeString.isEmpty()) { throw new InputParseException("Invalid format"); } - // PosX - if (typeString.matches("pos[0-9]+")) { + if ("hand".equalsIgnoreCase(typeString)) { + // Get the block type from the item in the user's hand. + final BaseBlock blockInHand = getBlockInHand(context.requireActor(), HandSide.MAIN_HAND); + state = blockInHand.toBlockState(); + nbt = blockInHand.getNbtData(); + } else if ("offhand".equalsIgnoreCase(typeString)) { + // Get the block type from the item in the user's off hand. + final BaseBlock blockInHand = getBlockInHand(context.requireActor(), HandSide.OFF_HAND); + state = blockInHand.toBlockState(); + nbt = blockInHand.getNbtData(); + } else if (typeString.matches("pos[0-9]+")) { int index = Integer.parseInt(typeString.replaceAll("[a-z]+", "")); // Get the block type from the "primary position" final World world = context.requireWorld(); @@ -301,45 +311,34 @@ public class DefaultBlockParser extends InputParser { throw new InputParseException("Your selection is not complete."); } state = world.getBlock(primaryPosition); + } else if (typeString.matches("slot[0-9]+")) { + int slot = Integer.parseInt(typeString.substring(4)) - 1; + Actor actor = context.requireActor(); + if (!(actor instanceof Player)) { + throw new InputParseException("The user is not a player!"); + } + Player player = (Player) actor; + BlockBag bag = player.getInventoryBlockBag(); + if (bag == null || !(bag instanceof SlottableBlockBag)) { + throw new InputParseException("Unsupported!"); + } + SlottableBlockBag slottable = (SlottableBlockBag) bag; + BaseItem item = slottable.getItem(slot); + + if (!item.getType().hasBlockType()) { + throw new InputParseException("You're not holding a block!"); + } + state = item.getType().getBlockType().getDefaultState(); + nbt = item.getNbtData(); } else { - if ("hand".equalsIgnoreCase(typeString)) { - // Get the block type from the item in the user's hand. - BaseBlock block = getBlockInHand(context.requireActor(), HandSide.MAIN_HAND); - state = block.toBlockState(); - nbt = block.getNbtData(); - } else if ("offhand".equalsIgnoreCase(typeString)) { - // Get the block type from the item in the user's off hand. - BaseBlock block = getBlockInHand(context.requireActor(), HandSide.OFF_HAND); - state = block.toBlockState(); - nbt = block.getNbtData(); - } else if (typeString.matches("slot[0-9]+")) { - int slot = Integer.parseInt(typeString.substring(4)) - 1; - Actor actor = context.requireActor(); - if (!(actor instanceof Player)) { - throw new InputParseException("The user is not a player!"); - } - Player player = (Player) actor; - BlockBag bag = player.getInventoryBlockBag(); - if (bag == null || !(bag instanceof SlottableBlockBag)) { - throw new InputParseException("Unsupported!"); - } - SlottableBlockBag slottable = (SlottableBlockBag) bag; - BaseItem item = slottable.getItem(slot); + BlockType type = BlockTypes.parse(typeString.toLowerCase(Locale.ROOT)); - if (!item.getType().hasBlockType()) { - throw new InputParseException("You're not holding a block!"); - } - state = item.getType().getBlockType().getDefaultState(); - nbt = item.getNbtData(); - } else { - BlockType type = BlockTypes.parse(typeString.toLowerCase(Locale.ROOT)); - - if (type != null) { - state = type.getDefaultState(); - } - if (state == null) { - throw new NoMatchException("Does not match a valid block type: '" + input + "'"); - } + 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(); @@ -351,15 +350,15 @@ public class DefaultBlockParser extends InputParser { if (stateString == null || stateString.isEmpty()) { state = new FuzzyBlockState(state); } else { - BlockType type = state.getBlockType(); + BlockType blockType = state.getBlockType(); FuzzyBlockState.Builder fuzzyBuilder = FuzzyBlockState.builder(); - fuzzyBuilder.type(type); + fuzzyBuilder.type(blockType); String[] entries = stateString.split(","); for (String entry : entries) { String[] split = entry.split("="); String key = split[0]; String val = split[1]; - Property prop = type.getProperty(key); + Property prop = blockType.getProperty(key); fuzzyBuilder.withProperty(prop, prop.getValueFor(val)); } state = fuzzyBuilder.build(); @@ -398,9 +397,17 @@ public class DefaultBlockParser extends InputParser { // Allow setting mob spawn type if (blockAndExtraData.length > 1) { String mobName = blockAndExtraData[1]; - EntityType mobType = EntityTypes.parse(mobName); + EntityType ent = EntityTypes.get(mobName.toLowerCase(Locale.ROOT)); + if (ent == null) { + throw new NoMatchException("Unknown entity type '" + mobName + "'"); + } + mobName = ent.getId(); + if (!worldEdit.getPlatformManager().queryCapability(Capability.USER_COMMANDS).isValidMobType(mobName)) { + throw new NoMatchException("Unknown mob type '" + mobName + "'"); + } return validate(context, new MobSpawnerBlock(state, mobName)); } else { + //noinspection ConstantConditions return validate(context, new MobSpawnerBlock(state, EntityTypes.PIG.getId())); } } else if (blockType == BlockTypes.PLAYER_HEAD || blockType == BlockTypes.PLAYER_WALL_HEAD) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/BlockStateMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/BlockStateMaskParser.java index 6e9a5b0ef..ca47294b4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/BlockStateMaskParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/BlockStateMaskParser.java @@ -29,8 +29,6 @@ import com.sk89q.worldedit.internal.registry.InputParser; import java.util.stream.Stream; -import java.util.stream.Stream; - public class BlockStateMaskParser extends InputParser { public BlockStateMaskParser(WorldEdit worldEdit) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/DefaultMaskParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/DefaultMaskParser.java index 411c1aa28..8d467a46e 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/DefaultMaskParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/mask/DefaultMaskParser.java @@ -1,206 +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.mask; - -import com.boydti.fawe.command.FaweParser; -import com.boydti.fawe.command.SuggestInputParseException; -import com.boydti.fawe.config.Caption; -import com.boydti.fawe.util.StringMan; -import com.sk89q.minecraft.util.commands.CommandLocals; -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.extension.input.InputParseException; -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.Mask; -import com.sk89q.worldedit.function.mask.MaskIntersection; -import com.sk89q.worldedit.function.mask.MaskUnion; -import com.sk89q.worldedit.session.request.Request; -import com.sk89q.worldedit.world.block.BaseBlock; -import com.sk89q.worldedit.world.block.BlockStateHolder; -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 DefaultMaskParser extends FaweParser { - public DefaultMaskParser(WorldEdit worldEdit) { - super(worldEdit, "masks"); - } - - @Override - public Mask 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())); - } - Extent extent = Request.request().getExtent(); - if (extent == null) extent = context.getExtent(); - List> masks = new ArrayList<>(); - masks.add(new ArrayList<>()); - - final CommandLocals locals = new CommandLocals(); - Actor actor = context != null ? context.getActor() : null; - if (actor != null) { - locals.put(Actor.class, actor); - } - try { - List>> parsed = parse(input); - for (Map.Entry> entry : parsed) { - ParseEntry pe = entry.getKey(); - final String command = pe.input; - String full = pe.full; - Mask mask = null; - if (command.isEmpty()) { - mask = parseFromInput(StringMan.join(entry.getValue(), ','), context); - } else { - List args = entry.getValue(); - String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " ")); - try { - mask = parse(command + cmdArgs, context); - } catch (SuggestInputParseException rethrow) { - throw rethrow; - } catch (Throwable e) { - // TODO NOT IMPLEMENTED -// 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 = "[" + StringMan.join(split, "][") + "]"; -// suggestions.set(i, suggestion); -// } +// TODO: Ping @MattBDev to reimplement 2020-02-04 +///* +// * 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; +//import com.boydti.fawe.config.Caption; +//import com.boydti.fawe.util.StringMan; +//import com.sk89q.minecraft.util.commands.CommandLocals; +//import com.sk89q.worldedit.WorldEdit; +//import com.sk89q.worldedit.extension.input.InputParseException; +//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.Mask; +//import com.sk89q.worldedit.function.mask.MaskIntersection; +//import com.sk89q.worldedit.function.mask.MaskUnion; +//import com.sk89q.worldedit.session.request.Request; +//import com.sk89q.worldedit.world.block.BaseBlock; +//import com.sk89q.worldedit.world.block.BlockStateHolder; +//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 DefaultMaskParser extends FaweParser { +// public DefaultMaskParser(WorldEdit worldEdit) { +// super(worldEdit, "masks"); +// } +// +// @Override +// public Mask 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())); +// } +// Extent extent = Request.request().getExtent(); +// if (extent == null) extent = context.getExtent(); +// List> masks = new ArrayList<>(); +// masks.add(new ArrayList<>()); +// +// final CommandLocals locals = new CommandLocals(); +// Actor actor = context != null ? context.getActor() : null; +// if (actor != null) { +// locals.put(Actor.class, actor); +// } +// try { +// List>> parsed = parse(input); +// for (Map.Entry> entry : parsed) { +// ParseEntry pe = entry.getKey(); +// final String command = pe.input; +// String full = pe.full; +// Mask mask = null; +// if (command.isEmpty()) { +// mask = parseFromInput(StringMan.join(entry.getValue(), ','), context); +// } else { +// List args = entry.getValue(); +// String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " ")); +// try { +// mask = parse(command + cmdArgs, context); +// } catch (SuggestInputParseException rethrow) { +// throw rethrow; +// } catch (Throwable e) { +// // TODO NOT IMPLEMENTED +//// 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 = "[" + 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 (mask == 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 == '#' || char0 == '?') { +// // TODO NOT IMPLEMENTED +//// throw new SuggestInputParseException(new NoMatchException("Unknown mask: " + full + ", See: //masks"), full, +//// () -> { +//// if (full.length() == 1) return new ArrayList<>(dispatcher.getPrimaryAliases()); +//// return dispatcher.getAliases().stream().filter( +//// s -> s.startsWith(command.toLowerCase()) +//// ).collect(Collectors.toList()); +//// } +//// ); +// } +// // Legacy syntax +// if (charMask) { +// switch (char0) { +// case '\\': // +// case '/': // +// case '{': // +// case '$': // +// 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(":", "]["); // } +// mask = parseFromInput("#" + char0 + "[" + value + "]", context); +// break; // } -// return suggestions; -// } catch (CommandException e1) { -// throw new InputParseException(e1.getMessage()); -// } catch (Throwable e2) { -// e2.printStackTrace(); -// throw new InputParseException(e2.getMessage()); -// } -// }); - } - if (mask == 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 == '#' || char0 == '?') { - // TODO NOT IMPLEMENTED -// throw new SuggestInputParseException(new NoMatchException("Unknown mask: " + full + ", See: //masks"), full, -// () -> { -// if (full.length() == 1) return new ArrayList<>(dispatcher.getPrimaryAliases()); -// return dispatcher.getAliases().stream().filter( -// s -> s.startsWith(command.toLowerCase()) -// ).collect(Collectors.toList()); +// case '|': +// case '~': +// case '<': +// case '>': +// case '!': +// input = input.substring(input.indexOf(char0) + 1); +// mask = parseFromInput(char0 + "[" + input + "]", context); +// if (actor != null) { +// actor.print(Caption.of("fawe.worldedit.help.command.clarifying.bracket" , char0 + "[" + input + "]")); // } -// ); - } - // Legacy syntax - if (charMask) { - switch (char0) { - case '\\': // - case '/': // - case '{': // - case '$': // - 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(":", "]["); - } - mask = parseFromInput("#" + char0 + "[" + value + "]", context); - break; - } - case '|': - case '~': - case '<': - case '>': - case '!': - input = input.substring(input.indexOf(char0) + 1); - mask = parseFromInput(char0 + "[" + input + "]", context); - if (actor != null) { - actor.print(Caption.of("fawe.worldedit.help.command.clarifying.bracket" , char0 + "[" + input + "]")); - } - return mask; - } - } - } - if (mask == null) { - if (command.startsWith("[")) { - int end = command.lastIndexOf(']'); - mask = parseFromInput(command.substring(1, end == -1 ? command.length() : end), context); - } else { - List entries = entry.getValue(); - BlockMaskBuilder builder = new BlockMaskBuilder(); -// if (StringMan.containsAny(full, "\\^$.|?+(){}<>~$!%^&*+-/")) - { - try { - builder.addRegex(full); - } catch (InputParseException ignore) {} - } - if (mask == null) { - context.setPreferringWildcard(false); - context.setRestricted(false); - BaseBlock block = worldEdit.getBlockFactory().parseFromInput(full, context); - builder.add(block); - mask = builder.build(extent); - } - } - } - } - if (pe.and) { - masks.add(new ArrayList<>()); - } - masks.get(masks.size() - 1).add(mask); - } - } catch (InputParseException rethrow) { - throw rethrow; - } catch (Throwable e) { - e.printStackTrace(); - throw new InputParseException(e.getMessage(), e); - } - List maskUnions = new ArrayList<>(); - for (List maskList : masks) { - if (maskList.size() == 1) { - maskUnions.add(maskList.get(0)); - } else if (maskList.size() != 0) { - maskUnions.add(new MaskUnion(maskList)); - } - } - if (maskUnions.size() == 1) { - return maskUnions.get(0); - } else if (maskUnions.size() != 0) { - return new MaskIntersection(maskUnions); - } else { - return null; - } - - } -} +// return mask; +// } +// } +// } +// if (mask == null) { +// if (command.startsWith("[")) { +// int end = command.lastIndexOf(']'); +// mask = parseFromInput(command.substring(1, end == -1 ? command.length() : end), context); +// } else { +// List entries = entry.getValue(); +// BlockMaskBuilder builder = new BlockMaskBuilder(); +//// if (StringMan.containsAny(full, "\\^$.|?+(){}<>~$!%^&*+-/")) +// { +// try { +// builder.addRegex(full); +// } catch (InputParseException ignore) {} +// } +// if (mask == null) { +// context.setPreferringWildcard(false); +// context.setRestricted(false); +// BaseBlock block = worldEdit.getBlockFactory().parseFromInput(full, context); +// builder.add(block); +// mask = builder.build(extent); +// } +// } +// } +// } +// if (pe.and) { +// masks.add(new ArrayList<>()); +// } +// masks.get(masks.size() - 1).add(mask); +// } +// } catch (InputParseException rethrow) { +// throw rethrow; +// } catch (Throwable e) { +// e.printStackTrace(); +// throw new InputParseException(e.getMessage(), e); +// } +// List maskUnions = new ArrayList<>(); +// for (List maskList : masks) { +// if (maskList.size() == 1) { +// maskUnions.add(maskList.get(0)); +// } else if (maskList.size() != 0) { +// maskUnions.add(new MaskUnion(maskList)); +// } +// } +// if (maskUnions.size() == 1) { +// return maskUnions.get(0); +// } else if (maskUnions.size() != 0) { +// return new MaskIntersection(maskUnions); +// } else { +// return null; +// } +// +// } +//} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/DefaultPatternParser.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/DefaultPatternParser.java index 63fdebf0b..fb67973b1 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/DefaultPatternParser.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/factory/parser/pattern/DefaultPatternParser.java @@ -1,184 +1,185 @@ -/* - * 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.object.random.TrueRandom; -import com.boydti.fawe.util.StringMan; -import com.google.common.collect.Iterables; -import com.sk89q.minecraft.util.commands.CommandLocals; -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.extension.input.InputParseException; -import com.sk89q.worldedit.extension.input.NoMatchException; -import com.sk89q.worldedit.extension.input.ParserContext; -import com.sk89q.worldedit.extension.platform.Actor; -import com.sk89q.worldedit.extension.platform.PlatformCommandManager; -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.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 DefaultPatternParser extends FaweParser { - - public DefaultPatternParser(WorldEdit worldEdit) { - super(worldEdit, "patterns"); - } - - @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 { - List args = entry.getValue(); - String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " ")); - try { - pattern = parse(command + cmdArgs, context); - } catch (SuggestInputParseException rethrow) { - throw rethrow; - } catch (Throwable e) { - // TODO NOT IMPLEMENTED -// 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 = "[" + StringMan.join(split, "][") + "]"; -// suggestions.set(i, suggestion); -// } +// TODO: Ping @MattBDev to reimplement (or remove because this class is stupid) 2020-02-04 +///* +// * 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.object.random.TrueRandom; +//import com.boydti.fawe.util.StringMan; +//import com.google.common.collect.Iterables; +//import com.sk89q.minecraft.util.commands.CommandLocals; +//import com.sk89q.worldedit.WorldEdit; +//import com.sk89q.worldedit.extension.input.InputParseException; +//import com.sk89q.worldedit.extension.input.NoMatchException; +//import com.sk89q.worldedit.extension.input.ParserContext; +//import com.sk89q.worldedit.extension.platform.Actor; +//import com.sk89q.worldedit.extension.platform.PlatformCommandManager; +//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.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 DefaultPatternParser extends FaweParser { +// +// public DefaultPatternParser(WorldEdit worldEdit) { +// super(worldEdit, "patterns"); +// } +// +// @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 { +// List args = entry.getValue(); +// String cmdArgs = ((args.isEmpty()) ? "" : " " + StringMan.join(args, " ")); +// try { +// pattern = parse(command + cmdArgs, context); +// } catch (SuggestInputParseException rethrow) { +// throw rethrow; +// } catch (Throwable e) { +// // TODO NOT IMPLEMENTED +//// 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 = "[" + 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) { +// // 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 == '#') { +// // TODO NOT IMPLEMENTED +//// 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(Locale.ROOT)) +//// ).collect(Collectors.toList()); +//// } +//// ); +// } +// +// +// if (charMask) { +// if (char0 == '$') { +// 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); +// } +// } +// 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"); // } // } -// return suggestions; -// } catch (CommandException e1) { -// throw new InputParseException(e1.getMessage()); -// } catch (Throwable e2) { -// e2.printStackTrace(); -// throw new InputParseException(e2.getMessage()); // } -// }); - } - if (pattern == 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 == '#') { - // TODO NOT IMPLEMENTED -// 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(Locale.ROOT)) -// ).collect(Collectors.toList()); -// } -// ); - } - - - if (charMask) { - if (char0 == '$') { - 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); - } - } - 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"); - } - } - } - } - } - } - 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; - } - if (patterns.size() == 1) { - return patterns.get(0); - } - RandomPattern random = new RandomPattern(new TrueRandom()); - for (int i = 0; i < patterns.size(); i++) { - random.add(patterns.get(i), chances.get(i)); - } - return random; - } -} +// } +// } +// } +// 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; +// } +// if (patterns.size() == 1) { +// return patterns.get(0); +// } +// 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/platform/PlatformCommandManager.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformCommandManager.java index bb2e0f085..ba83ca62c 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformCommandManager.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/PlatformCommandManager.java @@ -24,12 +24,8 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.boydti.fawe.Fawe; import com.boydti.fawe.command.AnvilCommands; import com.boydti.fawe.command.AnvilCommandsRegistration; -import com.boydti.fawe.command.CFICommands; -import com.boydti.fawe.command.CFICommandsRegistration; import com.boydti.fawe.config.Caption; import com.boydti.fawe.config.Settings; -import com.boydti.fawe.object.brush.visualization.cfi.HeightMapMCAGenerator; -import com.boydti.fawe.object.changeset.CFIChangeSet; import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.object.task.ThrowableSupplier; import com.boydti.fawe.util.StringMan; @@ -62,13 +58,9 @@ import com.sk89q.worldedit.command.HistoryCommands; import com.sk89q.worldedit.command.HistoryCommandsRegistration; import com.sk89q.worldedit.command.HistorySubCommands; import com.sk89q.worldedit.command.HistorySubCommandsRegistration; -import com.sk89q.worldedit.command.MaskCommands; -import com.sk89q.worldedit.command.MaskCommandsRegistration; import com.sk89q.worldedit.command.NavigationCommands; import com.sk89q.worldedit.command.NavigationCommandsRegistration; import com.sk89q.worldedit.command.PaintBrushCommands; -import com.sk89q.worldedit.command.PatternCommands; -import com.sk89q.worldedit.command.PatternCommandsRegistration; import com.sk89q.worldedit.command.RegionCommands; import com.sk89q.worldedit.command.RegionCommandsRegistration; import com.sk89q.worldedit.command.SchematicCommands; @@ -87,8 +79,6 @@ import com.sk89q.worldedit.command.ToolCommands; import com.sk89q.worldedit.command.ToolCommandsRegistration; import com.sk89q.worldedit.command.ToolUtilCommands; import com.sk89q.worldedit.command.ToolUtilCommandsRegistration; -import com.sk89q.worldedit.command.TransformCommands; -import com.sk89q.worldedit.command.TransformCommandsRegistration; import com.sk89q.worldedit.command.UtilityCommands; import com.sk89q.worldedit.command.UtilityCommandsRegistration; import com.sk89q.worldedit.command.WorldEditCommands; @@ -304,9 +294,10 @@ public final class PlatformCommandManager { }); }); */ - globalInjectedValues.injectValue(Key.of(CFICommands.CFISettings.class), - context -> context.injectedValue(Key.of(Actor.class)) - .orElseThrow(() -> new IllegalStateException("No CFI Settings")).getMeta("CFISettings")); + // TODO: Ping @MattBDev to reimplement 2020-02-04 +// globalInjectedValues.injectValue(Key.of(CFICommands.CFISettings.class), +// context -> context.injectedValue(Key.of(Actor.class)) +// .orElseThrow(() -> new IllegalStateException("No CFI Settings")).getMeta("CFISettings")); globalInjectedValues.injectValue(Key.of(World.class), context -> { LocalSession localSession = context.injectedValue(Key.of(LocalSession.class)) @@ -321,7 +312,6 @@ public final class PlatformCommandManager { } else { throw new MissingWorldException(); } - } catch (MissingWorldException e) { exceptionConverter.convert(e); throw new AssertionError("Should have thrown a new exception.", e); @@ -332,13 +322,13 @@ public final class PlatformCommandManager { } private void registerSubCommands(String name, List aliases, String desc, - CommandRegistration registration, CI instance) { + CommandRegistration registration, CI instance) { registerSubCommands(name, aliases, desc, registration, instance, m -> {}); } private void registerSubCommands(String name, List aliases, String desc, - CommandRegistration registration, CI instance, - Consumer additionalConfig) { + CommandRegistration registration, CI instance, + Consumer additionalConfig) { commandManager.register(name, cmd -> { cmd.aliases(aliases); cmd.description(TextComponent.of(desc)); @@ -396,27 +386,28 @@ public final class PlatformCommandManager { public void registerAllCommands() { if (Settings.IMP.ENABLED_COMPONENTS.COMMANDS) { - registerSubCommands( - "patterns", - ImmutableList.of(), - "Patterns determine what blocks are placed", - PatternCommandsRegistration.builder(), - new PatternCommands() - ); - registerSubCommands( - "masks", - ImmutableList.of(), - "Masks determine which blocks are placed", - MaskCommandsRegistration.builder(), - new MaskCommands(worldEdit) - ); - registerSubCommands( - "transforms", - ImmutableList.of(), - "Transforms modify how a block is placed", - TransformCommandsRegistration.builder(), - new TransformCommands() - ); + // TODO: Ping @MattBDev to reimplement (or remove) 2020-02-04 +// registerSubCommands( +// "patterns", +// ImmutableList.of(), +// "Patterns determine what blocks are placed", +// PatternCommandsRegistration.builder(), +// new PatternCommands() +// ); +// registerSubCommands( +// "masks", +// ImmutableList.of(), +// "Masks determine which blocks are placed", +// MaskCommandsRegistration.builder(), +// new MaskCommands(worldEdit) +// ); +// registerSubCommands( +// "transforms", +// ImmutableList.of(), +// "Transforms modify how a block is placed", +// TransformCommandsRegistration.builder(), +// new TransformCommands() +// ); registerSubCommands( "schematic", ImmutableList.of("schem", "/schematic", "/schem"), @@ -460,13 +451,14 @@ public final class PlatformCommandManager { WorldEditCommandsRegistration.builder(), new WorldEditCommands(worldEdit) ); - registerSubCommands( - "cfi", - ImmutableList.of("/cfi"), - "CFI commands", - CFICommandsRegistration.builder(), - new CFICommands(worldEdit) - ); + // TODO: Ping @MattBDev to reimplement 2020-02-04 +// registerSubCommands( +// "cfi", +// ImmutableList.of("/cfi"), +// "CFI commands", +// CFICommandsRegistration.builder(), +// new CFICommands(worldEdit) +// ); registerSubCommands( "/anvil", ImmutableList.of(), @@ -608,16 +600,6 @@ public final class PlatformCommandManager { return CommandArgParser.forArgString(input).parseArgs(); } - public T parseCommand(String args, Actor actor) { - InjectedValueAccess context; - if (actor == null) { - context = globalInjectedValues; - } else { - context = initializeInjectedValues(args::toString, actor, null); - } - return parseCommand(args, context); - } - public T parseConverter(String args, InjectedValueAccess access, Class clazz) { ArgumentConverter converter = commandManager.getConverter(Key.of(clazz)).orElse(null); if (converter != null) { @@ -630,14 +612,6 @@ public final class PlatformCommandManager { return null; } - public T parseCommand(String args, InjectedValueAccess access) { - if (args.isEmpty()) return null; - String[] split = parseArgs(args) - .map(Substring::getSubstring) - .toArray(String[]::new); - return (T) commandManager.execute(access, ImmutableList.copyOf(split)); - } - @Subscribe public void handleCommand(CommandEvent event) { Request.reset(); @@ -771,19 +745,20 @@ public final class PlatformCommandManager { worldEdit.flushBlockBag(actor, editSession); } - CFICommands.CFISettings cfi = actor.getMeta("CFISettings"); - if (cfi != null) { - HeightMapMCAGenerator gen = cfi.getGenerator(); - if (gen != null && gen.isModified()) { - try { - gen.update(); - CFIChangeSet set = new CFIChangeSet(gen, actor.getUniqueId()); - session.remember(actor, gen, set, actor.getLimit()); - } catch (IOException e) { - e.printStackTrace(); - } - } - } + // TODO: Ping @MattBDev to reimplement 2020-02-04 +// CFICommands.CFISettings cfi = actor.getMeta("CFISettings"); +// if (cfi != null) { +// HeightMapMCAGenerator gen = cfi.getGenerator(); +// if (gen != null && gen.isModified()) { +// try { +// gen.update(); +// CFIChangeSet set = new CFIChangeSet(gen, actor.getUniqueId()); +// session.remember(actor, gen, set, actor.getLimit()); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// } Request.reset(); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/PrimitiveBindings.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/PrimitiveBindings.java index b24868c9c..991b27ee2 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/PrimitiveBindings.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/PrimitiveBindings.java @@ -1,15 +1,7 @@ package com.sk89q.worldedit.extension.platform.binding; -import com.boydti.fawe.Fawe; -import com.boydti.fawe.object.extent.NullExtent; -import com.boydti.fawe.object.extent.ResettableExtent; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.entity.Entity; -import com.sk89q.worldedit.extension.factory.DefaultTransformParser; import com.sk89q.worldedit.extension.input.InputParseException; -import com.sk89q.worldedit.extension.input.ParserContext; -import com.sk89q.worldedit.extension.platform.Actor; -import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.internal.expression.EvaluationException; import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.ExpressionException; @@ -17,7 +9,6 @@ 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.Locale; import javax.annotation.Nullable; @@ -44,29 +35,31 @@ public class PrimitiveBindings extends Bindings { } } - /** - * Gets an {@link Extent} from a {@link Binding}. - * - * @param argument the context - * @return an extent - * @throws InputParseException on other error - */ - @Binding - public ResettableExtent getResettableExtent(Actor actor, String argument) throws InputParseException { - if (argument.equalsIgnoreCase("#null")) { - return new NullExtent(); - } - DefaultTransformParser parser = Fawe.get().getTransformParser(); - ParserContext parserContext = new ParserContext(); - if (actor instanceof Entity) { - Extent extent = ((Entity) actor).getExtent(); - if (extent instanceof World) { - parserContext.setWorld((World) extent); - } - } - parserContext.setSession(WorldEdit.getInstance().getSessionManager().get(actor)); - return parser.parseFromInput(argument, parserContext); - } +// TODO: Ping @MattBDev to reimplement 2020-02-04 +// +// /** +// * Gets an {@link Extent} from a {@link Binding}. +// * +// * @param argument the context +// * @return an extent +// * @throws InputParseException on other error +// */ +// @Binding +// public ResettableExtent getResettableExtent(Actor actor, String argument) throws InputParseException { +// if (argument.equalsIgnoreCase("#null")) { +// return new NullExtent(); +// } +// DefaultTransformParser parser = Fawe.get().getTransformParser(); +// ParserContext parserContext = new ParserContext(); +// if (actor instanceof Entity) { +// Extent extent = ((Entity) actor).getExtent(); +// if (extent instanceof World) { +// parserContext.setWorld((World) extent); +// } +// } +// parserContext.setSession(WorldEdit.getInstance().getSessionManager().get(actor)); +// return parser.parseFromInput(argument, parserContext); +// } /** * Gets a type from a {@link Binding}. diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/ProvideBindings.java b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/ProvideBindings.java index 653bc69ce..8a859a296 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/ProvideBindings.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/extension/platform/binding/ProvideBindings.java @@ -1,6 +1,5 @@ package com.sk89q.worldedit.extension.platform.binding; -import com.boydti.fawe.command.CFICommands; import com.boydti.fawe.config.Caption; import com.boydti.fawe.database.DBHandler; import com.boydti.fawe.database.RollbackDatabase; 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 927b195c4..9f2335d57 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 @@ -19,7 +19,6 @@ package com.sk89q.worldedit.internal.command; -import static com.google.common.base.Preconditions.checkNotNull; import com.sk89q.worldedit.IncompleteRegionException; import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.WorldEdit; @@ -40,6 +39,8 @@ import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; +import static com.google.common.base.Preconditions.checkNotNull; + /** * Logs called commands to a logger. */ diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandRegistrationHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandRegistrationHandler.java index 0697250a2..1a0b440cb 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandRegistrationHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandRegistrationHandler.java @@ -31,7 +31,6 @@ public class CommandRegistrationHandler { private static final CommandPermissionsConditionGenerator PERM_GEN = new CommandPermissionsConditionGenerator(); - private final List callListeners; public CommandRegistrationHandler(List callListeners) { diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandUtil.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandUtil.java index 2b06f539b..64c0324a4 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandUtil.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/CommandUtil.java @@ -54,13 +54,13 @@ public class CommandUtil { private static Component makeDeprecatedFooter(String reason, Component newCommand) { return TextComponent.builder() - .append(DEPRECATION_MARKER) - .append(" " + reason + ".") - .append(TextComponent.newline()) - .append(TextComponent.of("Use ", TextColor.GOLD, TextDecoration.ITALIC)) - .append(newCommand) - .append(TextComponent.of(" instead.", TextColor.GOLD, TextDecoration.ITALIC)) - .build(); + .append(DEPRECATION_MARKER) + .append(" " + reason + ".") + .append(TextComponent.newline()) + .append(TextComponent.of("Use ", TextColor.GOLD, TextDecoration.ITALIC)) + .append(newCommand) + .append(TextComponent.of(" instead.", TextColor.GOLD, TextDecoration.ITALIC)) + .build(); } public interface NewCommandGenerator { @@ -72,45 +72,45 @@ public class CommandUtil { public static Command deprecate(Command command, String reason, NewCommandGenerator newCommandGenerator) { Component deprecatedWarning = makeDeprecatedFooter( - reason, - newCommandSuggestion(newCommandGenerator, - NoInputCommandParameters.builder().build(), - command) + reason, + newCommandSuggestion(newCommandGenerator, + NoInputCommandParameters.builder().build(), + command) ); return command.toBuilder() - .action(parameters -> - deprecatedCommandWarning(parameters, command, reason, newCommandGenerator)) - .footer(command.getFooter() - .map(existingFooter -> existingFooter - .append(TextComponent.newline()).append(deprecatedWarning)) - .orElse(deprecatedWarning)) - .build(); + .action(parameters -> + deprecatedCommandWarning(parameters, command, reason, newCommandGenerator)) + .footer(command.getFooter() + .map(existingFooter -> existingFooter + .append(TextComponent.newline()).append(deprecatedWarning)) + .orElse(deprecatedWarning)) + .build(); } public static Optional footerWithoutDeprecation(Command command) { return command.getFooter() - .filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER))) - .map(footer -> Optional.of( - replaceDeprecation(footer) - )) - .orElseGet(command::getFooter); + .filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER))) + .map(footer -> Optional.of( + replaceDeprecation(footer) + )) + .orElseGet(command::getFooter); } public static Optional deprecationWarning(Command command) { return command.getFooter() - .map(CommandUtil::extractDeprecation) - .orElseGet(command::getFooter); + .map(CommandUtil::extractDeprecation) + .orElseGet(command::getFooter); } public static boolean isDeprecated(Command command) { return command.getFooter() - .filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER))) - .isPresent(); + .filter(footer -> anyComponent(footer, Predicate.isEqual(DEPRECATION_MARKER))) + .isPresent(); } private static boolean anyComponent(Component component, Predicate test) { return test.test(component) || component.children().stream() - .anyMatch(x -> anyComponent(x, test)); + .anyMatch(x -> anyComponent(x, test)); } private static Component replaceDeprecation(Component component) { @@ -118,9 +118,9 @@ public class CommandUtil { return TextComponent.empty(); } return component.children( - component.children().stream() - .map(CommandUtil::replaceDeprecation) - .collect(toList()) + component.children().stream() + .map(CommandUtil::replaceDeprecation) + .collect(toList()) ); } @@ -129,26 +129,26 @@ public class CommandUtil { return Optional.of(component); } return component.children().stream() - .map(CommandUtil::extractDeprecation) - .filter(Optional::isPresent) - .map(Optional::get) - .findAny(); + .map(CommandUtil::extractDeprecation) + .filter(Optional::isPresent) + .map(Optional::get) + .findAny(); } - private static Object deprecatedCommandWarning( - CommandParameters parameters, - Command command, - String reason, - NewCommandGenerator generator + private static int deprecatedCommandWarning( + CommandParameters parameters, + Command command, + String reason, + NewCommandGenerator generator ) throws Exception { parameters.injectedValue(Key.of(Actor.class)) - .ifPresent(actor -> { - Component suggestion = newCommandSuggestion(generator, parameters, command); - actor.print(TextComponent.of(reason + ". Please use ", TextColor.GOLD) - .append(suggestion) - .append(TextComponent.of(" instead.")) - ); - }); + .ifPresent(actor -> { + Component suggestion = newCommandSuggestion(generator, parameters, command); + actor.print(TextComponent.of(reason + ". Please use ", TextColor.GOLD) + .append(suggestion) + .append(TextComponent.of(" instead.")) + ); + }); return command.getAction().run(parameters); } @@ -157,15 +157,15 @@ public class CommandUtil { Command command) { String suggestedCommand = generator.newCommand(command, parameters); return TextComponent.of(suggestedCommand) - .decoration(TextDecoration.UNDERLINED, true) - .clickEvent(ClickEvent.suggestCommand(suggestedCommand)); + .decoration(TextDecoration.UNDERLINED, true) + .clickEvent(ClickEvent.suggestCommand(suggestedCommand)); } public static Map getSubCommands(Command currentCommand) { return currentCommand.getParts().stream() - .filter(p -> p instanceof SubCommandPart) - .flatMap(p -> ((SubCommandPart) p).getCommands().stream()) - .collect(Collectors.toMap(Command::getName, Function.identity())); + .filter(p -> p instanceof SubCommandPart) + .flatMap(p -> ((SubCommandPart) p).getCommands().stream()) + .collect(Collectors.toMap(Command::getName, Function.identity())); } private static String clean(String input) { @@ -173,7 +173,7 @@ public class CommandUtil { } private static final Comparator BY_CLEAN_NAME = - Comparator.comparing(c -> clean(c.getName())); + Comparator.comparing(c -> clean(c.getName())); public static Comparator byCleanName() { return BY_CLEAN_NAME; @@ -184,15 +184,15 @@ public class CommandUtil { */ public static List fixSuggestions(String arguments, List suggestions) { Substring lastArg = Iterables.getLast( - CommandArgParser.spaceSplit(arguments) + CommandArgParser.spaceSplit(arguments) ); return suggestions.stream() - // Re-map suggestions to only operate on the last non-quoted word - .map(suggestion -> onlyOnLastQuotedWord(lastArg, suggestion)) - .map(suggestion -> suggestLast(lastArg, suggestion)) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(toList()); + // Re-map suggestions to only operate on the last non-quoted word + .map(suggestion -> onlyOnLastQuotedWord(lastArg, suggestion)) + .map(suggestion -> suggestLast(lastArg, suggestion)) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(toList()); } private static Substring onlyOnLastQuotedWord(Substring lastArg, Substring suggestion) { @@ -228,7 +228,7 @@ public class CommandUtil { return Optional.empty(); } checkState(end <= builder.length(), - "Suggestion ends too late, last=%s, suggestion=", last, suggestion); + "Suggestion ends too late, last=%s, suggestion=", last, suggestion); builder.replace(start, end, suggestion.getSubstring()); return Optional.of(builder.toString()); } @@ -259,10 +259,10 @@ public class CommandUtil { public static T requireIV(Key type, String name, InjectedValueAccess injectedValueAccess) { return injectedValueAccess.injectedValue(type).orElseThrow(() -> - new IllegalStateException("No injected value for " + name + " (type " + type + ")") + new IllegalStateException("No injected value for " + name + " (type " + type + ")") ); } private CommandUtil() { } -} \ No newline at end of file +} diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/ConfirmHandler.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/ConfirmHandler.java index 0ed6eee07..3f3f7786a 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/ConfirmHandler.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/ConfirmHandler.java @@ -22,6 +22,7 @@ package com.sk89q.worldedit.internal.command; import com.sk89q.worldedit.command.util.annotation.Confirm; import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.util.formatting.text.TextComponent; +import java.util.Optional; import org.enginehub.piston.CommandParameters; import org.enginehub.piston.exception.StopExecutionException; import org.enginehub.piston.gen.CommandCallListener; @@ -39,7 +40,12 @@ public class ConfirmHandler implements CommandCallListener { if (confirmAnnotation == null) { return; } - Actor actor = parameters.injectedValue(Key.of(Actor.class)).get(); + Optional actorOpt = parameters.injectedValue(Key.of(Actor.class)); + + if (!actorOpt.isPresent()) { + return; + } + Actor actor = actorOpt.get(); if (!confirmAnnotation.value().passes(actor, parameters, 1)) { throw new StopExecutionException(TextComponent.empty()); } diff --git a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/exception/WorldEditExceptionConverter.java b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/exception/WorldEditExceptionConverter.java index 07e4e5648..9f6a40fe0 100644 --- a/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/exception/WorldEditExceptionConverter.java +++ b/worldedit-core/src/main/java/com/sk89q/worldedit/internal/command/exception/WorldEditExceptionConverter.java @@ -40,11 +40,12 @@ import com.sk89q.worldedit.util.formatting.text.TextComponent; import com.sk89q.worldedit.util.io.file.FileSelectionAbortedException; import com.sk89q.worldedit.util.io.file.FilenameResolutionException; import com.sk89q.worldedit.util.io.file.InvalidFilenameException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import org.enginehub.piston.exception.CommandException; import org.enginehub.piston.exception.UsageException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import static com.google.common.base.Preconditions.checkNotNull; /** diff --git a/worldedit-libs/core/ap/build.gradle.kts b/worldedit-libs/core/ap/build.gradle.kts index cfac0cf24..44374359b 100644 --- a/worldedit-libs/core/ap/build.gradle.kts +++ b/worldedit-libs/core/ap/build.gradle.kts @@ -1,9 +1,6 @@ applyLibrariesConfiguration() dependencies { - "shade"("FAWE-Piston:core/build/libs/core-${Versions.PISTON}:lastSuccessfulBuild@jar") - "shade"("FAWE-Piston:core-ap/annotations/build/libs/annotations-${Versions.PISTON}:lastSuccessfulBuild@jar") - "shade"("FAWE-Piston:core-ap/processor/build/libs/processor-${Versions.PISTON}:lastSuccessfulBuild@jar") "shade"("org.enginehub.piston.core-ap:annotations:${Versions.PISTON}") "shade"("org.enginehub.piston.core-ap:processor:${Versions.PISTON}") } diff --git a/worldedit-libs/core/build.gradle.kts b/worldedit-libs/core/build.gradle.kts index 1b4dbc30d..915c530b5 100644 --- a/worldedit-libs/core/build.gradle.kts +++ b/worldedit-libs/core/build.gradle.kts @@ -8,10 +8,10 @@ dependencies { "shade"("com.sk89q:jchronic:0.2.4a") { exclude(group = "junit", module = "junit") } + "shade"("com.thoughtworks.paranamer:paranamer:2.6") "shade"("com.github.luben:zstd-jni:1.4.3-1") "shade"("com.sk89q.lib:jlibnoise:1.0.0") - "shade"("FAWE-Piston:core/build/libs/core-${Versions.PISTON}:lastSuccessfulBuild@jar") - "shade"("FAWE-Piston:core-ap/runtime/build/libs/runtime-${Versions.PISTON}:lastSuccessfulBuild@jar") - "shade"("FAWE-Piston:default-impl/build/libs/default-impl-${Versions.PISTON}:lastSuccessfulBuild@jar") - + "shade"("org.enginehub.piston:core:${Versions.PISTON}") + "shade"("org.enginehub.piston.core-ap:runtime:${Versions.PISTON}") + "shade"("org.enginehub.piston:default-impl:${Versions.PISTON}") }