Major command changes that don't work yet.

This commit is contained in:
MattBDev 2019-07-05 20:46:48 -04:00
parent ffc2092d93
commit 8108d0a936
399 changed files with 13558 additions and 7985 deletions

View File

@ -38,30 +38,31 @@ println """
******************************************* *******************************************
""" """
group = 'com.boydti.fawe' allprojects {
group = 'com.boydti.fawe'
def rootVersion = "1.13" def rootVersion = "1.13"
def revision = "" def revision = ""
def buildNumber = "" def buildNumber = ""
def date = "" def date = ""
ext { ext {
git = Grgit.open(dir: '.git') git = Grgit.open(dir: '.git')
date = git.head().getDate().format("yy.MM.dd") date = git.head().getDate().format("yy.MM.dd")
revision = "-${git.head().abbreviatedId}" revision = "-${git.head().abbreviatedId}"
parents = git.head().parentIds; parents = git.head().parentIds;
if (project.hasProperty('buildnumber')) { if (project.hasProperty('buildnumber')) {
buildNumber = "$buildnumber" buildNumber = "$buildnumber"
} else { } else {
index = -2109; // Offset to match CI index = -2109; // Offset to match CI
for (; parents != null && !parents.isEmpty(); index++) { for (; parents != null && !parents.isEmpty(); index++) {
parents = git.getResolve().toCommit(parents.get(0)).getParentIds() parents = git.getResolve().toCommit(parents.get(0)).getParentIds()
}
buildNumber = "${index}"
} }
buildNumber = "${index}"
} }
version = String.format("%s.%s", rootVersion, buildNumber)
} }
version = String.format("%s.%s", rootVersion, buildNumber)
description = rootProject.name description = rootProject.name
subprojects { subprojects {
@ -97,6 +98,7 @@ configure(['worldedit-core', 'worldedit-bukkit', 'favs'].collect { project("$it"
apply plugin: 'maven' apply plugin: 'maven'
// apply plugin: 'checkstyle' // apply plugin: 'checkstyle'
apply plugin: 'com.github.johnrengelman.shadow' apply plugin: 'com.github.johnrengelman.shadow'
// apply plugin: 'com.jfrog.artifactory'
// Enable this requires putting license header files in many, many FAWE files // Enable this requires putting license header files in many, many FAWE files
// apply plugin: 'net.minecrell.licenser' // apply plugin: 'net.minecrell.licenser'
@ -117,7 +119,7 @@ configure(['worldedit-core', 'worldedit-bukkit', 'favs'].collect { project("$it"
} }
} }
if (!(name.equals('worldedit-forge') || name.equals('worldedit-sponge'))) { if (name == "worldedit-core" || name == "worldedit-bukkit") {
task sourcesJar(type: Jar, dependsOn: classes) { task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources' classifier = 'sources'
from sourceSets.main.allSource from sourceSets.main.allSource
@ -131,6 +133,11 @@ configure(['worldedit-core', 'worldedit-bukkit', 'favs'].collect { project("$it"
// build.dependsOn(checkstyleMain) // build.dependsOn(checkstyleMain)
// build.dependsOn(checkstyleTest) // build.dependsOn(checkstyleTest)
// build.dependsOn(javadocJar)
//
// artifactoryPublish {
// publishConfigs('archives')
// }
dependencies { dependencies {
compileOnly 'org.jetbrains:annotations:17.0.0' compileOnly 'org.jetbrains:annotations:17.0.0'
@ -176,5 +183,4 @@ configure(['worldedit-core', 'worldedit-bukkit', 'favs'].collect { project("$it"
} }
} }
} }

View File

@ -51,6 +51,7 @@ import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypes;
import com.thevoxelbox.voxelsniper.brush.IBrush; import com.thevoxelbox.voxelsniper.brush.IBrush;
import com.thevoxelbox.voxelsniper.brush.JockeyBrush;
import com.thevoxelbox.voxelsniper.brush.SnipeBrush; import com.thevoxelbox.voxelsniper.brush.SnipeBrush;
import com.thevoxelbox.voxelsniper.brush.perform.PerformBrush; import com.thevoxelbox.voxelsniper.brush.perform.PerformBrush;
import com.thevoxelbox.voxelsniper.brush.perform.Performer; import com.thevoxelbox.voxelsniper.brush.perform.Performer;
@ -201,22 +202,21 @@ public class Sniper {
changeQueue = new ChangeSetFaweQueue(changeSet, maskQueue); changeQueue = new ChangeSetFaweQueue(changeSet, maskQueue);
} }
LocalSession session = fp.getSession(); LocalSession session = fp.getSession();
{ // Set mask etc // Set mask etc
Mask destMask = session.getMask(); Mask destMask = session.getMask();
if (!Masks.isNull(destMask)) { if (!Masks.isNull(destMask)) {
new MaskTraverser(destMask).reset(changeQueue); new MaskTraverser(destMask).reset(changeQueue);
changeQueue = new FaweQueueDelegateExtent(changeQueue, new MaskingExtent(changeQueue, destMask)); changeQueue = new FaweQueueDelegateExtent(changeQueue, new MaskingExtent(changeQueue, destMask));
} }
Mask sourceMask = session.getSourceMask(); Mask sourceMask = session.getSourceMask();
if (!Masks.isNull(sourceMask)) { if (!Masks.isNull(sourceMask)) {
new MaskTraverser(sourceMask).reset(changeQueue); new MaskTraverser(sourceMask).reset(changeQueue);
changeQueue = new FaweQueueDelegateExtent(changeQueue, new SourceMaskExtent(changeQueue, sourceMask)); changeQueue = new FaweQueueDelegateExtent(changeQueue, new SourceMaskExtent(changeQueue, sourceMask));
} }
ResettableExtent transform = session.getTransform(); ResettableExtent transform = session.getTransform();
if (transform != null) { if (transform != null) {
transform.setExtent(changeQueue); transform.setExtent(changeQueue);
changeQueue = new FaweQueueDelegateExtent(changeQueue, transform); changeQueue = new FaweQueueDelegateExtent(changeQueue, transform);
}
} }
AsyncWorld world = getWorld(); AsyncWorld world = getWorld();
@ -369,22 +369,19 @@ public class Sniper {
snipeData.setExtent(world); snipeData.setExtent(world);
Request.reset(); Request.reset();
Request.request().setExtent(world); Request.request().setExtent(world);
switch (brush.getClass().getSimpleName()) { if (brush instanceof JockeyBrush) {
case "JockeyBrush": TaskManager.IMP.sync(new RunnableVal<Object>() {
TaskManager.IMP.sync(new RunnableVal<Object>() { @Override
@Override public void run(Object value) {
public void run(Object value) { brush.perform(snipeAction, snipeData, targetBlock, lastBlock);
brush.perform(snipeAction, snipeData, targetBlock, lastBlock);
}
});
break;
default:
if (sniperTool.getCurrentBrush() instanceof PerformBrush) {
PerformBrush performerBrush = (PerformBrush) sniperTool.getCurrentBrush();
performerBrush.initP(snipeData);
} }
brush.perform(snipeAction, snipeData, targetBlock, lastBlock); });
break; } else {
if (sniperTool.getCurrentBrush() instanceof PerformBrush) {
PerformBrush performerBrush = (PerformBrush) sniperTool.getCurrentBrush();
performerBrush.initP(snipeData);
}
brush.perform(snipeAction, snipeData, targetBlock, lastBlock);
} }
} finally { } finally {
snipeData.setExtent(null); snipeData.setExtent(null);

View File

@ -3,7 +3,7 @@ package com.thevoxelbox.voxelsniper;
import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.BBC;
import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FawePlayer;
import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.util.command.parametric.ExceptionConverter; import com.sk89q.worldedit.util.command.parametric.ExceptionConverter;
import com.thevoxelbox.voxelsniper.api.command.VoxelCommand; import com.thevoxelbox.voxelsniper.api.command.VoxelCommand;
import com.thevoxelbox.voxelsniper.command.*; import com.thevoxelbox.voxelsniper.command.*;
@ -71,7 +71,7 @@ public class VoxelSniperListener implements Listener {
FawePlayer fp = FawePlayer.wrap(player); FawePlayer fp = FawePlayer.wrap(player);
if (!fp.runAction(() -> { if (!fp.runAction(() -> {
ExceptionConverter exceptionConverter = CommandManager.getInstance().getExceptionConverter(); ExceptionConverter exceptionConverter = PlatformCommandManager.getInstance().getExceptionConverter();
try { try {
try { try {
found.onCommand(player, split); found.onCommand(player, split);

View File

@ -37,8 +37,6 @@ dependencies {
compile 'com.thevoxelbox.voxelsniper:voxelsniper:5.171.0' compile 'com.thevoxelbox.voxelsniper:voxelsniper:5.171.0'
compile 'com.comphenix.protocol:ProtocolLib-API:4.4.0-SNAPSHOT' compile 'com.comphenix.protocol:ProtocolLib-API:4.4.0-SNAPSHOT'
compile 'com.wasteofplastic:askyblock:3.0.8.2' compile 'com.wasteofplastic:askyblock:3.0.8.2'
compileOnly 'com.sk89q.worldguard:worldguard-core:7.0.0-20190215.210421-39'
compileOnly 'com.sk89q.worldguard:worldguard-legacy:7.0.0-20190215.210421-39'
} }
processResources { processResources {
@ -49,6 +47,10 @@ processResources {
) )
include 'plugin.yml' include 'plugin.yml'
} }
// from (zipTree('src/main/resources/worldedit-adapters.jar').matching {
// exclude 'META-INF/'
// })
// exclude '**/worldedit-adapters.jar'
} }
jar.archiveName="fawe-bukkit-${project.parent.version}.jar" jar.archiveName="fawe-bukkit-${project.parent.version}.jar"

View File

@ -3,22 +3,10 @@ package com.boydti.fawe.bukkit;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.IFawe; import com.boydti.fawe.IFawe;
import com.boydti.fawe.bukkit.chat.BukkitChatManager; import com.boydti.fawe.bukkit.chat.BukkitChatManager;
import com.boydti.fawe.bukkit.listener.AsyncTabCompleteListener;
import com.boydti.fawe.bukkit.listener.BrushListener; import com.boydti.fawe.bukkit.listener.BrushListener;
import com.boydti.fawe.bukkit.listener.BukkitImageListener; import com.boydti.fawe.bukkit.listener.BukkitImageListener;
import com.boydti.fawe.bukkit.listener.RenderListener; import com.boydti.fawe.bukkit.listener.RenderListener;
import com.boydti.fawe.bukkit.listener.SyncTabCompleteListener; import com.boydti.fawe.bukkit.regions.*;
import com.boydti.fawe.bukkit.regions.ASkyBlockHook;
import com.boydti.fawe.bukkit.regions.FactionsFeature;
import com.boydti.fawe.bukkit.regions.FactionsOneFeature;
import com.boydti.fawe.bukkit.regions.FactionsUUIDFeature;
import com.boydti.fawe.bukkit.regions.FreeBuildRegion;
import com.boydti.fawe.bukkit.regions.GriefPreventionFeature;
import com.boydti.fawe.bukkit.regions.PreciousStonesFeature;
import com.boydti.fawe.bukkit.regions.ResidenceFeature;
import com.boydti.fawe.bukkit.regions.TownyFeature;
import com.boydti.fawe.bukkit.regions.Worldguard;
import com.boydti.fawe.bukkit.regions.WorldguardFlag;
import com.boydti.fawe.bukkit.util.BukkitReflectionUtils; import com.boydti.fawe.bukkit.util.BukkitReflectionUtils;
import com.boydti.fawe.bukkit.util.BukkitTaskMan; import com.boydti.fawe.bukkit.util.BukkitTaskMan;
import com.boydti.fawe.bukkit.util.ItemUtil; import com.boydti.fawe.bukkit.util.ItemUtil;
@ -39,7 +27,7 @@ import com.boydti.fawe.util.Jars;
import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.TaskManager;
import com.boydti.fawe.util.image.ImageViewer; import com.boydti.fawe.util.image.ImageViewer;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.ConsoleCommandSender;
@ -127,18 +115,6 @@ public class FaweBukkit implements IFawe, Listener {
new ChunkListener_9(); new ChunkListener_9();
} }
try {
Class.forName("com.destroystokyo.paper.event.server.AsyncTabCompleteEvent");
Bukkit.getPluginManager().registerEvents(new AsyncTabCompleteListener(WorldEditPlugin.getInstance()), plugin);
} catch (Throwable ignore) {
debug("====== USE PAPER ======");
debug("DOWNLOAD: https://papermc.io/ci/job/Paper-1.13/");
debug("GUIDE: https://www.spigotmc.org/threads/21726/");
debug(" - This is only a recommendation");
debug(" - Allows the use of Async Tab Completetion as provided by Paper");
debug("==============================");
Bukkit.getPluginManager().registerEvents(new SyncTabCompleteListener(WorldEditPlugin.getInstance()), plugin);
}
}); });
} }
@ -405,7 +381,7 @@ public class FaweBukkit implements IFawe, Listener {
public Collection<FaweMaskManager> getMaskManagers() { public Collection<FaweMaskManager> getMaskManagers() {
final Plugin worldguardPlugin = Bukkit.getServer().getPluginManager().getPlugin("WorldGuard"); final Plugin worldguardPlugin = Bukkit.getServer().getPluginManager().getPlugin("WorldGuard");
final ArrayList<FaweMaskManager> managers = new ArrayList<>(); final ArrayList<FaweMaskManager> managers = new ArrayList<>();
if ((worldguardPlugin != null) && worldguardPlugin.isEnabled()) { if (worldguardPlugin != null && worldguardPlugin.isEnabled()) {
try { try {
managers.add(new Worldguard(worldguardPlugin, this)); managers.add(new Worldguard(worldguardPlugin, this));
managers.add(new WorldguardFlag(worldguardPlugin, this)); managers.add(new WorldguardFlag(worldguardPlugin, this));
@ -415,7 +391,7 @@ public class FaweBukkit implements IFawe, Listener {
} }
} }
final Plugin townyPlugin = Bukkit.getServer().getPluginManager().getPlugin("Towny"); final Plugin townyPlugin = Bukkit.getServer().getPluginManager().getPlugin("Towny");
if ((townyPlugin != null) && townyPlugin.isEnabled()) { if (townyPlugin != null && townyPlugin.isEnabled()) {
try { try {
managers.add(new TownyFeature(townyPlugin, this)); managers.add(new TownyFeature(townyPlugin, this));
Fawe.debug("Plugin 'Towny' found. Using it now."); Fawe.debug("Plugin 'Towny' found. Using it now.");
@ -424,7 +400,7 @@ public class FaweBukkit implements IFawe, Listener {
} }
} }
final Plugin factionsPlugin = Bukkit.getServer().getPluginManager().getPlugin("Factions"); final Plugin factionsPlugin = Bukkit.getServer().getPluginManager().getPlugin("Factions");
if ((factionsPlugin != null) && factionsPlugin.isEnabled()) { if (factionsPlugin != null && factionsPlugin.isEnabled()) {
try { try {
managers.add(new FactionsFeature(factionsPlugin)); managers.add(new FactionsFeature(factionsPlugin));
Fawe.debug("Plugin 'Factions' found. Using it now."); Fawe.debug("Plugin 'Factions' found. Using it now.");
@ -444,7 +420,7 @@ public class FaweBukkit implements IFawe, Listener {
} }
} }
final Plugin residencePlugin = Bukkit.getServer().getPluginManager().getPlugin("Residence"); final Plugin residencePlugin = Bukkit.getServer().getPluginManager().getPlugin("Residence");
if ((residencePlugin != null) && residencePlugin.isEnabled()) { if (residencePlugin != null && residencePlugin.isEnabled()) {
try { try {
managers.add(new ResidenceFeature(residencePlugin, this)); managers.add(new ResidenceFeature(residencePlugin, this));
Fawe.debug("Plugin 'Residence' found. Using it now."); Fawe.debug("Plugin 'Residence' found. Using it now.");
@ -453,7 +429,7 @@ public class FaweBukkit implements IFawe, Listener {
} }
} }
final Plugin griefpreventionPlugin = Bukkit.getServer().getPluginManager().getPlugin("GriefPrevention"); final Plugin griefpreventionPlugin = Bukkit.getServer().getPluginManager().getPlugin("GriefPrevention");
if ((griefpreventionPlugin != null) && griefpreventionPlugin.isEnabled()) { if (griefpreventionPlugin != null && griefpreventionPlugin.isEnabled()) {
try { try {
managers.add(new GriefPreventionFeature(griefpreventionPlugin)); managers.add(new GriefPreventionFeature(griefpreventionPlugin));
Fawe.debug("Plugin 'GriefPrevention' found. Using it now."); Fawe.debug("Plugin 'GriefPrevention' found. Using it now.");
@ -462,7 +438,7 @@ public class FaweBukkit implements IFawe, Listener {
} }
} }
final Plugin preciousstonesPlugin = Bukkit.getServer().getPluginManager().getPlugin("PreciousStones"); final Plugin preciousstonesPlugin = Bukkit.getServer().getPluginManager().getPlugin("PreciousStones");
if ((preciousstonesPlugin != null) && preciousstonesPlugin.isEnabled()) { if (preciousstonesPlugin != null && preciousstonesPlugin.isEnabled()) {
try { try {
managers.add(new PreciousStonesFeature(preciousstonesPlugin, this)); managers.add(new PreciousStonesFeature(preciousstonesPlugin, this));
Fawe.debug("Plugin 'PreciousStones' found. Using it now."); Fawe.debug("Plugin 'PreciousStones' found. Using it now.");
@ -473,7 +449,7 @@ public class FaweBukkit implements IFawe, Listener {
final Plugin aSkyBlock = Bukkit.getServer().getPluginManager().getPlugin("ASkyBlock"); final Plugin aSkyBlock = Bukkit.getServer().getPluginManager().getPlugin("ASkyBlock");
if ((aSkyBlock != null) && aSkyBlock.isEnabled()) { if (aSkyBlock != null && aSkyBlock.isEnabled()) {
try { try {
managers.add(new ASkyBlockHook(aSkyBlock)); managers.add(new ASkyBlockHook(aSkyBlock));
Fawe.debug("Plugin 'ASkyBlock' found. Using it now."); Fawe.debug("Plugin 'ASkyBlock' found. Using it now.");
@ -492,20 +468,6 @@ public class FaweBukkit implements IFawe, Listener {
return managers; return managers;
} }
//
// @EventHandler
// public void onWorldLoad(WorldLoadEvent event) {
// org.bukkit.World world = event.getWorld();
// world.setKeepSpawnInMemory(false);
// WorldServer nmsWorld = ((CraftWorld) world).getHandle();
// ChunkProviderServer provider = nmsWorld.getChunkProviderServer();
// try {
// Field fieldChunkLoader = provider.getClass().getDeclaredField("chunkLoader");
// ReflectionUtils.setFailsafeFieldValue(fieldChunkLoader, provider, new FaweChunkLoader());
// } catch (Throwable e) {
// e.printStackTrace();
// }
// }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) { public void onPlayerQuit(PlayerQuitEvent event) {

View File

@ -1,41 +0,0 @@
package com.boydti.fawe.bukkit.listener;
import com.boydti.fawe.object.string.MutableCharSequence;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.event.platform.CommandSuggestionEvent;
import com.sk89q.worldedit.extension.platform.CommandManager;
import com.sk89q.worldedit.util.command.CommandMapping;
import com.sk89q.worldedit.util.command.Dispatcher;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Listener;
import java.util.List;
public class ATabCompleteListener implements Listener {
private final WorldEditPlugin worldEdit;
public ATabCompleteListener(WorldEditPlugin worldEdit) {
this.worldEdit = worldEdit;
}
public List<String> onTab(String buffer, CommandSender sender) {
int firstSpace = buffer.indexOf(' ');
if (firstSpace == -1) return null;
MutableCharSequence mBuffer = MutableCharSequence.getTemporal();
mBuffer.setString(buffer);
mBuffer.setSubstring(0, firstSpace);
int index;
String label = buffer.substring(index = (mBuffer.indexOf(':') == -1 ? 1 : mBuffer.indexOf(':') + 1), firstSpace);
Dispatcher dispatcher = CommandManager.getInstance().getDispatcher();
CommandMapping weCommand = dispatcher.get(label);
if (weCommand != null) {
CommandSuggestionEvent event = new CommandSuggestionEvent(worldEdit.wrapCommandSender(sender), buffer.substring(index));
worldEdit.getWorldEdit().getEventBus().post(event);
List<String> suggestions = event.getSuggestions();
if (suggestions != null && !suggestions.isEmpty()) {
return suggestions;
}
}
return null;
}
}

View File

@ -1,29 +0,0 @@
package com.boydti.fawe.bukkit.listener;
import com.boydti.fawe.util.TaskManager;
import com.destroystokyo.paper.event.server.AsyncTabCompleteEvent;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.server.TabCompleteEvent;
import java.util.Collections;
import java.util.List;
public class AsyncTabCompleteListener extends ATabCompleteListener {
public AsyncTabCompleteListener(WorldEditPlugin worldEdit) {
super(worldEdit);
}
@EventHandler
public void onTabComplete(AsyncTabCompleteEvent event) {
if (event.isCommand()) {
List<String> result = this.onTab(event.getBuffer(), event.getSender());
if (result != null && !result.isEmpty()) {
event.setCompletions(result);
event.setHandled(true);
}
}
}
}

View File

@ -1,6 +1,5 @@
package com.boydti.fawe.bukkit.listener; package com.boydti.fawe.bukkit.listener;
import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.object.brush.MovableTool; import com.boydti.fawe.object.brush.MovableTool;
import com.boydti.fawe.object.brush.ResettableTool; import com.boydti.fawe.object.brush.ResettableTool;
@ -17,8 +16,6 @@ import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
public class BrushListener implements Listener { public class BrushListener implements Listener {
@ -47,16 +44,7 @@ public class BrushListener implements Listener {
} }
ScrollTool scrollable = (ScrollTool) tool; ScrollTool scrollable = (ScrollTool) tool;
if (scrollable.increment(player, ri)) { if (scrollable.increment(player, ri)) {
if (Settings.IMP.EXPERIMENTAL.PERSISTENT_BRUSHES) { bukkitPlayer.getInventory().setHeldItemSlot(oldSlot);
bukkitPlayer.getInventory().setHeldItemSlot(oldSlot);
} else {
final PlayerInventory inv = bukkitPlayer.getInventory();
final ItemStack item = inv.getItem(slot);
final ItemStack newItem = inv.getItem(oldSlot);
inv.setItem(slot, newItem);
inv.setItem(oldSlot, item);
bukkitPlayer.updateInventory();
}
} }
} }
} }

View File

@ -49,6 +49,7 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
public class BukkitImageListener implements Listener { public class BukkitImageListener implements Listener {
private Location mutable = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); private Location mutable = new Location(Bukkit.getWorlds().get(0), 0, 0, 0);
public BukkitImageListener(Plugin plugin) { public BukkitImageListener(Plugin plugin) {
@ -61,19 +62,20 @@ public class BukkitImageListener implements Listener {
Iterator<Player> iter = recipients.iterator(); Iterator<Player> iter = recipients.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Player player = iter.next(); Player player = iter.next();
if (player.equals(event.getPlayer())) continue;
FawePlayer<Object> fp = FawePlayer.wrap(player); FawePlayer<Object> fp = FawePlayer.wrap(player);
if (!fp.hasMeta()) continue;
CFICommands.CFISettings settings = fp.getMeta("CFISettings"); CFICommands.CFISettings settings = fp.getMeta("CFISettings");
if (settings == null || !settings.hasGenerator()) continue; if (player.equals(event.getPlayer()) || !fp.hasMeta() || settings == null || !settings.hasGenerator()) {
continue;
}
String name = player.getName().toLowerCase(); String name = player.getName().toLowerCase();
if (!event.getMessage().toLowerCase().contains(name)) { if (!event.getMessage().toLowerCase().contains(name)) {
ArrayDeque<String> buffered = fp.getMeta("CFIBufferedMessages"); ArrayDeque<String> buffered = fp.getMeta("CFIBufferedMessages");
if (buffered == null) fp.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque<>()); if (buffered == null) {
String full = String.format(event.getFormat(), event.getPlayer().getDisplayName(), event.getMessage()); fp.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque<>());
}
String full = String.format(event.getFormat(), event.getPlayer().getDisplayName(),
event.getMessage());
buffered.add(full); buffered.add(full);
iter.remove(); iter.remove();
} }
@ -82,29 +84,42 @@ public class BukkitImageListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onHangingBreakByEntity(HangingBreakByEntityEvent event) { public void onHangingBreakByEntity(HangingBreakByEntityEvent event) {
if(!(event.getRemover() instanceof Player)) return; if (!(event.getRemover() instanceof Player)) {
return;
}
handleInteract(event, (Player) event.getRemover(), event.getEntity(), false); handleInteract(event, (Player) event.getRemover(), event.getEntity(), false);
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if(!(event.getDamager() instanceof Player)) return; if (!(event.getDamager() instanceof Player)) {
return;
}
handleInteract(event, (Player) event.getDamager(), event.getEntity(), false); handleInteract(event, (Player) event.getDamager(), event.getEntity(), false);
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteract(PlayerInteractEvent event) { public void onPlayerInteract(PlayerInteractEvent event) {
if (event.useItemInHand() == Event.Result.DENY) return; if (event.useItemInHand() == Event.Result.DENY) {
return;
}
Player player = event.getPlayer(); Player player = event.getPlayer();
FawePlayer<Object> fp = FawePlayer.wrap(player); FawePlayer<Object> fp = FawePlayer.wrap(player);
if (fp.getMeta("CFISettings") == null) return; if (fp.getMeta("CFISettings") == null) {
return;
}
try { try {
if (event.getHand() == EquipmentSlot.OFF_HAND) return; if (event.getHand() == EquipmentSlot.OFF_HAND) {
} catch (NoSuchFieldError | NoSuchMethodError ignored) {} return;
}
} catch (NoSuchFieldError | NoSuchMethodError ignored) {
}
List<Block> target = player.getLastTwoTargetBlocks(null, 100); List<Block> target = player.getLastTwoTargetBlocks(null, 100);
if (target.isEmpty()) return; if (target.isEmpty()) {
return;
}
Block targetBlock = target.get(0); Block targetBlock = target.get(0);
World world = player.getWorld(); World world = player.getWorld();
@ -116,7 +131,8 @@ public class BukkitImageListener implements Listener {
if (!entities.isEmpty()) { if (!entities.isEmpty()) {
Action action = event.getAction(); Action action = event.getAction();
boolean primary = action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK; boolean primary =
action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK;
double minDist = Integer.MAX_VALUE; double minDist = Integer.MAX_VALUE;
ItemFrame minItemFrame = null; ItemFrame minItemFrame = null;
@ -137,7 +153,9 @@ public class BukkitImageListener implements Listener {
} }
if (minItemFrame != null) { if (minItemFrame != null) {
handleInteract(event, minItemFrame, primary); handleInteract(event, minItemFrame, primary);
if (event.isCancelled()) return; if (event.isCancelled()) {
return;
}
} }
} }
} }
@ -148,10 +166,14 @@ public class BukkitImageListener implements Listener {
} }
private BukkitImageViewer get(HeightMapMCAGenerator generator) { private BukkitImageViewer get(HeightMapMCAGenerator generator) {
if (generator == null) return null; if (generator == null) {
return null;
}
ImageViewer viewer = generator.getImageViewer(); ImageViewer viewer = generator.getImageViewer();
if (!(viewer instanceof BukkitImageViewer)) return null; if (!(viewer instanceof BukkitImageViewer)) {
return null;
}
return (BukkitImageViewer) viewer; return (BukkitImageViewer) viewer;
} }
@ -161,14 +183,18 @@ public class BukkitImageListener implements Listener {
} }
private void handleInteract(Event event, Player player, Entity entity, boolean primary) { private void handleInteract(Event event, Player player, Entity entity, boolean primary) {
if (!(entity instanceof ItemFrame)) return; if (!(entity instanceof ItemFrame)) {
return;
}
ItemFrame itemFrame = (ItemFrame) entity; ItemFrame itemFrame = (ItemFrame) entity;
FawePlayer<Object> fp = FawePlayer.wrap(player); FawePlayer<Object> fp = FawePlayer.wrap(player);
CFICommands.CFISettings settings = fp.getMeta("CFISettings"); CFICommands.CFISettings settings = fp.getMeta("CFISettings");
HeightMapMCAGenerator generator = settings == null ? null : settings.getGenerator(); HeightMapMCAGenerator generator = settings == null ? null : settings.getGenerator();
BukkitImageViewer viewer = get(generator); BukkitImageViewer viewer = get(generator);
if (viewer == null) return; if (viewer == null) {
return;
}
if (itemFrame.getRotation() != Rotation.NONE) { if (itemFrame.getRotation() != Rotation.NONE) {
itemFrame.setRotation(Rotation.NONE); itemFrame.setRotation(Rotation.NONE);
@ -178,7 +204,9 @@ public class BukkitImageListener implements Listener {
BrushTool tool; BrushTool tool;
try { try {
tool = session.getBrushTool(fp.getPlayer(), false); tool = session.getBrushTool(fp.getPlayer(), false);
} catch (InvalidToolBindException e) { return; } } catch (InvalidToolBindException e) {
return;
}
ItemFrame[][] frames = viewer.getItemFrames(); ItemFrame[][] frames = viewer.getItemFrames();
if (frames == null || tool == null) { if (frames == null || tool == null) {
@ -190,7 +218,9 @@ public class BukkitImageListener implements Listener {
BrushSettings context = primary ? tool.getPrimary() : tool.getSecondary(); BrushSettings context = primary ? tool.getPrimary() : tool.getSecondary();
Brush brush = context.getBrush(); Brush brush = context.getBrush();
if (brush == null) return; if (brush == null) {
return;
}
tool.setContext(context); tool.setContext(context);
if (event instanceof Cancellable) { if (event instanceof Cancellable) {
@ -208,7 +238,7 @@ public class BukkitImageListener implements Listener {
double zRat = Math.sin(yawRad) * a; double zRat = Math.sin(yawRad) * a;
BlockFace facing = itemFrame.getFacing(); BlockFace facing = itemFrame.getFacing();
double thickness = 1/32D + 1/128D; double thickness = 1 / 32D + 1 / 128D;
double modX = facing.getModX(); double modX = facing.getModX();
double modZ = facing.getModZ(); double modZ = facing.getModZ();
double dx = source.getX() - target.getX() - modX * thickness; double dx = source.getX() - target.getX() - modX * thickness;
@ -225,8 +255,8 @@ public class BukkitImageListener implements Listener {
localX = (modZ) * (dx - offset * xRat); localX = (modZ) * (dx - offset * xRat);
} }
double localY = dy - offset * Math.sin(pitchRad); double localY = dy - offset * Math.sin(pitchRad);
int localPixelX = (int)((localX + 0.5) * 128); int localPixelX = (int) ((localX + 0.5) * 128);
int localPixelY = (int)((localY + 0.5) * 128); int localPixelY = (int) ((localY + 0.5) * 128);
UUID uuid = itemFrame.getUniqueId(); UUID uuid = itemFrame.getUniqueId();
for (int blockX = 0; blockX < frames.length; blockX++) { for (int blockX = 0; blockX < frames.length; blockX++) {
@ -240,18 +270,25 @@ public class BukkitImageListener implements Listener {
int worldX = (int) (pixelX * width / (frames.length * 128d)); int worldX = (int) (pixelX * width / (frames.length * 128d));
int worldZ = (int) (pixelY * length / (frames[0].length * 128d)); int worldZ = (int) (pixelY * length / (frames[0].length * 128d));
if (worldX < 0 || worldX > width || worldZ < 0 || worldZ > length) return; if (worldX < 0 || worldX > width || worldZ < 0 || worldZ > length) {
return;
}
fp.runAction(() -> { fp.runAction(() -> {
BlockVector3 wPos = BlockVector3.at(worldX, 0, worldZ); BlockVector3 wPos = BlockVector3.at(worldX, 0, worldZ);
viewer.refresh(); viewer.refresh();
int topY = generator.getNearestSurfaceTerrainBlock(wPos.getBlockX(), wPos.getBlockZ(), 255, 0, 255); int topY = generator
.getNearestSurfaceTerrainBlock(wPos.getBlockX(), wPos.getBlockZ(), 255,
0, 255);
wPos = wPos.withY(topY); wPos = wPos.withY(topY);
EditSession es = new EditSessionBuilder(fp.getWorld()).player(fp).combineStages(false).autoQueue(false).blockBag(null).limitUnlimited().build(); EditSession es = new EditSessionBuilder(fp.getWorld()).player(fp)
.combineStages(false).autoQueue(false).blockBag(null).limitUnlimited()
.build();
ExtentTraverser last = new ExtentTraverser(es.getExtent()).last(); ExtentTraverser last = new ExtentTraverser(es.getExtent()).last();
if (last.get() instanceof FastWorldEditExtent) last = last.previous(); if (last.get() instanceof FastWorldEditExtent) {
last = last.previous();
}
last.setNext(generator); last.setNext(generator);
try { try {
brush.build(es, wPos, context.getMaterial(), context.getSize()); brush.build(es, wPos, context.getMaterial(), context.getSize());
@ -262,9 +299,6 @@ public class BukkitImageListener implements Listener {
viewer.view(generator); viewer.view(generator);
}, true, true); }, true, true);
return; return;
} }
} }

View File

@ -2,7 +2,6 @@ package com.boydti.fawe.bukkit.listener;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.config.Settings; import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.TaskManager;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
@ -14,7 +13,9 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
@ -46,7 +47,6 @@ public class RenderListener implements Listener {
OFFSET = 8; OFFSET = 8;
timeOut = 2; timeOut = 2;
} else { } else {
int tpsSqr = tps32 * tps32;
OFFSET = 1 + (tps32 / 102400); OFFSET = 1 + (tps32 / 102400);
timeOut = 162 - (tps32 / 2560); timeOut = 162 - (tps32 / 2560);
} }
@ -75,7 +75,7 @@ public class RenderListener implements Listener {
}, 1); }, 1);
} }
public void setViewDistance(Player player, int value) { private void setViewDistance(Player player, int value) {
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
if (value == Settings.IMP.EXPERIMENTAL.DYNAMIC_CHUNK_RENDERING) { if (value == Settings.IMP.EXPERIMENTAL.DYNAMIC_CHUNK_RENDERING) {
views.remove(uuid); views.remove(uuid);
@ -99,7 +99,7 @@ public class RenderListener implements Listener {
player.setViewDistance(value); player.setViewDistance(value);
} }
public int getViewDistance(Player player) { private int getViewDistance(Player player) {
int[] value = views.get(player.getUniqueId()); int[] value = views.get(player.getUniqueId());
return value == null ? Settings.IMP.EXPERIMENTAL.DYNAMIC_CHUNK_RENDERING : value[0]; return value == null ? Settings.IMP.EXPERIMENTAL.DYNAMIC_CHUNK_RENDERING : value[0];
} }
@ -121,14 +121,13 @@ public class RenderListener implements Listener {
} }
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent event) { public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
setViewDistance(player, 1); setViewDistance(player, 1);
FawePlayer fp = FawePlayer.wrap(player);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerLeave(org.bukkit.event.player.PlayerQuitEvent event) { public void onPlayerLeave(PlayerQuitEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
UUID uid = player.getUniqueId(); UUID uid = player.getUniqueId();
views.remove(uid); views.remove(uid);

View File

@ -1,25 +0,0 @@
package com.boydti.fawe.bukkit.listener;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.server.TabCompleteEvent;
import java.util.List;
public class SyncTabCompleteListener extends ATabCompleteListener {
public SyncTabCompleteListener(WorldEditPlugin worldEdit) {
super(worldEdit);
}
@EventHandler
public void onTabComplete(TabCompleteEvent event) {
if (event.getSender() instanceof ConsoleCommandSender || event.getBuffer().startsWith("/")) {
List<String> result = this.onTab(event.getBuffer(), event.getSender());
if (result != null) {
event.setCompletions(result);
}
}
}
}

View File

@ -158,6 +158,7 @@ public class AsyncWorld extends DelegateFaweQueue implements World, HasFaweQueue
return parent; return parent;
} }
@Override
public FaweQueue getQueue() { public FaweQueue getQueue() {
return queue; return queue;
} }
@ -174,6 +175,7 @@ public class AsyncWorld extends DelegateFaweQueue implements World, HasFaweQueue
return wrap(world); return wrap(world);
} }
@Override
public Operation commit() { public Operation commit() {
flush(); flush();
return null; return null;

View File

@ -19,7 +19,7 @@
package com.sk89q.bukkit.util; package com.sk89q.bukkit.util;
import com.sk89q.minecraft.util.commands.Command; import org.enginehub.piston.annotation.Command;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.CommandsManager; import com.sk89q.minecraft.util.commands.CommandsManager;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
@ -31,6 +31,8 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@Deprecated
@SuppressWarnings("deprecation")
public class CommandsManagerRegistration extends CommandRegistration { public class CommandsManagerRegistration extends CommandRegistration {
protected CommandsManager<?> commands; protected CommandsManager<?> commands;

View File

@ -22,6 +22,8 @@ package com.sk89q.bukkit.util;
import com.sk89q.minecraft.util.commands.CommandsManager; import com.sk89q.minecraft.util.commands.CommandsManager;
import com.sk89q.util.StringUtil; import com.sk89q.util.StringUtil;
import com.sk89q.wepif.PermissionsResolverManager; import com.sk89q.wepif.PermissionsResolverManager;
import java.util.Arrays;
import java.util.List;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -29,12 +31,10 @@ import org.bukkit.command.PluginIdentifiableCommand;
import org.bukkit.command.TabCompleter; import org.bukkit.command.TabCompleter;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import java.util.Arrays;
import java.util.List;
/** /**
* An implementation of a dynamically registered {@link org.bukkit.command.Command} attached to a plugin * An implementation of a dynamically registered {@link org.bukkit.command.Command} attached to a plugin
*/ */
@SuppressWarnings("deprecation")
public class DynamicPluginCommand extends org.bukkit.command.Command implements PluginIdentifiableCommand { public class DynamicPluginCommand extends org.bukkit.command.Command implements PluginIdentifiableCommand {
protected final CommandExecutor owner; protected final CommandExecutor owner;
@ -78,14 +78,14 @@ public class DynamicPluginCommand extends org.bukkit.command.Command implements
return owningPlugin; return owningPlugin;
} }
// @Override @Override
// public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
// if (registeredWith instanceof CommandInspector) { if (registeredWith instanceof CommandInspector) {
// return ((TabCompleter) owner).onTabComplete(sender, this, alias, args); return ((TabCompleter) owner).onTabComplete(sender, this, alias, args);
// } else { } else {
// return super.tabComplete(sender, alias, args); return super.tabComplete(sender, alias, args);
// } }
// } }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override

View File

@ -30,6 +30,7 @@ import org.bukkit.help.HelpTopicFactory;
import java.util.Map; import java.util.Map;
@SuppressWarnings("deprecation")
public class DynamicPluginCommandHelpTopic extends HelpTopic { public class DynamicPluginCommandHelpTopic extends HelpTopic {
private final DynamicPluginCommand cmd; private final DynamicPluginCommand cmd;

View File

@ -32,6 +32,7 @@ import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -159,8 +160,8 @@ public class FlatFilePermissionsResolver implements PermissionsResolver {
} }
} }
userPermissionsCache.put(key.toLowerCase(), permsCache); userPermissionsCache.put(key.toLowerCase(Locale.ROOT), permsCache);
userGroups.put(key.toLowerCase(), new HashSet<>(Arrays.asList(groups))); userGroups.put(key.toLowerCase(Locale.ROOT), new HashSet<>(Arrays.asList(groups)));
} }
} }
} catch (IOException e) { } catch (IOException e) {
@ -184,7 +185,7 @@ public class FlatFilePermissionsResolver implements PermissionsResolver {
} }
} }
Set<String> perms = userPermissionsCache.get(player.toLowerCase()); Set<String> perms = userPermissionsCache.get(player.toLowerCase(Locale.ROOT));
if (perms == null) { if (perms == null) {
return defaultPermissionsCache.contains(permission) return defaultPermissionsCache.contains(permission)
|| defaultPermissionsCache.contains("*"); || defaultPermissionsCache.contains("*");
@ -201,13 +202,13 @@ public class FlatFilePermissionsResolver implements PermissionsResolver {
@Override @Override
public boolean inGroup(String player, String group) { public boolean inGroup(String player, String group) {
Set<String> groups = userGroups.get(player.toLowerCase()); Set<String> groups = userGroups.get(player.toLowerCase(Locale.ROOT));
return groups != null && groups.contains(group); return groups != null && groups.contains(group);
} }
@Override @Override
public String[] getGroups(String player) { public String[] getGroups(String player) {
Set<String> groups = userGroups.get(player.toLowerCase()); Set<String> groups = userGroups.get(player.toLowerCase(Locale.ROOT));
if (groups == null) { if (groups == null) {
return new String[0]; return new String[0];
} }

View File

@ -21,31 +21,25 @@ package com.sk89q.worldedit.bukkit;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Function;
import com.sk89q.worldedit.NotABlockException; import com.sk89q.worldedit.NotABlockException;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.IBukkitAdapter; import com.sk89q.worldedit.bukkit.adapter.IBukkitAdapter;
import com.sk89q.worldedit.bukkit.adapter.SimpleBukkitAdapter; import com.sk89q.worldedit.bukkit.adapter.SimpleBukkitAdapter;
import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemType;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
import org.bukkit.block.data.BlockData; import org.bukkit.block.data.BlockData;
@ -74,6 +68,12 @@ public enum BukkitAdapter {
return INSTANCE.adapter; return INSTANCE.adapter;
} }
private static final ParserContext TO_BLOCK_CONTEXT = new ParserContext();
static {
TO_BLOCK_CONTEXT.setRestricted(false);
}
/** /**
* Checks equality between a WorldEdit BlockType and a Bukkit Material * Checks equality between a WorldEdit BlockType and a Bukkit Material
* *
@ -112,6 +112,26 @@ public enum BukkitAdapter {
return getAdapter().adapt(world); return getAdapter().adapt(world);
} }
/**
* Create a WorldEdit Player from a Bukkit Player.
*
* @param player The Bukkit player
* @return The WorldEdit player
*/
public static BukkitPlayer adapt(Player player) {
return getAdapter().adapt(player);
}
/**
* Create a Bukkit Player from a WorldEdit Player.
*
* @param player The WorldEdit player
* @return The Bukkit player
*/
public static Player adapt(com.sk89q.worldedit.entity.Player player) {
return getAdapter().adapt(player);
}
/** /**
* Create a WorldEdit location from a Bukkit location. * Create a WorldEdit location from a Bukkit location.
* *
@ -134,10 +154,24 @@ public enum BukkitAdapter {
return getAdapter().adapt(location); return getAdapter().adapt(location);
} }
/**
* Create a Bukkit location from a WorldEdit position with a Bukkit world.
*
* @param world the Bukkit world
* @param position the WorldEdit position
* @return a Bukkit location
*/
public static org.bukkit.Location adapt(org.bukkit.World world, Vector3 position) { public static org.bukkit.Location adapt(org.bukkit.World world, Vector3 position) {
return getAdapter().adapt(world, position); return getAdapter().adapt(world, position);
} }
/**
* Create a Bukkit location from a WorldEdit position with a Bukkit world.
*
* @param world the Bukkit world
* @param position the WorldEdit position
* @return a Bukkit location
*/
public static org.bukkit.Location adapt(org.bukkit.World world, BlockVector3 position) { public static org.bukkit.Location adapt(org.bukkit.World world, BlockVector3 position) {
checkNotNull(world); checkNotNull(world);
checkNotNull(position); checkNotNull(position);
@ -157,19 +191,26 @@ public enum BukkitAdapter {
return getAdapter().adapt(world, location); return getAdapter().adapt(world, location);
} }
public static Vector3 asVector(org.bukkit.Location location) {
return getAdapter().asVector(location);
}
/** /**
* Create a WorldEdit Vector from a Bukkit location. * Create a WorldEdit Vector from a Bukkit location.
* *
* @param location The Bukkit location * @param location The Bukkit location
* @return a WorldEdit vector * @return a WorldEdit vector
*/ */
public static Vector3 asVector(org.bukkit.Location location) {
checkNotNull(location);
return Vector3.at(location.getX(), location.getY(), location.getZ());
}
/**
* Create a WorldEdit BlockVector from a Bukkit location.
*
* @param location The Bukkit location
* @return a WorldEdit vector
*/
public static BlockVector3 asBlockVector(org.bukkit.Location location) { public static BlockVector3 asBlockVector(org.bukkit.Location location) {
checkNotNull(location); checkNotNull(location);
return getAdapter().asBlockVector(location); return BlockVector3.at(location.getX(), location.getY(), location.getZ());
} }
/** /**
@ -329,12 +370,4 @@ public enum BukkitAdapter {
checkNotNull(item); checkNotNull(item);
return getAdapter().adapt(item); return getAdapter().adapt(item);
} }
public static BukkitPlayer adapt(Player player) {
return getAdapter().adapt(player);
}
public static Player adapt(com.sk89q.worldedit.entity.Player player) {
return getAdapter().adapt(player);
}
} }

View File

@ -40,4 +40,5 @@ class BukkitBiomeRegistry implements BiomeRegistry {
final Biome bukkitBiome = BukkitAdapter.adapt(biome); final Biome bukkitBiome = BukkitAdapter.adapt(biome);
return bukkitBiome == null ? null : bukkitBiome::name; return bukkitBiome == null ? null : bukkitBiome::name;
} }
} }

View File

@ -19,26 +19,28 @@
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.worldedit.bukkit.BukkitTextAdapter.reduceToText;
import com.sk89q.bukkit.util.CommandInspector; import com.sk89q.bukkit.util.CommandInspector;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.command.CommandMapping; import java.util.Optional;
import com.sk89q.worldedit.util.command.Description;
import com.sk89q.worldedit.util.command.Dispatcher;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.enginehub.piston.CommandManager;
import org.enginehub.piston.inject.InjectedValueStore;
import org.enginehub.piston.inject.Key;
import org.enginehub.piston.inject.MapBackedValueStore;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkNotNull;
class BukkitCommandInspector implements CommandInspector { class BukkitCommandInspector implements CommandInspector {
private static final Logger logger = LoggerFactory.getLogger(BukkitCommandInspector.class); private static final Logger logger = LoggerFactory.getLogger(BukkitCommandInspector.class);
private final WorldEditPlugin plugin; private final WorldEditPlugin plugin;
private final Dispatcher dispatcher; private final CommandManager dispatcher;
BukkitCommandInspector(WorldEditPlugin plugin, Dispatcher dispatcher) { BukkitCommandInspector(WorldEditPlugin plugin, CommandManager dispatcher) {
checkNotNull(plugin); checkNotNull(plugin);
checkNotNull(dispatcher); checkNotNull(dispatcher);
this.plugin = plugin; this.plugin = plugin;
@ -47,9 +49,9 @@ class BukkitCommandInspector implements CommandInspector {
@Override @Override
public String getShortText(Command command) { public String getShortText(Command command) {
CommandMapping mapping = dispatcher.get(command.getName()); Optional<org.enginehub.piston.Command> mapping = dispatcher.getCommand(command.getName());
if (mapping != null) { if (mapping.isPresent()) {
return mapping.getDescription().getDescription(); return reduceToText(mapping.get().getDescription());
} else { } else {
logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'"); logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'");
return "Help text not available"; return "Help text not available";
@ -58,10 +60,9 @@ class BukkitCommandInspector implements CommandInspector {
@Override @Override
public String getFullText(Command command) { public String getFullText(Command command) {
CommandMapping mapping = dispatcher.get(command.getName()); Optional<org.enginehub.piston.Command> mapping = dispatcher.getCommand(command.getName());
if (mapping != null) { if (mapping.isPresent()) {
Description description = mapping.getDescription(); return reduceToText(mapping.get().getFullHelp());
return "Usage: " + description.getUsage() + (description.getHelp() != null ? "\n" + description.getHelp() : "");
} else { } else {
logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'"); logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'");
return "Help text not available"; return "Help text not available";
@ -70,11 +71,12 @@ class BukkitCommandInspector implements CommandInspector {
@Override @Override
public boolean testPermission(CommandSender sender, Command command) { public boolean testPermission(CommandSender sender, Command command) {
CommandMapping mapping = dispatcher.get(command.getName()); Optional<org.enginehub.piston.Command> mapping = dispatcher.getCommand(command.getName());
if (mapping != null) { if (mapping.isPresent()) {
CommandLocals locals = new CommandLocals(); InjectedValueStore store = MapBackedValueStore.create();
locals.put(Actor.class, plugin.wrapCommandSender(sender)); store.injectValue(Key.of(Actor.class), context ->
return mapping.getCallable().testPermission(locals); Optional.of(plugin.wrapCommandSender(sender)));
return mapping.get().getCondition().satisfied(store);
} else { } else {
logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'"); logger.warn("BukkitCommandInspector doesn't know how about the command '" + command + "'");
return false; return false;

View File

@ -21,17 +21,21 @@ package com.sk89q.worldedit.bukkit;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.internal.cui.CUIEvent; import com.sk89q.worldedit.internal.cui.CUIEvent;
import com.sk89q.worldedit.session.SessionKey; import com.sk89q.worldedit.session.SessionKey;
import com.sk89q.worldedit.util.auth.AuthorizationException; import com.sk89q.worldedit.util.auth.AuthorizationException;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.adapter.bukkit.TextAdapter;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.annotation.Nullable;
import java.io.File; import java.io.File;
import java.util.UUID; import java.util.UUID;
import javax.annotation.Nullable;
public class BukkitCommandSender implements Actor { public class BukkitCommandSender implements Actor {
/** /**
@ -89,6 +93,11 @@ public class BukkitCommandSender implements Actor {
} }
} }
@Override
public void print(Component component) {
TextAdapter.sendComponent(sender, component);
}
@Override @Override
public boolean canDestroyBedrock() { public boolean canDestroyBedrock() {
return true; return true;

View File

@ -23,7 +23,6 @@ import com.boydti.fawe.Fawe;
import com.boydti.fawe.bukkit.FaweBukkit; import com.boydti.fawe.bukkit.FaweBukkit;
import com.boydti.fawe.object.RunnableVal; import com.boydti.fawe.object.RunnableVal;
import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.TaskManager;
import com.sk89q.util.StringUtil; import com.sk89q.util.StringUtil;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
@ -38,12 +37,19 @@ import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector3; import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.session.SessionKey; import com.sk89q.worldedit.session.SessionKey;
import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.util.HandSide;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.adapter.bukkit.TextAdapter;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.gamemode.GameMode; import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldedit.world.gamemode.GameModes; import com.sk89q.worldedit.world.gamemode.GameModes;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Nullable;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
@ -53,11 +59,6 @@ import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.PlayerInventory;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class BukkitPlayer extends AbstractPlayerActor { public class BukkitPlayer extends AbstractPlayerActor {
private Player player; private Player player;
@ -162,6 +163,11 @@ public class BukkitPlayer extends AbstractPlayerActor {
} }
} }
@Override
public void print(Component component) {
TextAdapter.sendComponent(player, component);
}
@Override @Override
public void setPosition(Vector3 pos, float pitch, float yaw) { public void setPosition(Vector3 pos, float pitch, float yaw) {
if (pos instanceof com.sk89q.worldedit.util.Location) { if (pos instanceof com.sk89q.worldedit.util.Location) {
@ -187,12 +193,12 @@ public class BukkitPlayer extends AbstractPlayerActor {
@Override @Override
public GameMode getGameMode() { public GameMode getGameMode() {
return GameModes.get(player.getGameMode().name().toLowerCase()); return GameModes.get(player.getGameMode().name().toLowerCase(Locale.ROOT));
} }
@Override @Override
public void setGameMode(GameMode gameMode) { public void setGameMode(GameMode gameMode) {
player.setGameMode(org.bukkit.GameMode.valueOf(gameMode.getId().toUpperCase())); player.setGameMode(org.bukkit.GameMode.valueOf(gameMode.getId().toUpperCase(Locale.ROOT)));
} }
@Override @Override

View File

@ -68,7 +68,7 @@ class BukkitRegistries extends BundledRegistries {
@Override @Override
public ItemCategoryRegistry getItemCategoryRegistry() { public ItemCategoryRegistry getItemCategoryRegistry() {
return itemCategoryRegistry; return itemCategoryRegistry;
} }
@Override @Override

View File

@ -19,29 +19,32 @@
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import static com.sk89q.worldedit.bukkit.BukkitTextAdapter.reduceToText;
import com.sk89q.bukkit.util.CommandInfo; import com.sk89q.bukkit.util.CommandInfo;
import com.sk89q.bukkit.util.CommandRegistration; import com.sk89q.bukkit.util.CommandRegistration;
import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.command.util.PermissionCondition;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.MultiUserPlatform; import com.sk89q.worldedit.extension.platform.MultiUserPlatform;
import com.sk89q.worldedit.extension.platform.Preference; import com.sk89q.worldedit.extension.platform.Preference;
import com.sk89q.worldedit.util.command.CommandMapping; import com.sk89q.worldedit.world.DataFixer;
import com.sk89q.worldedit.util.command.Description;
import com.sk89q.worldedit.util.command.Dispatcher;
import com.sk89q.worldedit.world.registry.Registries; import com.sk89q.worldedit.world.registry.Registries;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import javax.annotation.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.EnumMap; import java.util.EnumMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.enginehub.piston.CommandManager;
public class BukkitServerInterface implements MultiUserPlatform { public class BukkitServerInterface implements MultiUserPlatform {
public Server server; public Server server;
@ -64,6 +67,22 @@ public class BukkitServerInterface implements MultiUserPlatform {
return BukkitRegistries.getInstance(); return BukkitRegistries.getInstance();
} }
@Override
public int getDataVersion() {
if (plugin.getBukkitImplAdapter() != null) {
return plugin.getBukkitImplAdapter().getDataVersion();
}
return -1;
}
@Override
public DataFixer getDataFixer() {
if (plugin.getBukkitImplAdapter() != null) {
return plugin.getBukkitImplAdapter().getDataFixer();
}
return null;
}
@Override @Override
public boolean isValidMobType(String type) { public boolean isValidMobType(String type) {
final EntityType entityType = EntityType.fromName(type); final EntityType entityType = EntityType.fromName(type);
@ -115,20 +134,25 @@ public class BukkitServerInterface implements MultiUserPlatform {
} }
@Override @Override
public void registerCommands(Dispatcher dispatcher) { public void registerCommands(CommandManager dispatcher) {
List<CommandInfo> toRegister = new ArrayList<>();
BukkitCommandInspector inspector = new BukkitCommandInspector(plugin, dispatcher); BukkitCommandInspector inspector = new BukkitCommandInspector(plugin, dispatcher);
for (CommandMapping command : dispatcher.getCommands()) { dynamicCommands.register(dispatcher.getAllCommands()
Description description = command.getDescription(); .map(command -> {
List<String> permissions = description.getPermissions(); String[] permissionsArray = command.getCondition()
String[] permissionsArray = new String[permissions.size()]; .as(PermissionCondition.class)
permissions.toArray(permissionsArray); .map(PermissionCondition::getPermissions)
.map(s -> s.toArray(new String[0]))
.orElseGet(() -> new String[0]);
toRegister.add(new CommandInfo(description.getUsage(), description.getDescription(), command.getAllAliases(), inspector, permissionsArray)); String[] aliases = Stream.concat(
} Stream.of(command.getName()),
command.getAliases().stream()
dynamicCommands.register(toRegister); ).toArray(String[]::new);
return new CommandInfo(reduceToText(command.getUsage()),
reduceToText(command.getDescription()), aliases,
inspector, permissionsArray);
}).collect(Collectors.toList()));
} }
@Override @Override

View File

@ -0,0 +1,48 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* 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 <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.bukkit;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
public class BukkitTextAdapter {
public static String reduceToText(Component component) {
StringBuilder text = new StringBuilder();
appendTextTo(text, component);
return text.toString();
}
private static void appendTextTo(StringBuilder builder, Component component) {
if (component instanceof TextComponent) {
builder.append(((TextComponent) component).content());
} else if (component instanceof TranslatableComponent) {
builder.append(((TranslatableComponent) component).key());
}
for (Component child : component.children()) {
appendTextTo(builder, child);
}
}
private BukkitTextAdapter() {
}
}

View File

@ -20,6 +20,7 @@
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
@ -38,6 +39,14 @@ import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.weather.WeatherType; import com.sk89q.worldedit.world.weather.WeatherType;
import com.sk89q.worldedit.world.weather.WeatherTypes; import com.sk89q.worldedit.world.weather.WeatherTypes;
import java.lang.ref.WeakReference;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.bukkit.Effect; import org.bukkit.Effect;
import org.bukkit.TreeType; import org.bukkit.TreeType;
import org.bukkit.World; import org.bukkit.World;
@ -47,16 +56,9 @@ import org.bukkit.block.Chest;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.inventory.DoubleChestInventory; import org.bukkit.inventory.DoubleChestInventory;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.slf4j.Logger; import org.slf4j.Logger;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BukkitWorld extends AbstractWorld { public class BukkitWorld extends AbstractWorld {
private static final Logger logger = WorldEdit.logger; private static final Logger logger = WorldEdit.logger;
@ -154,6 +156,11 @@ public class BukkitWorld extends AbstractWorld {
return getWorld().getName(); return getWorld().getName();
} }
@Override
public Path getStoragePath() {
return getWorld().getWorldFolder().toPath();
}
@Override @Override
public int getBlockLightLevel(BlockVector3 pt) { public int getBlockLightLevel(BlockVector3 pt) {
return getWorld().getBlockAt(pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()).getLightLevel(); return getWorld().getBlockAt(pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()).getLightLevel();
@ -239,11 +246,11 @@ public class BukkitWorld extends AbstractWorld {
return false; return false;
} }
BlockState state = block.getState(); BlockState state = block.getState();
if (!(state instanceof org.bukkit.inventory.InventoryHolder)) { if (!(state instanceof InventoryHolder)) {
return false; return false;
} }
org.bukkit.inventory.InventoryHolder chest = (org.bukkit.inventory.InventoryHolder) state; InventoryHolder chest = (InventoryHolder) state;
Inventory inven = chest.getInventory(); Inventory inven = chest.getInventory();
if (chest instanceof Chest) { if (chest instanceof Chest) {
inven = getBlockInventory((Chest) chest); inven = getBlockInventory((Chest) chest);
@ -311,10 +318,13 @@ public class BukkitWorld extends AbstractWorld {
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
if (other == null) { if (worldRef.get() == null) {
return false;
} else if (other == null) {
return false; return false;
} else if ((other instanceof BukkitWorld)) { } else if ((other instanceof BukkitWorld)) {
return ((BukkitWorld) other).getWorld().equals(getWorld()); World otherWorld = ((BukkitWorld) other).worldRef.get();
return otherWorld != null && otherWorld.equals(getWorld());
} else if (other instanceof com.sk89q.worldedit.world.World) { } else if (other instanceof com.sk89q.worldedit.world.World) {
return ((com.sk89q.worldedit.world.World) other).getName().equals(getName()); return ((com.sk89q.worldedit.world.World) other).getName().equals(getName());
} else { } else {

View File

@ -42,8 +42,9 @@ public class CUIChannelListener implements PluginMessageListener {
public void onPluginMessageReceived(String channel, Player player, byte[] message) { public void onPluginMessageReceived(String channel, Player player, byte[] message) {
LocalSession session = plugin.getSession(player); LocalSession session = plugin.getSession(player);
String text = new String(message, UTF_8_CHARSET); String text = new String(message, UTF_8_CHARSET);
session.handleCUIInitializationMessage(text); final BukkitPlayer actor = plugin.wrapPlayer(player);
session.describeCUI(plugin.wrapPlayer(player)); session.handleCUIInitializationMessage(text, actor);
session.describeCUI(actor);
} }
} }

View File

@ -21,14 +21,10 @@
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.util.StringUtil;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.command.CommandMapping;
import com.sk89q.worldedit.util.command.Dispatcher;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.event.Event.Result; import org.bukkit.event.Event.Result;
@ -36,14 +32,16 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerCommandSendEvent; import org.bukkit.event.player.PlayerCommandSendEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.EquipmentSlot;
import org.enginehub.piston.CommandManager;
import org.enginehub.piston.inject.InjectedValueStore;
import org.enginehub.piston.inject.Key;
import org.enginehub.piston.inject.MapBackedValueStore;
import java.util.Set; import java.util.Optional;
import java.util.stream.Collectors;
/** /**
* Handles all events thrown in relation to a Player * Handles all events thrown in relation to a Player
@ -52,12 +50,6 @@ public class WorldEditListener implements Listener {
private WorldEditPlugin plugin; private WorldEditPlugin plugin;
/**
* Called when a player plays an animation, such as an arm swing
*
* @param event Relevant event details
*/
/** /**
* Construct the object; * Construct the object;
* *
@ -77,48 +69,18 @@ public class WorldEditListener implements Listener {
WorldEdit.getInstance().getSessionManager().get(plugin.wrapPlayer(event.getPlayer())); WorldEdit.getInstance().getSessionManager().get(plugin.wrapPlayer(event.getPlayer()));
} }
/**
* Called when a player attempts to use a command
*
* @param event Relevant event details
*/
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { public void onPlayerCommandSend(PlayerCommandSendEvent event) {
String[] split = event.getMessage().split(" "); InjectedValueStore store = MapBackedValueStore.create();
store.injectValue(Key.of(Actor.class), context ->
if (split.length > 0) { Optional.of(plugin.wrapCommandSender(event.getPlayer())));
split[0] = split[0].substring(1); CommandManager commandManager = plugin.getWorldEdit().getPlatformManager().getPlatformCommandManager().getCommandManager();
split = plugin.getWorldEdit().getPlatformManager().getCommandManager().commandDetection(split); event.getCommands().removeIf(name ->
} // remove if in the manager and not satisfied
commandManager.getCommand(name)
final String newMessage = "/" + StringUtil.joinString(split, " "); .filter(command -> !command.getCondition().satisfied(store))
.isPresent()
if (!newMessage.equals(event.getMessage())) { );
event.setMessage(newMessage);
plugin.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
if (!event.getMessage().isEmpty()) {
plugin.getServer().dispatchCommand(event.getPlayer(), event.getMessage().substring(1));
}
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerCommand(PlayerCommandSendEvent event) {
Dispatcher dispatcher = plugin.getWorldEdit().getPlatformManager().getCommandManager().getDispatcher();
if (dispatcher != null) {
CommandLocals locals = new CommandLocals();
locals.put(Actor.class, plugin.wrapCommandSender(event.getPlayer()));
Set<String> toRemove = plugin.getWorldEdit().getPlatformManager().getCommandManager().getDispatcher().getCommands().stream()
.filter(commandMapping -> !commandMapping.getCallable().testPermission(locals))
.map(CommandMapping::getPrimaryAlias)
.collect(Collectors.toSet());
event.getCommands().removeIf(toRemove::contains);
}
} }
/** /**
@ -136,12 +98,8 @@ public class WorldEditListener implements Listener {
return; return;
} }
try { if (event.getHand() == EquipmentSlot.OFF_HAND) {
if (event.getHand() == EquipmentSlot.OFF_HAND) { return;
return; // TODO api needs to be able to get either hand depending on event
// for now just ignore all off hand interacts
}
} catch (NoSuchMethodError | NoSuchFieldError ignored) {
} }
final Player player = plugin.wrapPlayer(event.getPlayer()); final Player player = plugin.wrapPlayer(event.getPlayer());
@ -167,7 +125,6 @@ public class WorldEditListener implements Listener {
event.setCancelled(true); event.setCancelled(true);
} }
} else if (action == Action.RIGHT_CLICK_BLOCK) { } else if (action == Action.RIGHT_CLICK_BLOCK) {
final Block clickedBlock = event.getClickedBlock(); final Block clickedBlock = event.getClickedBlock();
final Location pos = new Location(world, clickedBlock.getX(), clickedBlock.getY(), clickedBlock.getZ()); final Location pos = new Location(world, clickedBlock.getX(), clickedBlock.getY(), clickedBlock.getZ());

View File

@ -19,8 +19,6 @@
package com.sk89q.worldedit.bukkit; package com.sk89q.worldedit.bukkit;
import com.bekvon.bukkit.residence.commands.message;
import com.bekvon.bukkit.residence.containers.cmd;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.bukkit.FaweBukkit; import com.boydti.fawe.bukkit.FaweBukkit;
import com.boydti.fawe.bukkit.adapter.v1_13_1.Spigot_v1_13_R2; import com.boydti.fawe.bukkit.adapter.v1_13_1.Spigot_v1_13_R2;
@ -37,17 +35,20 @@ import com.sk89q.worldedit.bukkit.adapter.AdapterLoadException;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplLoader; import com.sk89q.worldedit.bukkit.adapter.BukkitImplLoader;
import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.event.platform.CommandSuggestionEvent;
import com.sk89q.worldedit.event.platform.PlatformReadyEvent; import com.sk89q.worldedit.event.platform.PlatformReadyEvent;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.util.command.CommandMapping;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockCategory; import com.sk89q.worldedit.world.block.BlockCategory;
import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.item.ItemCategory; import com.sk89q.worldedit.world.item.ItemCategory;
import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.registry.LegacyMapper; import com.sk89q.worldedit.world.registry.LegacyMapper;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.Tag; import org.bukkit.Tag;
@ -55,6 +56,8 @@ import org.bukkit.block.Biome;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
@ -75,6 +78,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.logging.Level; import java.util.logging.Level;
@ -192,10 +196,11 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
// Now we can register events // Now we can register events
getServer().getPluginManager().registerEvents(new WorldEditListener(this), this); getServer().getPluginManager().registerEvents(new WorldEditListener(this), this);
// register async tab complete, if available
if (PaperLib.isPaper()) {
getServer().getPluginManager().registerEvents(new AsyncTabCompleteListener(), this);
}
// If we are on MCPC+/Cauldron, then Forge will have already loaded
// Forge WorldEdit and there's (probably) not going to be any other
// platforms to be worried about... at the current time of writing
WorldEdit.getInstance().getEventBus().post(new PlatformReadyEvent()); WorldEdit.getInstance().getEventBus().post(new PlatformReadyEvent());
// Register 1.13 Material ids with LegacyMapper // Register 1.13 Material ids with LegacyMapper
@ -205,6 +210,8 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
legacyMapper.register(m.getId(), 0, BukkitAdapter.adapt(m).getDefaultState()); legacyMapper.register(m.getId(), 0, BukkitAdapter.adapt(m).getDefaultState());
} }
} }
PaperLib.suggestPaper(this);
} }
public void setupRegistries() { public void setupRegistries() {
@ -228,11 +235,12 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
).toImmutableState(); ).toImmutableState();
BlockState defaultState = blockState.getBlockType().getAllStates().get(0); BlockState defaultState = blockState.getBlockType().getAllStates().get(0);
for (Map.Entry<Property<?>, Object> propertyObjectEntry : state.getStates().entrySet()) { for (Map.Entry<Property<?>, Object> propertyObjectEntry : state.getStates().entrySet()) {
defaultState = defaultState.with((Property) propertyObjectEntry.getKey(), propertyObjectEntry.getValue()); //noinspection unchecked
defaultState = defaultState.with((Property<Object>) propertyObjectEntry.getKey(), propertyObjectEntry.getValue());
} }
return defaultState; return defaultState;
} catch (InputParseException e) { } catch (InputParseException e) {
e.printStackTrace(); getLogger().log(Level.WARNING, "Error loading block state for " + material.getKey(), e);
return blockState; return blockState;
} }
})); }));
@ -260,7 +268,7 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
for (Tag<Material> itemTag : Bukkit.getTags(Tag.REGISTRY_ITEMS, Material.class)) { for (Tag<Material> itemTag : Bukkit.getTags(Tag.REGISTRY_ITEMS, Material.class)) {
ItemCategory.REGISTRY.register(itemTag.getKey().toString(), new ItemCategory(itemTag.getKey().toString())); ItemCategory.REGISTRY.register(itemTag.getKey().toString(), new ItemCategory(itemTag.getKey().toString()));
} }
} catch (NoSuchMethodError e) { } catch (NoSuchMethodError ignored) {
getLogger().warning("The version of Spigot/Paper you are using doesn't support Tags. The usage of tags with WorldEdit will not work until you update."); getLogger().warning("The version of Spigot/Paper you are using doesn't support Tags. The usage of tags with WorldEdit will not work until you update.");
} }
} }
@ -554,4 +562,32 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
return bukkitAdapter; return bukkitAdapter;
} }
private class AsyncTabCompleteListener implements Listener {
AsyncTabCompleteListener() {
}
@SuppressWarnings("UnnecessaryFullyQualifiedName")
@EventHandler(ignoreCancelled = true)
public void onAsyncTabComplete(com.destroystokyo.paper.event.server.AsyncTabCompleteEvent event) {
if (!event.isCommand()) return;
String buffer = event.getBuffer();
final String[] parts = buffer.split(" ");
if (parts.length < 1) return;
final String label = parts[0];
final Optional<org.enginehub.piston.Command> command
= WorldEdit.getInstance().getPlatformManager().getPlatformCommandManager().getCommandManager().getCommand(label);
if (!command.isPresent()) return;
CommandSuggestionEvent suggestEvent = new CommandSuggestionEvent(wrapCommandSender(event.getSender()), event.getBuffer());
getWorldEdit().getEventBus().post(suggestEvent);
List<String> suggestions = suggestEvent.getSuggestions();
if (suggestions != null && !suggestions.isEmpty()) {
event.setCompletions(suggestions);
event.setHandled(true);
}
//event.setCompletions(CommandUtil.fixSuggestions(event.getBuffer(), suggestEvent.getSuggestions()));
//event.setHandled(true);
}
}
} }

View File

@ -24,6 +24,7 @@ import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.world.DataFixer;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockStateHolder;
@ -44,6 +45,21 @@ import javax.annotation.Nullable;
*/ */
public interface BukkitImplAdapter<T> extends IBukkitAdapter { public interface BukkitImplAdapter<T> extends IBukkitAdapter {
/**
* Get the Minecraft data version for the current world data.
*
* @return the data version
*/
int getDataVersion();
/**
* Get a data fixer, or null if not supported
*
* @return the data fixer
*/
@Nullable
DataFixer getDataFixer();
/** /**
* Get the block at the given location. * Get the block at the given location.
* *

View File

@ -52,7 +52,7 @@ public class BukkitImplLoader {
"**\n" + "**\n" +
"** When working with blocks or undoing, chests will be empty, signs\n" + "** When working with blocks or undoing, chests will be empty, signs\n" +
"** will be blank, and so on. There will be no support for entity\n" + "** will be blank, and so on. There will be no support for entity\n" +
"** and biome-related functions.\n" + "** and block property-related functions.\n" +
"**\n" + "**\n" +
"** Please see http://wiki.sk89q.com/wiki/WorldEdit/Bukkit_adapters\n" + "** Please see http://wiki.sk89q.com/wiki/WorldEdit/Bukkit_adapters\n" +
"**********************************************\n"; "**********************************************\n";
@ -160,9 +160,6 @@ public class BukkitImplLoader {
if (cls.isSynthetic()) continue; if (cls.isSynthetic()) continue;
if (BukkitImplAdapter.class.isAssignableFrom(cls)) { if (BukkitImplAdapter.class.isAssignableFrom(cls)) {
return (BukkitImplAdapter) cls.newInstance(); return (BukkitImplAdapter) cls.newInstance();
} else {
log.warn("Failed to load the Bukkit adapter class '" + className +
"' because it does not implement " + BukkitImplAdapter.class.getCanonicalName());
} }
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
log.warn("Failed to load the Bukkit adapter class '" + className + log.warn("Failed to load the Bukkit adapter class '" + className +
@ -171,7 +168,6 @@ public class BukkitImplLoader {
log.warn("Failed to load the Bukkit adapter class '" + className + log.warn("Failed to load the Bukkit adapter class '" + className +
"' that is not supposed to be raising this error", e); "' that is not supposed to be raising this error", e);
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace();
if (className.equals(customCandidate)) { if (className.equals(customCandidate)) {
log.warn("Failed to load the Bukkit adapter class '" + className + "'", e); log.warn("Failed to load the Bukkit adapter class '" + className + "'", e);
} }

View File

@ -371,6 +371,6 @@ public interface IBukkitAdapter {
} }
default BiomeType adapt(Biome biome) { default BiomeType adapt(Biome biome) {
return BiomeTypes.get(biome.name().toLowerCase()); return BiomeTypes.register(biome.name().toLowerCase());
} }
} }

View File

@ -25,7 +25,7 @@ import com.sk89q.worldedit.extension.factory.DefaultTransformParser;
import com.sk89q.worldedit.extension.factory.parser.mask.DefaultMaskParser; import com.sk89q.worldedit.extension.factory.parser.mask.DefaultMaskParser;
import com.sk89q.worldedit.extension.factory.parser.pattern.DefaultPatternParser; import com.sk89q.worldedit.extension.factory.parser.pattern.DefaultPatternParser;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard;
@ -152,7 +152,7 @@ public class FaweAPI {
* @param aliases The aliases to give the command (or none) * @param aliases The aliases to give the command (or none)
*/ */
public static void registerCommands(Object clazz, String... aliases) { public static void registerCommands(Object clazz, String... aliases) {
CommandManager.getInstance().registerCommands(clazz, aliases); PlatformCommandManager.getInstance().registerCommands(clazz, aliases);
} }
/** /**

View File

@ -1,11 +1,24 @@
package com.boydti.fawe.command; package com.boydti.fawe.command;
import com.boydti.fawe.Fawe; import static com.google.common.base.Preconditions.checkNotNull;
import com.boydti.fawe.FaweAPI; import com.boydti.fawe.FaweAPI;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.BBC;
import com.boydti.fawe.jnbt.anvil.*; import com.boydti.fawe.jnbt.anvil.MCAClipboard;
import com.boydti.fawe.jnbt.anvil.filters.*; import com.boydti.fawe.jnbt.anvil.MCAFile;
import com.boydti.fawe.jnbt.anvil.MCAFilter;
import com.boydti.fawe.jnbt.anvil.MCAFilterCounter;
import com.boydti.fawe.jnbt.anvil.MCAQueue;
import com.boydti.fawe.jnbt.anvil.filters.DebugFixP2Roads;
import com.boydti.fawe.jnbt.anvil.filters.DeleteBiomeFilterSimple;
import com.boydti.fawe.jnbt.anvil.filters.DeleteOldFilter;
import com.boydti.fawe.jnbt.anvil.filters.DeleteUnclaimedFilter;
import com.boydti.fawe.jnbt.anvil.filters.DeleteUninhabitedFilter;
import com.boydti.fawe.jnbt.anvil.filters.PlotTrimFilter;
import com.boydti.fawe.jnbt.anvil.filters.RemapFilter;
import com.boydti.fawe.jnbt.anvil.filters.RemoveLayerFilter;
import com.boydti.fawe.jnbt.anvil.filters.SetPatternFilter;
import com.boydti.fawe.jnbt.anvil.filters.TrimAirFilter;
import com.boydti.fawe.jnbt.anvil.history.IAnvilHistory; import com.boydti.fawe.jnbt.anvil.history.IAnvilHistory;
import com.boydti.fawe.jnbt.anvil.history.NullAnvilHistory; import com.boydti.fawe.jnbt.anvil.history.NullAnvilHistory;
import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FawePlayer;
@ -14,17 +27,16 @@ import com.boydti.fawe.object.RegionWrapper;
import com.boydti.fawe.object.RunnableVal4; import com.boydti.fawe.object.RunnableVal4;
import com.boydti.fawe.object.changeset.AnvilHistory; import com.boydti.fawe.object.changeset.AnvilHistory;
import com.boydti.fawe.object.clipboard.remap.ClipboardRemapper; import com.boydti.fawe.object.clipboard.remap.ClipboardRemapper;
import com.boydti.fawe.object.mask.FaweBlockMatcher;
import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.SetQueue; import com.boydti.fawe.util.SetQueue;
import com.boydti.fawe.util.StringMan; import org.enginehub.piston.annotation.Command;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.pattern.RandomPattern;
import com.sk89q.worldedit.internal.annotation.Selection; import com.sk89q.worldedit.internal.annotation.Selection;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
@ -33,15 +45,10 @@ import com.sk89q.worldedit.util.command.binding.Switch;
import com.sk89q.worldedit.util.command.parametric.Optional; import com.sk89q.worldedit.util.command.parametric.Optional;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import java.io.IOException; import java.io.IOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
import static com.google.common.base.Preconditions.checkNotNull;
@Command(aliases = {"/anvil"}, desc = "Manipulate billions of blocks: [More Info](https://github.com/boy0001/FastAsyncWorldedit/wiki/Anvil-API)") @Command(aliases = {"/anvil"}, desc = "Manipulate billions of blocks: [More Info](https://github.com/boy0001/FastAsyncWorldedit/wiki/Anvil-API)")
public class AnvilCommands { public class AnvilCommands {
@ -139,9 +146,7 @@ public class AnvilCommands {
desc = "Replace all blocks in the selection with another", desc = "Replace all blocks in the selection with another",
help = "Replace all blocks in the selection with another\n" + help = "Replace all blocks in the selection with another\n" +
"The -d flag disabled wildcard data matching\n", "The -d flag disabled wildcard data matching\n",
flags = "df", flags = "df"
min = 2,
max = 4
) )
@CommandPermissions("worldedit.anvil.replaceall") @CommandPermissions("worldedit.anvil.replaceall")
public void replaceAll(Player player, String folder, @Optional String from, String to, @Switch('d') boolean useData) throws WorldEditException { public void replaceAll(Player player, String folder, @Optional String from, String to, @Switch('d') boolean useData) throws WorldEditException {
@ -164,9 +169,7 @@ public class AnvilCommands {
aliases = {"remapall"}, aliases = {"remapall"},
usage = "<folder>", usage = "<folder>",
help = "Remap the world between MCPE/PC values", help = "Remap the world between MCPE/PC values",
desc = "Remap the world between MCPE/PC values", desc = "Remap the world between MCPE/PC values"
min = 1,
max = 1
) )
@CommandPermissions("worldedit.anvil.remapall") @CommandPermissions("worldedit.anvil.remapall")
public void remapall(Player player, String folder) throws WorldEditException { public void remapall(Player player, String folder) throws WorldEditException {
@ -188,9 +191,7 @@ public class AnvilCommands {
help = "Delete all chunks which haven't been occupied for `age-ticks` (20t = 1s) and \n" + help = "Delete all chunks which haven't been occupied for `age-ticks` (20t = 1s) and \n" +
"Have not been accessed since `file-duration` (ms) after creation and\n" + "Have not been accessed since `file-duration` (ms) after creation and\n" +
"Have not been used in the past `chunk-inactivity` (ms)" + "Have not been used in the past `chunk-inactivity` (ms)" +
"The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`", "The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`"
min = 2,
max = 3
) )
@CommandPermissions("worldedit.anvil.deleteallunvisited") @CommandPermissions("worldedit.anvil.deleteallunvisited")
public void deleteAllUnvisited(Player player, String folder, int inhabitedTicks, @Optional("60000") int fileDurationMillis) throws WorldEditException { public void deleteAllUnvisited(Player player, String folder, int inhabitedTicks, @Optional("60000") int fileDurationMillis) throws WorldEditException {
@ -220,7 +221,7 @@ public class AnvilCommands {
} }
@Command( @Command(
aliases = {"deleteunclaimed"}, name = "deleteunclaimed",
usage = "<age-ticks> [file-age=60000]", usage = "<age-ticks> [file-age=60000]",
desc = "(Supports: WG, P2, GP) Delete all chunks which haven't been occupied AND claimed", desc = "(Supports: WG, P2, GP) Delete all chunks which haven't been occupied AND claimed",
help = "(Supports: WG, P2, GP) Delete all chunks which aren't claimed AND haven't been occupied for `age-ticks` (20t = 1s) and \n" + help = "(Supports: WG, P2, GP) Delete all chunks which aren't claimed AND haven't been occupied for `age-ticks` (20t = 1s) and \n" +
@ -245,9 +246,7 @@ public class AnvilCommands {
help = "Delete regions which haven't been accessed in a certain amount of time\n" + help = "Delete regions which haven't been accessed in a certain amount of time\n" +
"You can use seconds (s), minutes (m), hours (h), days (d), weeks (w), years (y)\n" + "You can use seconds (s), minutes (m), hours (h), days (d), weeks (w), years (y)\n" +
"(months are not a unit of time)\n" + "(months are not a unit of time)\n" +
"E.g. 8h5m12s\n", "E.g. 8h5m12s\n"
min = 2,
max = 3
) )
@CommandPermissions("worldedit.anvil.deletealloldregions") @CommandPermissions("worldedit.anvil.deletealloldregions")
public void deleteAllOldRegions(Player player, String folder, String time) throws WorldEditException { public void deleteAllOldRegions(Player player, String folder, String time) throws WorldEditException {
@ -258,7 +257,7 @@ public class AnvilCommands {
} }
@Command( @Command(
aliases = {"trimallplots", }, name = "trimallplots",
desc = "Trim chunks in a Plot World", desc = "Trim chunks in a Plot World",
help = "Trim chunks in a Plot World\n" + help = "Trim chunks in a Plot World\n" +
"Unclaimed chunks will be deleted\n" + "Unclaimed chunks will be deleted\n" +
@ -278,7 +277,7 @@ public class AnvilCommands {
} }
@Command( @Command(
aliases = {"deletebiomechunks", }, name = "deletebiomechunks",
desc = "Delete chunks matching a specific biome" desc = "Delete chunks matching a specific biome"
) )
@CommandPermissions("worldedit.anvil.trimallair") @CommandPermissions("worldedit.anvil.trimallair")
@ -289,7 +288,7 @@ public class AnvilCommands {
} }
@Command( @Command(
aliases = {"trimallair", }, name = "trimallair",
desc = "Trim all air in the world" desc = "Trim all air in the world"
) )
@CommandPermissions("worldedit.anvil.trimallair") @CommandPermissions("worldedit.anvil.trimallair")
@ -300,7 +299,7 @@ public class AnvilCommands {
} }
@Command( @Command(
aliases = {"debugfixroads", }, name = "debugfixroads",
desc = "debug - do not use" desc = "debug - do not use"
) )
@CommandPermissions("worldedit.anvil.debugfixroads") @CommandPermissions("worldedit.anvil.debugfixroads")
@ -314,9 +313,7 @@ public class AnvilCommands {
aliases = {"replaceallpattern", "reap", "repallpat"}, aliases = {"replaceallpattern", "reap", "repallpat"},
usage = "<folder> [from-block] <to-pattern>", usage = "<folder> [from-block] <to-pattern>",
desc = "Replace all blocks in the selection with another", desc = "Replace all blocks in the selection with another",
flags = "dm", flags = "dm"
min = 2,
max = 4
) )
@CommandPermissions("worldedit.anvil.replaceall") @CommandPermissions("worldedit.anvil.replaceall")
public void replaceAllPattern(Player player, String folder, @Optional String from, final Pattern to, @Switch('d') boolean useData, @Switch('m') boolean useMap) throws WorldEditException { public void replaceAllPattern(Player player, String folder, @Optional String from, final Pattern to, @Switch('d') boolean useData, @Switch('m') boolean useMap) throws WorldEditException {
@ -346,9 +343,7 @@ public class AnvilCommands {
aliases = {"countall"}, aliases = {"countall"},
usage = "<folder> [hasSky] <id>", usage = "<folder> [hasSky] <id>",
desc = "Count all blocks in a world", desc = "Count all blocks in a world",
flags = "d", flags = "d"
min = 2,
max = 3
) )
@CommandPermissions("worldedit.anvil.countall") @CommandPermissions("worldedit.anvil.countall")
public void countAll(Player player, EditSession editSession, String folder, String arg, @Switch('d') boolean useData) throws WorldEditException { public void countAll(Player player, EditSession editSession, String folder, String arg, @Switch('d') boolean useData) throws WorldEditException {

View File

@ -4,7 +4,7 @@ import com.boydti.fawe.config.Commands;
import com.boydti.fawe.jnbt.anvil.HeightMapMCAGenerator; import com.boydti.fawe.jnbt.anvil.HeightMapMCAGenerator;
import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.object.changeset.CFIChangeSet; import com.boydti.fawe.object.changeset.CFIChangeSet;
import com.sk89q.minecraft.util.commands.Command; import org.enginehub.piston.annotation.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
@ -28,12 +28,9 @@ public class CFICommand extends MethodCommands {
} }
@Command( @Command(
aliases = {"cfi", "createfromimage"}, name = "cfi",
usage = "", aliases = {"cfi", "createfromimage"},
min = 0, desc = "Start CreateFromImage"
max = -1,
anyFlags = true,
desc = "Start CreateFromImage"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void cfi(FawePlayer fp, CommandContext context) throws CommandException, IOException { public void cfi(FawePlayer fp, CommandContext context) throws CommandException, IOException {
@ -51,49 +48,49 @@ public class CFICommand extends MethodCommands {
private void dispatch(FawePlayer fp, CFICommands.CFISettings settings, CommandContext context) throws CommandException { private void dispatch(FawePlayer fp, CFICommands.CFISettings settings, CommandContext context) throws CommandException {
if (!settings.hasGenerator()) { if (!settings.hasGenerator()) {
switch (context.argsLength()) { if (context.argsLength() == 0) {
case 0: { String hmCmd = child.alias() + " ";
String hmCmd = child.alias() + " "; if (settings.image == null) {
if (settings.image == null) { hmCmd += "image";
hmCmd += "image"; } else {
} else { hmCmd =
hmCmd = Commands.getAlias(CFICommands.class, "heightmap") + " " + settings.imageArg; Commands.getAlias(CFICommands.class, "heightmap") + " " + settings.imageArg;
}
child.msg("What do you want to use as the base?").newline()
.text("&7[&aHeightMap&7]").cmdTip(hmCmd).text(" - A heightmap like ").text("&7[&athis&7]").linkTip("http://i.imgur.com/qCd30MR.jpg")
.newline()
.text("&7[&aEmpty&7]").cmdTip(child.alias() + " empty").text("- An empty map of a specific size")
.send(fp);
break;
} }
default: { child.msg("What do you want to use as the base?").newline()
String remaining = context.getJoinedStrings(0); .text("[HeightMap]").cmdTip(hmCmd).text(" - A heightmap like ")
if (!dispatcher.contains(context.getString(0))) { .text("[this]").linkTip("http://i.imgur.com/qCd30MR.jpg")
switch (context.argsLength()) { .newline()
case 1: { .text("[Empty]").cmdTip(child.alias() + " empty")
String cmd = Commands.getAlias(CFICommands.class, "heightmap") + " " + context.getJoinedStrings(0); .text("- An empty map of a specific size")
dispatcher.call(cmd, context.getLocals(), new String[0]); .send(fp);
return; } else {
} String remaining = context.getJoinedStrings(0);
case 2: { if (!dispatcher.contains(context.getString(0))) {
String cmd = Commands.getAlias(CFICommands.class, "empty") + " " + context.getJoinedStrings(0); switch (context.argsLength()) {
dispatcher.call(cmd, context.getLocals(), new String[0]); case 1: {
return; String cmd =
} Commands.getAlias(CFICommands.class, "heightmap") + " " + context
.getJoinedStrings(0);
dispatcher.call(cmd, context.getLocals(), new String[0]);
return;
}
case 2: {
String cmd =
Commands.getAlias(CFICommands.class, "empty") + " " + context
.getJoinedStrings(0);
dispatcher.call(cmd, context.getLocals(), new String[0]);
return;
} }
} }
dispatcher.call(remaining, context.getLocals(), new String[0]);
} }
dispatcher.call(remaining, context.getLocals(), new String[0]);
} }
} else { } else {
switch (context.argsLength()) { if (context.argsLength() == 0) {
case 0: settings.setCategory("");
settings.setCategory(""); child.mainMenu(fp);
child.mainMenu(fp); } else {
break; dispatcher.call(context.getJoinedStrings(0), context.getLocals(), new String[0]);
default:
dispatcher.call(context.getJoinedStrings(0), context.getLocals(), new String[0]);
break;
} }
} }
} }

View File

@ -20,7 +20,9 @@ import com.boydti.fawe.util.TaskManager;
import com.boydti.fawe.util.TextureUtil; import com.boydti.fawe.util.TextureUtil;
import com.boydti.fawe.util.chat.Message; import com.boydti.fawe.util.chat.Message;
import com.boydti.fawe.util.image.ImageUtil; import com.boydti.fawe.util.image.ImageUtil;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import java.util.stream.IntStream;
import org.enginehub.piston.annotation.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
@ -72,10 +74,11 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import org.enginehub.piston.annotation.CommandContainer;
import static com.boydti.fawe.util.image.ImageUtil.load; import static com.boydti.fawe.util.image.ImageUtil.load;
@Command(aliases = {"/cfi"}, desc = "Create a world from images: [More Info](https://git.io/v5iDy)") @CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class)
public class CFICommands extends MethodCommands { public class CFICommands extends MethodCommands {
private final Dispatcher dispathcer; private final Dispatcher dispathcer;
@ -99,17 +102,14 @@ public class CFICommands extends MethodCommands {
@Command( @Command(
aliases = {"heightmap"}, aliases = {"heightmap"},
usage = "<url>",
desc = "Start CFI with a height map as a base" desc = "Start CFI with a height map as a base"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void heightmap(FawePlayer fp, FawePrimitiveBinding.ImageUri image, @Optional("1") double yscale) throws ParameterException { public void heightmap(FawePlayer fp, FawePrimitiveBinding.ImageUri image, @Optional("1") double yscale) throws ParameterException {
if (yscale != 0) { if (yscale != 0) {
int[] raw = ((DataBufferInt) image.load().getRaster().getDataBuffer()).getData(); int[] raw = ((DataBufferInt) image.load().getRaster().getDataBuffer()).getData();
int[] table = new int[256]; int[] table = IntStream.range(0, 256).map(i -> Math.min(255, (int) (i * yscale)))
for (int i = 0; i < table.length; i++) { .toArray();
table[i] = Math.min(255, (int) (i * yscale));
}
for (int i = 0; i < raw.length; i++) { for (int i = 0; i < raw.length; i++) {
int color = raw[i]; int color = raw[i];
int red = table[(color >> 16) & 0xFF]; int red = table[(color >> 16) & 0xFF];
@ -123,8 +123,7 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"empty"}, name = "empty",
usage = "<width> <length>",
desc = "Start CFI with an empty map as a base" desc = "Start CFI with an empty map as a base"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
@ -135,8 +134,7 @@ public class CFICommands extends MethodCommands {
private String generateName() { private String generateName() {
DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH.mm.ss"); DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH.mm.ss");
String data = df.format(new Date()); return df.format(new Date());
return data;
} }
private void setup(HeightMapMCAGenerator generator, FawePlayer fp) { private void setup(HeightMapMCAGenerator generator, FawePlayer fp) {
@ -149,8 +147,7 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"brush"}, name = "brush",
usage = "",
desc = "Info about using brushes with CFI" desc = "Info about using brushes with CFI"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
@ -166,23 +163,23 @@ public class CFICommands extends MethodCommands {
} else { } else {
msg = msg("This is not supported with your platform/version").newline(); msg = msg("This is not supported with your platform/version").newline();
} }
msg.text("&8< &7[&aBack&7]").cmdTip(alias()).send(fp); msg.text("< [Back]").cmdTip(alias()).send(fp);
} }
@Command( @Command(
aliases = {"cancel", "exit"}, name = "cancel",
usage = "", aliases = {"exit"},
desc = "Cancel creation" desc = "Cancel creation"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void cancel(FawePlayer fp) throws ParameterException, IOException { public void cancel(FawePlayer fp) {
getSettings(fp).remove(); getSettings(fp).remove();
fp.sendMessage("Cancelled!"); fp.sendMessage("Cancelled!");
} }
@Command( @Command(
aliases = {"done", "create"}, name = "done",
usage = "", aliases = "create",
desc = "Create the world" desc = "Create the world"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
@ -240,8 +237,7 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"column", "setcolumn"}, name = "column",
usage = "<pattern> [url|mask]",
desc = "Set the floor and main block" desc = "Set the floor and main block"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
@ -256,8 +252,7 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"floor", "setfloor"}, name = "floor",
usage = "<pattern> [url|mask]",
desc = "Set the floor (default: grass)" desc = "Set the floor (default: grass)"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
@ -276,8 +271,7 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"main", "setmain"}, name = "main",
usage = "<pattern> [url|mask]",
desc = "Set the main block (default: stone)" desc = "Set the main block (default: stone)"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
@ -296,10 +290,10 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
name = "overlay",
aliases = {"overlay", "setoverlay"}, aliases = {"overlay", "setoverlay"},
usage = "<pattern> [url|mask]",
desc = "Set the overlay block", desc = "Set the overlay block",
help = "Change the block directly above the floor (default: air)\n" + descFooter = "Change the block directly above the floor (default: air)\n" +
"e.g. Tallgrass" "e.g. Tallgrass"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
@ -314,9 +308,8 @@ public class CFICommands extends MethodCommands {
@Command( @Command(
aliases = {"smooth"}, aliases = {"smooth"},
usage = "<radius> <iterations> [image|mask]",
desc = "Smooth the terrain", desc = "Smooth the terrain",
help = "Smooth terrain within an image-mask, or worldedit mask\n" + descFooter = "Smooth terrain within an image-mask, or worldedit mask\n" +
" - You can use !0 as the mask to smooth everything\n" + " - You can use !0 as the mask to smooth everything\n" +
" - This supports smoothing snow layers (set the floor to 78:7)\n" + " - This supports smoothing snow layers (set the floor to 78:7)\n" +
" - A good value for radius and iterations would be 1 8." " - A good value for radius and iterations would be 1 8."
@ -335,8 +328,7 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"snow"}, name = "snow",
usage = "[image|mask]",
desc = "Create some snow" desc = "Create some snow"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
@ -351,10 +343,9 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"biomepriority", "palettebiomepriority", "setpalettebiomepriority"}, name = "biomepriority",
usage = "[percent=50]",
desc = "Set the biome priority", desc = "Set the biome priority",
help = "Increase or decrease biome priority when using blockBiomeColor.\n" + descFooter = "Increase or decrease biome priority when using blockBiomeColor.\n" +
"A value of 50 is the default\n" + "A value of 50 is the default\n" +
"Above 50 will prefer to color with biomes\n" + "Above 50 will prefer to color with biomes\n" +
"Below 50 will prefer to color with blocks" "Below 50 will prefer to color with blocks"
@ -366,10 +357,9 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"paletteblocks", "colorpaletterblocks", "setcolorpaletteblocks"}, name = "paletteblocks",
usage = "<blocks|#clipboard|*>",
desc = "Set the blocks used for coloring", desc = "Set the blocks used for coloring",
help = "Allow only specific blocks to be used for coloring\n" + descFooter = "Allow only specific blocks to be used for coloring\n" +
"`blocks` is a list of blocks e.g. stone,bedrock,wool\n" + "`blocks` is a list of blocks e.g. stone,bedrock,wool\n" +
"`#clipboard` will only use the blocks present in your clipboard." "`#clipboard` will only use the blocks present in your clipboard."
) )
@ -377,15 +367,15 @@ public class CFICommands extends MethodCommands {
public void paletteblocks(FawePlayer fp, Player player, LocalSession session, @Optional String arg) throws ParameterException, EmptyClipboardException, InputParseException, FileNotFoundException { public void paletteblocks(FawePlayer fp, Player player, LocalSession session, @Optional String arg) throws ParameterException, EmptyClipboardException, InputParseException, FileNotFoundException {
if (arg == null) { if (arg == null) {
msg("What blocks do you want to color with?").newline() msg("What blocks do you want to color with?").newline()
.text("&7[&aAll&7]").cmdTip(alias() + " PaletteBlocks *").text(" - All available blocks") .text("[All]").cmdTip(alias() + " PaletteBlocks *").text(" - All available blocks")
.newline() .newline()
.text("&7[&aClipboard&7]").cmdTip(alias() + " PaletteBlocks #clipboard").text(" - The blocks in your clipboard") .text("[Clipboard]").cmdTip(alias() + " PaletteBlocks #clipboard").text(" - The blocks in your clipboard")
.newline() .newline()
.text("&7[&aList&7]").suggestTip(alias() + " PaletteBlocks stone,gravel").text(" - A comma separated list of blocks") .text("[List]").suggestTip(alias() + " PaletteBlocks stone,gravel").text(" - A comma separated list of blocks")
.newline() .newline()
.text("&7[&aComplexity&7]").cmdTip(alias() + " Complexity").text(" - Block textures within a complexity range") .text("[Complexity]").cmdTip(alias() + " Complexity").text(" - Block textures within a complexity range")
.newline() .newline()
.text("&8< &7[&aBack&7]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "coloring")) .text("< [Back]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "coloring"))
.send(fp); .send(fp);
return; return;
} }
@ -444,10 +434,9 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"randomization", "paletterandomization"}, name = "randomization",
usage = "<true|false>",
desc = "Set whether randomization is enabled", desc = "Set whether randomization is enabled",
help = "This is enabled by default, randomization will add some random variation in the blocks used to closer match the provided image.\n" + 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" + "If disabled, the closest block to the color will always be used.\n" +
"Randomization will allow mixing biomes when coloring with biomes" "Randomization will allow mixing biomes when coloring with biomes"
) )
@ -458,10 +447,9 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"complexity", "palettecomplexity"}, name = "complexity",
usage = "<minPercent> <maxPercent>",
desc = "Set the complexity for coloring", desc = "Set the complexity for coloring",
help = "Set the complexity for coloring\n" + 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" + "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" + "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." "Using 0 73 for the min/max would use the simplest 73% of blocks for coloring, and is a reasonable value."
@ -475,10 +463,9 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"schem", "schematic", "schems", "schematics", "addschems"}, name = "schem",
usage = "[url] <mask> <file|folder|url> <rarity> <distance> <rotate=true>",
desc = "Populate schematics", desc = "Populate schematics",
help = "Populate a schematic on the terrain\n" + descFooter = "Populate a schematic on the terrain\n" +
" - Change the mask (e.g. angle mask) to only place the schematic in specific locations.\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 rarity is a value between 0 and 100.\n" +
" - The distance is the spacing between each schematic" " - The distance is the spacing between each schematic"
@ -502,10 +489,9 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"biome", "setbiome"}, name = "biome",
usage = "<biome> [image|mask]",
desc = "Set the biome", desc = "Set the biome",
help = "Set the biome in specific parts of the map.\n" + 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)" + " - 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" + " - 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" " - If a mask is used, the biome will be set anywhere the mask applies"
@ -522,7 +508,7 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"caves", "addcaves"}, name = "caves",
desc = "Generate vanilla caves" desc = "Generate vanilla caves"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
@ -533,10 +519,9 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"ore", "addore"}, name = "ore",
usage = "<mask=stone> <pattern> <size> <frequency> <rarity> <minY> <maxY>",
desc = "Add an ore", desc = "Add an ore",
help = "Use a specific pattern and settings to generate ore" descFooter = "Use a specific pattern and settings to generate ore"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void ore(FawePlayer fp, Mask mask, Pattern pattern, int size, int frequency, int rariry, int minY, int maxY) throws ParameterException, WorldEditException { public void ore(FawePlayer fp, Mask mask, Pattern pattern, int size, int frequency, int rariry, int minY, int maxY) throws ParameterException, WorldEditException {
@ -546,8 +531,7 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"ores", "addores"}, name = "ores",
usage = "<mask=stone>",
desc = "Generate the vanilla ores" desc = "Generate the vanilla ores"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
@ -558,10 +542,9 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"height", "setheight"}, name = "height",
usage = "<height|image>",
desc = "Set the height", desc = "Set the height",
help = "Set the terrain height either based on an image heightmap, or a numeric value." descFooter = "Set the terrain height either based on an image heightmap, or a numeric value."
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void height(FawePlayer fp, String arg) throws ParameterException, WorldEditException { public void height(FawePlayer fp, String arg) throws ParameterException, WorldEditException {
@ -576,10 +559,8 @@ public class CFICommands extends MethodCommands {
} }
@Command( @Command(
aliases = {"water", "waterid"}, name = "water",
usage = "<block>", desc = "Change the block used for water\ne.g. Lava"
desc = "Change the block used for water\n" +
"e.g. Lava"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void waterId(FawePlayer fp, BlockStateHolder block) throws ParameterException, WorldEditException { public void waterId(FawePlayer fp, BlockStateHolder block) throws ParameterException, WorldEditException {
@ -592,9 +573,7 @@ public class CFICommands extends MethodCommands {
@Command( @Command(
aliases = {"baseid", "bedrockid"}, aliases = {"baseid", "bedrockid"},
usage = "<block>", desc = "Change the block used for the base\ne.g. Bedrock"
desc = "Change the block used for the base\n" +
"e.g. Bedrock"
) )
@CommandPermissions("worldedit.anvil.cfi") @CommandPermissions("worldedit.anvil.cfi")
public void baseId(FawePlayer fp, BlockStateHolder block) throws ParameterException, WorldEditException { public void baseId(FawePlayer fp, BlockStateHolder block) throws ParameterException, WorldEditException {
@ -607,7 +586,6 @@ public class CFICommands extends MethodCommands {
@Command( @Command(
aliases = {"worldthickness", "width", "thickness"}, aliases = {"worldthickness", "width", "thickness"},
usage = "<height>",
desc = "Set the thickness of the generated world\n" + desc = "Set the thickness of the generated world\n" +
" - A value of 0 is the default and will not modify the height" " - A value of 0 is the default and will not modify the height"
) )
@ -620,7 +598,6 @@ public class CFICommands extends MethodCommands {
@Command( @Command(
aliases = {"floorthickness", "floorheight", "floorwidth"}, aliases = {"floorthickness", "floorheight", "floorwidth"},
usage = "<height>",
desc = "Set the thickness of the top layer\n" + desc = "Set the thickness of the top layer\n" +
" - A value of 0 is the default and will only set the top block" " - A value of 0 is the default and will only set the top block"
) )
@ -659,7 +636,6 @@ public class CFICommands extends MethodCommands {
@Command( @Command(
aliases = {"waterheight", "sealevel", "setwaterheight"}, aliases = {"waterheight", "sealevel", "setwaterheight"},
usage = "<height>",
desc = "Set the level water is generated at\n" + desc = "Set the level water is generated at\n" +
"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)" " - By default water is disabled (with a value of 0)"
@ -785,14 +761,14 @@ public class CFICommands extends MethodCommands {
int biomePriority = gen.getBiomePriority(); int biomePriority = gen.getBiomePriority();
Message msg = msg("&8>>&7 Current Settings &8<<&7").newline() Message msg = msg(">> Current Settings <<").newline()
.text("&7Randomization ").text("&7[&a" + (Boolean.toString(rand).toUpperCase()) + "&7]").cmdTip(alias() + " randomization " + (!rand)) .text("Randomization ").text("[" + (Boolean.toString(rand).toUpperCase()) + "]").cmdTip(alias() + " randomization " + (!rand))
.newline() .newline()
.text("&7Mask ").text("&7[&a" + mask + "&7]").cmdTip(alias() + " mask") .text("Mask ").text("[" + mask + "]").cmdTip(alias() + " mask")
.newline() .newline()
.text("&7Blocks ").text("&7[&a" + blocks + "&7]").tooltip(blockList).command(alias() + " paletteBlocks") .text("Blocks ").text("[" + blocks + "]").tooltip(blockList).command(alias() + " paletteBlocks")
.newline() .newline()
.text("&7BiomePriority ").text("&7[&a" + biomePriority + "&7]").cmdTip(alias() + " biomepriority") .text("BiomePriority ").text("[" + biomePriority + "]").cmdTip(alias() + " biomepriority")
.newline(); .newline();
if (settings.image != null) { if (settings.image != null) {
@ -802,19 +778,19 @@ public class CFICommands extends MethodCommands {
if (settings.mask != null) colorArgs.append(" " + settings.maskArg); if (settings.mask != null) colorArgs.append(" " + settings.maskArg);
if (!settings.whiteOnly) colorArgs.append(" -w"); if (!settings.whiteOnly) colorArgs.append(" -w");
msg.text("&7Image: ") msg.text("Image: ")
.text("&7[&a" + settings.imageArg + "&7]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "image")) .text("[" + settings.imageArg + "]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "image"))
.newline().newline() .newline().newline()
.text("&cLet's Color&7: ") .text("&cLet's Color: ")
.cmdOptions(alias() + " ", colorArgs.toString(), "Biomes", "Blocks", "BlockAndBiome", "Glass") .cmdOptions(alias() + " ", colorArgs.toString(), "Biomes", "Blocks", "BlockAndBiome", "Glass")
.newline(); .newline();
} else { } else {
msg.newline().text("You can color a world using an image like ") msg.newline().text("You can color a world using an image like ")
.text("&7[&aThis&7]").linkTip("http://i.imgur.com/vJYinIU.jpg").newline() .text("[This]").linkTip("http://i.imgur.com/vJYinIU.jpg").newline()
.text("&cYou MUST provide an image: ") .text("&cYou MUST provide an image: ")
.text("&7[&aNone&7]").cmdTip(alias() + " " + Commands.getAlias(Command.class, "image")).newline(); .text("[None]").cmdTip(alias() + " " + Commands.getAlias(Command.class, "image")).newline();
} }
msg.text("&8< &7[&aBack&7]").cmdTip(alias()).send(fp); msg.text("< [Back]").cmdTip(alias()).send(fp);
} }
@Command( @Command(
@ -835,12 +811,12 @@ public class CFICommands extends MethodCommands {
StringBuilder cmd = new StringBuilder(alias() + " mask "); StringBuilder cmd = new StringBuilder(alias() + " mask ");
msg("&8>>&7 Current Settings &8<<&7").newline() msg(">> Current Settings <<").newline()
.text("&7Image Mask ").text("&7[&a" + settings.imageMaskArg + "&7]").suggestTip(cmd + "http://") .text("Image Mask ").text("[" + settings.imageMaskArg + "]").suggestTip(cmd + "http://")
.newline() .newline()
.text("&7WorldEdit Mask ").text("&7[&a" + settings.maskArg + "&7]").suggestTip(cmd + "<mask>") .text("WorldEdit Mask ").text("[" + settings.maskArg + "]").suggestTip(cmd + "<mask>")
.newline() .newline()
.text("&8< &7[&aBack&7]").cmdTip(alias() + " " + settings.getCategory()).send(fp); .text("< [Back]").cmdTip(alias() + " " + settings.getCategory()).send(fp);
} }
@Command( @Command(
@ -861,10 +837,10 @@ public class CFICommands extends MethodCommands {
if (pattern != null) { if (pattern != null) {
dispathcer.call(settings.getCategory(), context.getLocals(), new String[0]); dispathcer.call(settings.getCategory(), context.getLocals(), new String[0]);
} else { } else {
msg("&8>>&7 Current Settings &8<<&7").newline() msg(">> Current Settings <<").newline()
.text("&7Pattern ").text("&7[&aClick Here&7]").suggestTip(cmd + " stone") .text("Pattern ").text("[Click Here]").suggestTip(cmd + " stone")
.newline() .newline()
.text("&8< &7[&aBack&7]").cmdTip(alias() + " " + settings.getCategory()).send(fp); .text("< [Back]").cmdTip(alias() + " " + settings.getCategory()).send(fp);
} }
} }
@ -902,9 +878,9 @@ public class CFICommands extends MethodCommands {
StringBuilder cmd = new StringBuilder(alias() + " image "); StringBuilder cmd = new StringBuilder(alias() + " image ");
if (image == null) { if (image == null) {
msg("Please provide an image:").newline() msg("Please provide an image:").newline()
.text("From a URL: ").text("&7[&aClick Here&7]").suggestTip(cmd + "http://") .text("From a URL: ").text("[Click Here]").suggestTip(cmd + "http://")
.newline() .newline()
.text("From a file: ").text("&7[&aClick Here&7]").suggestTip(cmd + "file://") .text("From a file: ").text("[Click Here]").suggestTip(cmd + "file://")
.send(fp); .send(fp);
} else { } else {
if (settings.hasGenerator()) { if (settings.hasGenerator()) {
@ -931,7 +907,7 @@ public class CFICommands extends MethodCommands {
msg("What would you like to populate?").newline() msg("What would you like to populate?").newline()
.text("(You will need to type these commands)").newline() .text("(You will need to type these commands)").newline()
.cmdOptions(alias() + " ", "", "Ores", "Ore", "Caves", "Schematics", "Smooth") .cmdOptions(alias() + " ", "", "Ores", "Ore", "Caves", "Schematics", "Smooth")
.newline().text("&8< &7[&aBack&7]").cmdTip(alias()) .newline().text("< [Back]").cmdTip(alias())
.send(fp); .send(fp);
} }
@ -966,49 +942,49 @@ public class CFICommands extends MethodCommands {
String waterHeight = Commands.getAlias(CFICommands.class, "waterheight"); String waterHeight = Commands.getAlias(CFICommands.class, "waterheight");
String snow = Commands.getAlias(CFICommands.class, "snow"); String snow = Commands.getAlias(CFICommands.class, "snow");
Message msg = msg("&8>>&7 Current Settings &8<<&7").newline() Message msg = msg(">> Current Settings <<").newline()
.text("&7Mask ").text("&7[&a" + mask + "&7]").cmdTip(alias() + " mask") .text("Mask ").text("[" + mask + "]").cmdTip(alias() + " mask")
.newline() .newline()
.text("&7Pattern ").text("&7[&a" + pattern + "&7]").cmdTip(alias() + " pattern") .text("Pattern ").text("[" + pattern + "]").cmdTip(alias() + " pattern")
.newline() .newline()
.newline() .newline()
.text("&8>>&7 Components &8<<&7") .text(">> Components <<")
.newline() .newline()
.text("&7[&aHeight&7]").suggestTip(alias() + " " + alias("height") + " 120").text(" - Terrain height for whole map") .text("[Height]").suggestTip(alias() + " " + alias("height") + " 120").text(" - Terrain height for whole map")
.newline() .newline()
.text("&7[&aWaterHeight&7]").suggestTip(alias() + " " + alias("waterheight") + " 60").text(" - Sea level for whole map") .text("[WaterHeight]").suggestTip(alias() + " " + alias("waterheight") + " 60").text(" - Sea level for whole map")
.newline() .newline()
.text("&7[&aFloorThickness&7]").suggestTip(alias() + " " + alias("floorthickness") + " 60").text(" - Floor thickness of entire map") .text("[FloorThickness]").suggestTip(alias() + " " + alias("floorthickness") + " 60").text(" - Floor thickness of entire map")
.newline() .newline()
.text("&7[&aWorldThickness&7]").suggestTip(alias() + " " + alias("worldthickness") + " 60").text(" - World thickness of entire map") .text("[WorldThickness]").suggestTip(alias() + " " + alias("worldthickness") + " 60").text(" - World thickness of entire map")
.newline() .newline()
.text("&7[&aSnow&7]").suggestTip(alias() + " " + alias("snow") + maskArgs).text(" - Set snow in the masked areas") .text("[Snow]").suggestTip(alias() + " " + alias("snow") + maskArgs).text(" - Set snow in the masked areas")
.newline(); .newline();
if (pattern != null) { if (pattern != null) {
String disabled = "You must specify a pattern"; String disabled = "You must specify a pattern";
msg msg
.text("&7[&cWaterId&7]").tooltip(disabled).newline() .text("[&cWaterId]").tooltip(disabled).newline()
.text("&7[&cBedrockId&7]").tooltip(disabled).newline() .text("[&cBedrockId]").tooltip(disabled).newline()
.text("&7[&cFloor&7]").tooltip(disabled).newline() .text("[&cFloor]").tooltip(disabled).newline()
.text("&7[&cMain&7]").tooltip(disabled).newline() .text("[&cMain]").tooltip(disabled).newline()
.text("&7[&cColumn&7]").tooltip(disabled).newline() .text("[&cColumn]").tooltip(disabled).newline()
.text("&7[&cOverlay&7]").tooltip(disabled).newline(); .text("[&cOverlay]").tooltip(disabled).newline();
} else { } else {
StringBuilder compArgs = new StringBuilder(); StringBuilder compArgs = new StringBuilder();
compArgs.append(" " + settings.patternArg + maskArgs); compArgs.append(" " + settings.patternArg + maskArgs);
msg msg
.text("&7[&aWaterId&7]").cmdTip(alias() + " waterId " + pattern).text(" - Water id for whole map").newline() .text("[WaterId]").cmdTip(alias() + " waterId " + pattern).text(" - Water id for whole map").newline()
.text("&7[&aBedrockId&7]").cmdTip(alias() + " baseId " + pattern).text(" - Bedrock id for whole map").newline() .text("[BedrockId]").cmdTip(alias() + " baseId " + pattern).text(" - Bedrock id for whole map").newline()
.text("&7[&aFloor&7]").cmdTip(alias() + " floor" + compArgs).text(" - Set the floor in the masked areas").newline() .text("[Floor]").cmdTip(alias() + " floor" + compArgs).text(" - Set the floor in the masked areas").newline()
.text("&7[&aMain&7]").cmdTip(alias() + " main" + compArgs).text(" - Set the main block in the masked areas").newline() .text("[Main]").cmdTip(alias() + " main" + compArgs).text(" - Set the main block in the masked areas").newline()
.text("&7[&aColumn&7]").cmdTip(alias() + " column" + compArgs).text(" - Set the columns in the masked areas").newline() .text("[Column]").cmdTip(alias() + " column" + compArgs).text(" - Set the columns in the masked areas").newline()
.text("&7[&aOverlay&7]").cmdTip(alias() + " overlay" + compArgs).text(" - Set the overlay in the masked areas").newline(); .text("[Overlay]").cmdTip(alias() + " overlay" + compArgs).text(" - Set the overlay in the masked areas").newline();
} }
msg.newline() msg.newline()
.text("&8< &7[&aBack&7]").cmdTip(alias()) .text("< [Back]").cmdTip(alias())
.send(fp); .send(fp);
} }
@ -1160,9 +1136,9 @@ public class CFICommands extends MethodCommands {
protected void mainMenu(FawePlayer fp) { protected void mainMenu(FawePlayer fp) {
msg("What do you want to do now?").newline() msg("What do you want to do now?").newline()
.cmdOptions(alias() + " ", "", "Coloring", "Component", "Populate", "Brush") .cmdOptions(alias() + " ", "", "Coloring", "Component", "Populate", "Brush")
.newline().text("&3<> &7[&aView&7]").command(alias() + " " + Commands.getAlias(CFICommands.class, "download")).tooltip("View full resolution image") .newline().text("<> [View]").command(alias() + " " + Commands.getAlias(CFICommands.class, "download")).tooltip("View full resolution image")
.newline().text("&4>< &7[&aCancel&7]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "cancel")) .newline().text(">< [Cancel]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "cancel"))
.newline().text("&2>> &7[&aDone&7]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "done")) .newline().text("&2>> [Done]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "done"))
.send(fp); .send(fp);
} }
} }

View File

@ -3,7 +3,7 @@ package com.boydti.fawe.config;
import com.boydti.fawe.configuration.ConfigurationSection; import com.boydti.fawe.configuration.ConfigurationSection;
import com.boydti.fawe.configuration.file.YamlConfiguration; import com.boydti.fawe.configuration.file.YamlConfiguration;
import com.boydti.fawe.util.StringMan; import com.boydti.fawe.util.StringMan;
import com.sk89q.minecraft.util.commands.Command; import org.enginehub.piston.annotation.Command;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
@ -31,53 +31,6 @@ public class Commands {
} }
} }
public static Command fromArgs(String[] aliases, String usage, String desc, int min, Integer max, String flags, String help, boolean queued) {
int finalMax = max == null ? -1 : max;
return new Command() {
@Override
public Class<? extends Annotation> annotationType() {
return Command.class;
}
@Override
public String[] aliases() {
return aliases;
}
@Override
public String usage() {
return usage;
}
@Override
public String desc() {
return desc;
}
@Override
public int min() {
return min;
}
@Override
public int max() {
return finalMax;
}
@Override
public String flags() {
return flags;
}
@Override
public String help() {
return help;
}
@Override
public boolean anyFlags() {
return !(flags.isEmpty() || flags.matches("[a-z]+"));
}
@Override
public boolean queued() {
return queued;
}
};
}
public static Command translate(Class clazz, final Command command) { public static Command translate(Class clazz, final Command command) {
if (cmdConfig == null || command instanceof TranslatedCommand) { if (cmdConfig == null || command instanceof TranslatedCommand) {
return command; return command;

View File

@ -250,23 +250,28 @@ public abstract class MappedFaweQueue<WORLD, CHUNK, CHUNKSECTIONS, SECTION> impl
} }
} }
@Override
public Settings getSettings() { public Settings getSettings() {
return settings; return settings;
} }
@Override
public void setSettings(Settings settings) { public void setSettings(Settings settings) {
this.settings = settings == null ? Settings.IMP : settings; this.settings = settings == null ? Settings.IMP : settings;
} }
@Override
public void setWorld(String world) { public void setWorld(String world) {
this.world = world; this.world = world;
this.weWorld = null; this.weWorld = null;
} }
@Override
public World getWEWorld() { public World getWEWorld() {
return weWorld != null ? weWorld : (weWorld = FaweAPI.getWorld(world)); return weWorld != null ? weWorld : (weWorld = FaweAPI.getWorld(world));
} }
@Override
public String getWorldName() { public String getWorldName() {
return world; return world;
} }
@ -288,52 +293,59 @@ public abstract class MappedFaweQueue<WORLD, CHUNK, CHUNKSECTIONS, SECTION> impl
@Override @Override
public boolean supports(Capability capability) { public boolean supports(Capability capability) {
if (capability == Capability.CHANGE_TASKS) { return capability == Capability.CHANGE_TASKS;
return true;
}
return false;
} }
public void setSessions(ConcurrentLinkedDeque<EditSession> sessions) { public void setSessions(ConcurrentLinkedDeque<EditSession> sessions) {
this.sessions = sessions; this.sessions = sessions;
} }
@Override
public long getModified() { public long getModified() {
return modified; return modified;
} }
@Override
public void setModified(long modified) { public void setModified(long modified) {
this.modified = modified; this.modified = modified;
} }
@Override
public RunnableVal2<ProgressType, Integer> getProgressTask() { public RunnableVal2<ProgressType, Integer> getProgressTask() {
return progressTask; return progressTask;
} }
@Override
public void setProgressTask(RunnableVal2<ProgressType, Integer> progressTask) { public void setProgressTask(RunnableVal2<ProgressType, Integer> progressTask) {
this.progressTask = progressTask; this.progressTask = progressTask;
} }
@Override
public void setChangeTask(RunnableVal2<FaweChunk, FaweChunk> changeTask) { public void setChangeTask(RunnableVal2<FaweChunk, FaweChunk> changeTask) {
this.changeTask = changeTask; this.changeTask = changeTask;
} }
@Override
public RunnableVal2<FaweChunk, FaweChunk> getChangeTask() { public RunnableVal2<FaweChunk, FaweChunk> getChangeTask() {
return changeTask; return changeTask;
} }
@Override
public SetQueue.QueueStage getStage() { public SetQueue.QueueStage getStage() {
return stage; return stage;
} }
@Override
public void setStage(SetQueue.QueueStage stage) { public void setStage(SetQueue.QueueStage stage) {
this.stage = stage; this.stage = stage;
} }
@Override
public void addNotifyTask(Runnable runnable) { public void addNotifyTask(Runnable runnable) {
this.tasks.add(runnable); this.tasks.add(runnable);
} }
@Override
public void addTask(Runnable whenFree) { public void addTask(Runnable whenFree) {
tasks.add(whenFree); tasks.add(whenFree);
} }

View File

@ -1,16 +1,14 @@
package com.boydti.fawe.jnbt; package com.boydti.fawe.jnbt;
import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.BBC;
import com.boydti.fawe.object.RunnableVal2;
import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.object.exception.FaweException;
import com.sk89q.jnbt.NBTInputStream; import com.sk89q.jnbt.NBTInputStream;
import java.io.DataInput;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import java.util.function.Function;
public class NBTStreamer { public class NBTStreamer {
private final NBTInputStream is; private final NBTInputStream is;
@ -27,7 +25,7 @@ public class NBTStreamer {
* @throws IOException * @throws IOException
*/ */
public void readFully() throws IOException { public void readFully() throws IOException {
is.readNamedTagLazy(node -> readers.get(node)); is.readNamedTagLazy(readers::get);
is.close(); is.close();
} }

View File

@ -122,7 +122,7 @@ public class SchematicStreamer extends NBTStreamer {
ByteReader biomeReader = new ByteReader() { ByteReader biomeReader = new ByteReader() {
@Override @Override
public void run(int index, int value) { public void run(int index, int value) {
fc.setBiome(index, BiomeTypes.get(value)); fc.setBiome(index, BiomeTypes.register(value));
} }
}; };
NBTStreamReader<Integer, Integer> initializer23 = new NBTStreamReader<Integer, Integer>() { NBTStreamReader<Integer, Integer> initializer23 = new NBTStreamReader<Integer, Integer>() {

View File

@ -1,11 +1,7 @@
package com.boydti.fawe.jnbt.anvil; package com.boydti.fawe.jnbt.anvil;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.example.SimpleIntFaweChunk; import com.boydti.fawe.example.SimpleIntFaweChunk;
import com.boydti.fawe.jnbt.anvil.HeightMapMCADrawer;
import com.boydti.fawe.jnbt.anvil.MCAChunk;
import com.boydti.fawe.jnbt.anvil.MCAWriter;
import com.boydti.fawe.object.*; import com.boydti.fawe.object.*;
import com.boydti.fawe.object.brush.visualization.VirtualWorld; import com.boydti.fawe.object.brush.visualization.VirtualWorld;
import com.boydti.fawe.object.change.StreamChange; import com.boydti.fawe.object.change.StreamChange;
@ -930,7 +926,7 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr
public BiomeType getBiomeType(int x, int z) throws FaweException.FaweChunkLoadException { public BiomeType getBiomeType(int x, int z) throws FaweException.FaweChunkLoadException {
int index = z * getWidth() + x; int index = z * getWidth() + x;
if (index < 0 || index >= getArea()) index = Math.floorMod(index, getArea()); if (index < 0 || index >= getArea()) index = Math.floorMod(index, getArea());
return BiomeTypes.get(biomes.getByte(index)); return BiomeTypes.register(biomes.getByte(index));
} }
@Override @Override

View File

@ -9,14 +9,25 @@ import com.boydti.fawe.object.number.MutableLong;
import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.MathMan; import com.boydti.fawe.util.MathMan;
import com.boydti.fawe.util.ReflectionUtils; import com.boydti.fawe.util.ReflectionUtils;
import com.sk89q.jnbt.*; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.NBTConstants;
import com.sk89q.jnbt.NBTInputStream;
import com.sk89q.jnbt.NBTOutputStream;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes; import com.sk89q.worldedit.world.biome.BiomeTypes;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
public class MCAChunk extends FaweChunk<Void> { public class MCAChunk extends FaweChunk<Void> {
@ -105,12 +116,9 @@ public class MCAChunk extends FaweChunk<Void> {
} }
out.writeNamedTag("HeightMap", heightMap); out.writeNamedTag("HeightMap", heightMap);
out.writeNamedTagName("Sections", NBTConstants.TYPE_LIST); out.writeNamedTagName("Sections", NBTConstants.TYPE_LIST);
nbtOut.getOutputStream().writeByte(NBTConstants.TYPE_COMPOUND); nbtOut.writeByte(NBTConstants.TYPE_COMPOUND);
int len = 0; int len = (int) Arrays.stream(ids).filter(Objects::nonNull).count();
for (int[] id : ids) { nbtOut.writeInt(len);
if (id != null) len++;
}
nbtOut.getOutputStream().writeInt(len);
for (int layer = 0; layer < ids.length; layer++) { for (int layer = 0; layer < ids.length; layer++) {
int[] idLayer = ids[layer]; int[] idLayer = ids[layer];
if (idLayer == null) { if (idLayer == null) {
@ -131,8 +139,7 @@ public class MCAChunk extends FaweChunk<Void> {
buffer = new byte[8192]; buffer = new byte[8192];
} }
FastByteArrayOutputStream buffered = new FastByteArrayOutputStream(buffer); FastByteArrayOutputStream buffered = new FastByteArrayOutputStream(buffer);
DataOutputStream dataOut = new DataOutputStream(buffered); try (NBTOutputStream nbtOut = new NBTOutputStream(buffered)) {
try (NBTOutputStream nbtOut = new NBTOutputStream((DataOutput) dataOut)) {
write(nbtOut); write(nbtOut);
} }
return buffered.toByteArray(); return buffered.toByteArray();
@ -603,14 +610,14 @@ public class MCAChunk extends FaweChunk<Void> {
public BiomeType[] getBiomeArray() { public BiomeType[] getBiomeArray() {
BiomeType[] arr = new BiomeType[256]; BiomeType[] arr = new BiomeType[256];
for (int i = 0; i < arr.length; i++) { for (int i = 0; i < arr.length; i++) {
arr[i] = BiomeTypes.get(biomes[i]); arr[i] = BiomeTypes.register(biomes[i]);
} }
return arr; return arr;
} }
@Override @Override
public BiomeType getBiomeType(int x, int z) { public BiomeType getBiomeType(int x, int z) {
return BiomeTypes.get(biomes[(x & 15) + ((z & 15) << 4)]); return BiomeTypes.register(biomes[(x & 15) + ((z & 15) << 4)]);
} }
@Override @Override

View File

@ -4,7 +4,6 @@ import com.boydti.fawe.FaweCache;
import com.boydti.fawe.object.FaweChunk; import com.boydti.fawe.object.FaweChunk;
import com.boydti.fawe.object.io.FastByteArrayOutputStream; import com.boydti.fawe.object.io.FastByteArrayOutputStream;
import com.boydti.fawe.util.MathMan; import com.boydti.fawe.util.MathMan;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.ListTag; import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.NBTConstants; import com.sk89q.jnbt.NBTConstants;
@ -15,9 +14,6 @@ import com.sk89q.worldedit.world.block.BlockID;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypes;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -224,8 +220,7 @@ public class WritableMCAChunk extends FaweChunk<Void> {
buffer = new byte[8192]; buffer = new byte[8192];
} }
FastByteArrayOutputStream buffered = new FastByteArrayOutputStream(buffer); FastByteArrayOutputStream buffered = new FastByteArrayOutputStream(buffer);
DataOutputStream dataOut = new DataOutputStream(buffered); try (NBTOutputStream nbtOut = new NBTOutputStream(buffered)) {
try (NBTOutputStream nbtOut = new NBTOutputStream((DataOutput) dataOut)) {
write(nbtOut); write(nbtOut);
} }
return buffered.toByteArray(); return buffered.toByteArray();

View File

@ -24,10 +24,9 @@ import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.extension.platform.PlatformManager; import com.sk89q.worldedit.extension.platform.PlatformManager;
import com.sk89q.worldedit.extension.platform.PlayerProxy; import com.sk89q.worldedit.extension.platform.PlayerProxy;
import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard;
@ -46,8 +45,6 @@ import com.sk89q.worldedit.regions.selector.Polygonal2DRegionSelector;
import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import javax.annotation.Nullable;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -59,6 +56,7 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.jetbrains.annotations.NotNull;
public abstract class FawePlayer<T> extends Metadatable { public abstract class FawePlayer<T> extends Metadatable {
@ -152,74 +150,70 @@ public abstract class FawePlayer<T> extends Metadatable {
return cancelled; return cancelled;
} }
private void setConfirmTask(@Nullable Runnable task, CommandContext context, String command) { private void setConfirmTask(@NotNull Runnable task, CommandContext context) {
if (task != null) { Runnable newTask = () -> PlatformCommandManager.getInstance().handleCommandTask(() -> {
Runnable newTask = () -> CommandManager.getInstance().handleCommandTask(() -> { task.run();
task.run(); return null;
return null; }, context.getLocals());
}, context.getLocals()); setMeta("cmdConfirm", newTask);
setMeta("cmdConfirm", newTask);
} else {
setMeta("cmdConfirm", new CommandEvent(getPlayer(), command));
}
} }
public void checkConfirmation(@Nullable Runnable task, String command, int times, int limit, CommandContext context) throws RegionOperationException { public void checkConfirmation(@NotNull Runnable task, String command, int times, int limit, CommandContext context) throws RegionOperationException {
if (command != null && !getMeta("cmdConfirmRunning", false)) { if (command != null && !getMeta("cmdConfirmRunning", false)) {
if (times > limit) { if (times > limit) {
setConfirmTask(task, context, command); setConfirmTask(task, context);
String volume = "<unspecified>"; String volume = "<unspecified>";
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(0, times, command, volume)); throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(0, times, command, volume));
} }
} }
if (task != null) task.run(); task.run();
} }
public void checkConfirmationRadius(@Nullable Runnable task, String command, int radius, CommandContext context) throws RegionOperationException { public void checkConfirmationRadius(@NotNull Runnable task, String command, int radius, CommandContext context) throws RegionOperationException {
if (command != null && !getMeta("cmdConfirmRunning", false)) { if (command != null && !getMeta("cmdConfirmRunning", false)) {
if (radius > 0) { if (radius > 0) {
if (radius > 448) { if (radius > 448) {
setConfirmTask(task, context, command); setConfirmTask(task, context);
long volume = (long) (Math.PI * ((double) radius * radius)); long volume = (long) (Math.PI * ((double) radius * radius));
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(0, radius, command, NumberFormat.getNumberInstance().format(volume))); throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(0, radius, command, NumberFormat.getNumberInstance().format(volume)));
} }
} }
} }
if (task != null) task.run(); task.run();
} }
public void checkConfirmationStack(@Nullable Runnable task, String command, Region region, int times, CommandContext context) throws RegionOperationException { public void checkConfirmationStack(@NotNull Runnable task, String command, Region region, int times, CommandContext context) throws RegionOperationException {
if (command != null && !getMeta("cmdConfirmRunning", false)) { if (command != null && !getMeta("cmdConfirmRunning", false)) {
if (region != null) { if (region != null) {
BlockVector3 min = region.getMinimumPoint(); BlockVector3 min = region.getMinimumPoint();
BlockVector3 max = region.getMaximumPoint(); BlockVector3 max = region.getMaximumPoint();
long area = (long) ((max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1)) * times; long area = (long) ((max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1)) * times;
if (area > 2 << 18) { if (area > 2 << 18) {
setConfirmTask(task, context, command); setConfirmTask(task, context);
BlockVector3 base = max.subtract(min).add(BlockVector3.ONE); BlockVector3 base = max.subtract(min).add(BlockVector3.ONE);
long volume = (long) base.getX() * base.getZ() * base.getY() * times; long volume = (long) base.getX() * base.getZ() * base.getY() * times;
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(min, max, command, NumberFormat.getNumberInstance().format(volume))); throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(min, max, command, NumberFormat.getNumberInstance().format(volume)));
} }
} }
} }
if (task != null) task.run(); task.run();
} }
public void checkConfirmationRegion(@Nullable Runnable task, String command, Region region, CommandContext context) throws RegionOperationException { public void checkConfirmationRegion(@NotNull Runnable task, String command, Region region, CommandContext context) throws RegionOperationException {
if (command != null && !getMeta("cmdConfirmRunning", false)) { if (command != null && !getMeta("cmdConfirmRunning", false)) {
if (region != null) { if (region != null) {
BlockVector3 min = region.getMinimumPoint(); BlockVector3 min = region.getMinimumPoint();
BlockVector3 max = region.getMaximumPoint(); BlockVector3 max = region.getMaximumPoint();
long area = (max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1); long area = (max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1);
if (area > 2 << 18) { if (area > 2 << 18) {
setConfirmTask(task, context, command); setConfirmTask(task, context);
BlockVector3 base = max.subtract(min).add(BlockVector3.ONE); BlockVector3 base = max.subtract(min).add(BlockVector3.ONE);
long volume = (long) base.getX() * base.getZ() * base.getY(); long volume = (long) base.getX() * base.getZ() * base.getY();
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(min, max, command, NumberFormat.getNumberInstance().format(volume))); throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(min, max, command, NumberFormat.getNumberInstance().format(volume)));
} }
} }
} }
if (task != null) task.run(); task.run();
} }
public synchronized boolean confirm() { public synchronized boolean confirm() {

View File

@ -175,12 +175,6 @@ public interface FaweQueue extends HasFaweQueue, Extent {
fc.fillCuboid(0, 15, minY, maxY, 0, 15, combinedId); fc.fillCuboid(0, 15, minY, maxY, 0, 15, combinedId);
fc.optimize(); fc.optimize();
int bcx = (current.minX) >> 4;
int bcz = (current.minZ) >> 4;
int tcx = (current.maxX) >> 4;
int tcz = (current.maxZ) >> 4;
// [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge]
MainUtil.chunkTaskSync(current, new RunnableVal<int[]>() { MainUtil.chunkTaskSync(current, new RunnableVal<int[]>() {
@Override @Override
public void run(int[] value) { public void run(int[] value) {
@ -228,6 +222,7 @@ public interface FaweQueue extends HasFaweQueue, Extent {
File getSaveFolder(); File getSaveFolder();
@Override
default int getMaxY() { default int getMaxY() {
World weWorld = getWEWorld(); World weWorld = getWEWorld();
return weWorld == null ? 255 : weWorld.getMaxY(); return weWorld == null ? 255 : weWorld.getMaxY();
@ -452,7 +447,7 @@ public interface FaweQueue extends HasFaweQueue, Extent {
try { try {
return getCombinedId4Data(x, y, z); return getCombinedId4Data(x, y, z);
} catch (FaweException ignore) { } catch (FaweException ignore) {
session.debug(BBC.WORLDEDIT_FAILED_LOAD_CHUNK, x >> 4, z >> 4); BBC.WORLDEDIT_FAILED_LOAD_CHUNK.send(session.getPlayer(),x >> 4, z >> 4);
return def; return def;
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -125,6 +125,7 @@ public class RegionWrapper extends CuboidRegion {
return this.minX + "," + this.minY + "," + this.minZ + "->" + this.maxX + "," + this.maxY + "," + this.maxZ; return this.minX + "," + this.minY + "," + this.minZ + "->" + this.maxX + "," + this.maxY + "," + this.maxZ;
} }
@Override
public boolean isGlobal() { public boolean isGlobal() {
return minX == Integer.MIN_VALUE && minZ == Integer.MIN_VALUE && maxX == Integer.MAX_VALUE && maxZ == Integer.MAX_VALUE && minY <= 0 && maxY >= 255; return minX == Integer.MIN_VALUE && minZ == Integer.MIN_VALUE && maxX == Integer.MAX_VALUE && maxZ == Integer.MAX_VALUE && minY <= 0 && maxY >= 255;
} }

View File

@ -13,7 +13,7 @@ import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.input.InputParseException; import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.internal.expression.Expression; import com.sk89q.worldedit.internal.expression.Expression;
@ -62,7 +62,7 @@ public class BrushSettings {
} }
public static BrushSettings get(BrushTool tool, Player player, LocalSession session, Map<String, Object> settings) throws CommandException, InputParseException { public static BrushSettings get(BrushTool tool, Player player, LocalSession session, Map<String, Object> settings) throws CommandException, InputParseException {
Dispatcher dispatcher = CommandManager.getInstance().getDispatcher(); Dispatcher dispatcher = PlatformCommandManager.getInstance().getCommandManager();
Dispatcher brushDispatcher = (Dispatcher) (dispatcher.get("brush").getCallable()); Dispatcher brushDispatcher = (Dispatcher) (dispatcher.get("brush").getCallable());
if (brushDispatcher == null) { if (brushDispatcher == null) {
return null; return null;

View File

@ -10,7 +10,7 @@ import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.command.tool.brush.Brush;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector; import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
@ -48,7 +48,7 @@ public class CommandBrush implements Brush {
List<String> cmds = StringMan.split(replaced, ';'); List<String> cmds = StringMan.split(replaced, ';');
for (String cmd : cmds) { for (String cmd : cmds) {
CommandEvent event = new CommandEvent(wePlayer, cmd); CommandEvent event = new CommandEvent(wePlayer, cmd);
CommandManager.getInstance().handleCommandOnCurrentThread(event); PlatformCommandManager.getInstance().handleCommandOnCurrentThread(event);
} }
} }
} }

View File

@ -10,7 +10,7 @@ import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector; import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
@ -42,7 +42,7 @@ public class ScatterCommand extends ScatterBrush {
List<String> cmds = StringMan.split(replaced, ';'); List<String> cmds = StringMan.split(replaced, ';');
for (String cmd : cmds) { for (String cmd : cmds) {
CommandEvent event = new CommandEvent(wePlayer, cmd); CommandEvent event = new CommandEvent(wePlayer, cmd);
CommandManager.getInstance().handleCommandOnCurrentThread(event); PlatformCommandManager.getInstance().handleCommandOnCurrentThread(event);
} }
} }
} }

View File

@ -26,7 +26,6 @@ public interface HeightMap {
default void applyHeightMapData(int[][] data, EditSession session, BlockVector3 pos, int size, double yscale, boolean smooth, boolean towards, boolean layers) throws MaxChangedBlocksException { default void applyHeightMapData(int[][] data, EditSession session, BlockVector3 pos, int size, double yscale, boolean smooth, boolean towards, boolean layers) throws MaxChangedBlocksException {
BlockVector3 top = session.getMaximumPoint(); BlockVector3 top = session.getMaximumPoint();
int maxY = top.getBlockY(); int maxY = top.getBlockY();
int diameter = 2 * size + 1;
Location min = new Location(session.getWorld(), pos.subtract(size, maxY, size).toVector3()); Location min = new Location(session.getWorld(), pos.subtract(size, maxY, size).toVector3());
BlockVector3 max = pos.add(size, maxY, size); BlockVector3 max = pos.add(size, maxY, size);
Region region = new CuboidRegion(session.getWorld(), min.toBlockPoint(), max); Region region = new CuboidRegion(session.getWorld(), min.toBlockPoint(), max);
@ -34,6 +33,7 @@ public interface HeightMap {
if (smooth) { if (smooth) {
try { try {
HeightMapFilter filter = (HeightMapFilter) HeightMapFilter.class.getConstructors()[0].newInstance(GaussianKernel.class.getConstructors()[0].newInstance(5, 1)); HeightMapFilter filter = (HeightMapFilter) HeightMapFilter.class.getConstructors()[0].newInstance(GaussianKernel.class.getConstructors()[0].newInstance(5, 1));
int diameter = 2 * size + 1;
data[1] = filter.filter(data[1], diameter, diameter); data[1] = filter.filter(data[1], diameter, diameter);
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -1,6 +1,5 @@
package com.boydti.fawe.object.brush.visualization; package com.boydti.fawe.object.brush.visualization;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.example.SimpleIntFaweChunk; import com.boydti.fawe.example.SimpleIntFaweChunk;
import com.boydti.fawe.object.FaweChunk; import com.boydti.fawe.object.FaweChunk;
import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FawePlayer;
@ -8,9 +7,9 @@ import com.boydti.fawe.object.RunnableVal2;
import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.object.exception.FaweException;
import com.boydti.fawe.util.SetQueue; import com.boydti.fawe.util.SetQueue;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.world.biome.BiomeTypes; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operation;
import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector2;
@ -20,10 +19,10 @@ import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.weather.WeatherType; import com.sk89q.worldedit.world.weather.WeatherType;
import com.sk89q.worldedit.world.weather.WeatherTypes; import com.sk89q.worldedit.world.weather.WeatherTypes;
import java.io.File; import java.io.File;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;

View File

@ -4,7 +4,6 @@ import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.history.UndoContext; import com.sk89q.worldedit.history.UndoContext;
import com.sk89q.worldedit.history.change.Change; import com.sk89q.worldedit.history.change.Change;
import com.sk89q.worldedit.math.MutableBlockVector2; import com.sk89q.worldedit.math.MutableBlockVector2;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes; import com.sk89q.worldedit.world.biome.BiomeTypes;
public class MutableBiomeChange implements Change { public class MutableBiomeChange implements Change {
@ -26,11 +25,11 @@ public class MutableBiomeChange implements Change {
@Override @Override
public void undo(UndoContext context) throws WorldEditException { public void undo(UndoContext context) throws WorldEditException {
context.getExtent().setBiome(mutable, BiomeTypes.get(from)); context.getExtent().setBiome(mutable, BiomeTypes.register(from));
} }
@Override @Override
public void redo(UndoContext context) throws WorldEditException { public void redo(UndoContext context) throws WorldEditException {
context.getExtent().setBiome(mutable, BiomeTypes.get(to)); context.getExtent().setBiome(mutable, BiomeTypes.register(to));
} }
} }

View File

@ -4,7 +4,11 @@ import com.boydti.fawe.Fawe;
import com.boydti.fawe.config.Settings; import com.boydti.fawe.config.Settings;
import com.boydti.fawe.database.DBHandler; import com.boydti.fawe.database.DBHandler;
import com.boydti.fawe.database.RollbackDatabase; import com.boydti.fawe.database.RollbackDatabase;
import com.boydti.fawe.object.*; import com.boydti.fawe.object.FaweInputStream;
import com.boydti.fawe.object.FaweOutputStream;
import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.object.IntegerPair;
import com.boydti.fawe.object.RegionWrapper;
import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.MainUtil;
import com.sk89q.jnbt.NBTInputStream; import com.sk89q.jnbt.NBTInputStream;
import com.sk89q.jnbt.NBTOutputStream; import com.sk89q.jnbt.NBTOutputStream;
@ -13,12 +17,11 @@ import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypes;
import java.io.DataOutput;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -291,7 +294,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
} }
enttFile.getParentFile().mkdirs(); enttFile.getParentFile().mkdirs();
enttFile.createNewFile(); enttFile.createNewFile();
osENTCT = new NBTOutputStream((DataOutput) getCompressedOS(new FileOutputStream(enttFile))); osENTCT = new NBTOutputStream(getCompressedOS(new FileOutputStream(enttFile)));
return osENTCT; return osENTCT;
} }
@ -302,7 +305,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
} }
entfFile.getParentFile().mkdirs(); entfFile.getParentFile().mkdirs();
entfFile.createNewFile(); entfFile.createNewFile();
osENTCF = new NBTOutputStream((DataOutput) getCompressedOS(new FileOutputStream(entfFile))); osENTCF = new NBTOutputStream(getCompressedOS(new FileOutputStream(entfFile)));
return osENTCF; return osENTCF;
} }
@ -313,7 +316,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
} }
nbttFile.getParentFile().mkdirs(); nbttFile.getParentFile().mkdirs();
nbttFile.createNewFile(); nbttFile.createNewFile();
osNBTT = new NBTOutputStream((DataOutput) getCompressedOS(new FileOutputStream(nbttFile))); osNBTT = new NBTOutputStream(getCompressedOS(new FileOutputStream(nbttFile)));
return osNBTT; return osNBTT;
} }
@ -324,7 +327,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
} }
nbtfFile.getParentFile().mkdirs(); nbtfFile.getParentFile().mkdirs();
nbtfFile.createNewFile(); nbtfFile.createNewFile();
osNBTF = new NBTOutputStream((DataOutput) getCompressedOS(new FileOutputStream(nbtfFile))); osNBTF = new NBTOutputStream(getCompressedOS(new FileOutputStream(nbtfFile)));
return osNBTF; return osNBTF;
} }
@ -343,8 +346,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
if (!bioFile.exists()) { if (!bioFile.exists()) {
return null; return null;
} }
FaweInputStream is = MainUtil.getCompressedIS(new FileInputStream(bioFile)); return MainUtil.getCompressedIS(new FileInputStream(bioFile));
return is;
} }
@Override @Override
@ -391,8 +393,8 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
// skip mode // skip mode
gis.skipFully(1); gis.skipFully(1);
// origin // origin
ox = ((gis.read() << 24) + (gis.read() << 16) + (gis.read() << 8) + (gis.read() << 0)); ox = ((gis.read() << 24) + (gis.read() << 16) + (gis.read() << 8) + gis.read());
oz = ((gis.read() << 24) + (gis.read() << 16) + (gis.read() << 8) + (gis.read() << 0)); oz = ((gis.read() << 24) + (gis.read() << 16) + (gis.read() << 8) + gis.read());
setOrigin(ox, oz); setOrigin(ox, oz);
DiskStorageSummary summary = new DiskStorageSummary(ox, oz); DiskStorageSummary summary = new DiskStorageSummary(ox, oz);
if (!requiredRegion.isIn(ox, oz)) { if (!requiredRegion.isIn(ox, oz)) {
@ -432,8 +434,8 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
// skip mode // skip mode
gis.skipFully(1); gis.skipFully(1);
// origin // origin
ox = ((gis.read() << 24) + (gis.read() << 16) + (gis.read() << 8) + (gis.read() << 0)); ox = ((gis.read() << 24) + (gis.read() << 16) + (gis.read() << 8) + gis.read());
oz = ((gis.read() << 24) + (gis.read() << 16) + (gis.read() << 8) + (gis.read() << 0)); oz = ((gis.read() << 24) + (gis.read() << 16) + (gis.read() << 8) + gis.read());
setOrigin(ox, oz); setOrigin(ox, oz);
fis.close(); fis.close();
gis.close(); gis.close();
@ -446,8 +448,6 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
public static class DiskStorageSummary { public static class DiskStorageSummary {
private final int z;
private final int x;
public int[] blocks; public int[] blocks;
public int minX; public int minX;
@ -458,8 +458,6 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
public DiskStorageSummary(int x, int z) { public DiskStorageSummary(int x, int z) {
blocks = new int[BlockTypes.states.length]; blocks = new int[BlockTypes.states.length];
this.x = x;
this.z = z;
minX = x; minX = x;
maxX = x; maxX = x;
minZ = z; minZ = z;
@ -485,7 +483,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
for (int i = 0; i < blocks.length; i++) { for (int i = 0; i < blocks.length; i++) {
if (blocks[i] != 0) { if (blocks[i] != 0) {
BlockState state = BlockTypes.states[i]; BlockState state = BlockTypes.states[i];
map.put(state, (Integer) blocks[i]); map.put(state, blocks[i]);
} }
} }
return map; return map;
@ -498,18 +496,14 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
for (Map.Entry<BlockState, Integer> entry : map.entrySet()) { for (Map.Entry<BlockState, Integer> entry : map.entrySet()) {
BlockState id = entry.getKey(); BlockState id = entry.getKey();
int changes = entry.getValue(); int changes = entry.getValue();
double percent = ((changes * 1000l) / count) / 10d; double percent = (changes * 1000L / count) / 10d;
newMap.put(id, (Double) percent); newMap.put(id, percent);
} }
return newMap; return newMap;
} }
public int getSize() { public int getSize() {
int count = 0; return Arrays.stream(blocks).sum();
for (int block : blocks) {
count += block;
}
return count;
} }
} }

View File

@ -9,8 +9,6 @@ import com.boydti.fawe.util.MainUtil;
import com.sk89q.jnbt.NBTInputStream; import com.sk89q.jnbt.NBTInputStream;
import com.sk89q.jnbt.NBTOutputStream; import com.sk89q.jnbt.NBTOutputStream;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import java.io.DataOutput;
import java.io.IOException; import java.io.IOException;
/** /**
@ -189,7 +187,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
return entCStreamZip; return entCStreamZip;
} }
entCStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE); entCStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE);
return entCStreamZip = new NBTOutputStream((DataOutput) getCompressedOS(entCStream)); return entCStreamZip = new NBTOutputStream(getCompressedOS(entCStream));
} }
@Override @Override
@ -198,7 +196,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
return entRStreamZip; return entRStreamZip;
} }
entRStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE); entRStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE);
return entRStreamZip = new NBTOutputStream((DataOutput) getCompressedOS(entRStream)); return entRStreamZip = new NBTOutputStream(getCompressedOS(entRStream));
} }
@Override @Override
@ -207,7 +205,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
return tileCStreamZip; return tileCStreamZip;
} }
tileCStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE); tileCStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE);
return tileCStreamZip = new NBTOutputStream((DataOutput) getCompressedOS(tileCStream)); return tileCStreamZip = new NBTOutputStream(getCompressedOS(tileCStream));
} }
@Override @Override
@ -216,7 +214,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
return tileRStreamZip; return tileRStreamZip;
} }
tileRStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE); tileRStream = new FastByteArrayOutputStream(Settings.IMP.HISTORY.BUFFER_SIZE);
return tileRStreamZip = new NBTOutputStream((DataOutput) getCompressedOS(tileRStream)); return tileRStreamZip = new NBTOutputStream(getCompressedOS(tileRStream));
} }
@Override @Override

View File

@ -144,7 +144,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
return null; return null;
} }
int biomeId = mbb.get(HEADER_SIZE + (volume << 2) + index) & 0xFF; int biomeId = mbb.get(HEADER_SIZE + (volume << 2) + index) & 0xFF;
return BiomeTypes.get(biomeId); return BiomeTypes.register(biomeId);
} }
@Override @Override

View File

@ -1,6 +1,5 @@
package com.boydti.fawe.object.clipboard; package com.boydti.fawe.object.clipboard;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.config.Settings; import com.boydti.fawe.config.Settings;
import com.boydti.fawe.jnbt.NBTStreamer; import com.boydti.fawe.jnbt.NBTStreamer;
import com.boydti.fawe.object.IntegerTrio; import com.boydti.fawe.object.IntegerTrio;
@ -9,10 +8,8 @@ import com.boydti.fawe.util.ReflectionUtils;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.IntTag; import com.sk89q.jnbt.IntTag;
import com.sk89q.jnbt.Tag; import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.world.biome.BiomeTypes; import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
@ -122,7 +119,7 @@ public class MemoryOptimizedClipboard extends FaweClipboard {
if (!hasBiomes()) { if (!hasBiomes()) {
return null; return null;
} }
return BiomeTypes.get(biomes[index]); return BiomeTypes.register(biomes[index]);
} }
@Override @Override

View File

@ -41,6 +41,7 @@ public class FastWorldEditExtent extends AbstractDelegateExtent implements HasFa
this.queue = queue; this.queue = queue;
} }
@Override
public FaweQueue getQueue() { public FaweQueue getQueue() {
return queue; return queue;
} }

View File

@ -48,6 +48,7 @@ public abstract class FaweRegionExtent extends ResettableExtent {
return false; return false;
} }
@Override
public final boolean contains(BlockVector3 p) { public final boolean contains(BlockVector3 p) {
return contains(p.getBlockX(), p.getBlockY(), p.getBlockZ()); return contains(p.getBlockX(), p.getBlockY(), p.getBlockZ());
} }

View File

@ -1,5 +1,7 @@
package com.boydti.fawe.object.extent; package com.boydti.fawe.object.extent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.boydti.fawe.util.ExtentTraverser; import com.boydti.fawe.util.ExtentTraverser;
import com.boydti.fawe.util.ReflectionUtils; import com.boydti.fawe.util.ReflectionUtils;
import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.AbstractDelegateExtent;
@ -7,12 +9,10 @@ import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable; import java.io.Serializable;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import static com.google.common.base.Preconditions.checkNotNull;
public class ResettableExtent extends AbstractDelegateExtent implements Serializable { public class ResettableExtent extends AbstractDelegateExtent implements Serializable {
public ResettableExtent(Extent parent) { public ResettableExtent(Extent parent) {
super(parent); super(parent);
@ -41,7 +41,7 @@ public class ResettableExtent extends AbstractDelegateExtent implements Serializ
return this; return this;
} }
private void writeObject(java.io.ObjectOutputStream stream) throws IOException { private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject(); stream.defaultWriteObject();
Extent extent = getExtent(); Extent extent = getExtent();
boolean next = extent instanceof ResettableExtent; boolean next = extent instanceof ResettableExtent;

View File

@ -34,13 +34,13 @@ public class SolidPlaneMask extends SolidBlockMask implements ResettableMask {
originZ = vector.getBlockZ(); originZ = vector.getBlockZ();
mode = 0; mode = 0;
Extent extent = getExtent(); Extent extent = getExtent();
if (!extent.getBlockType(mutable.setComponents(originX - 1, originY, originZ)).getMaterial().isAir() && !extent.getBlockType(mutable.setComponents(originX + 1, originY, originZ)).getMaterial().isAir()) { if (!extent.getBlock(mutable.setComponents(originX - 1, originY, originZ)).getMaterial().isAir() && !extent.getBlock(mutable.setComponents(originX + 1, originY, originZ)).getMaterial().isAir()) {
mode &= 1; mode &= 1;
} }
if (!extent.getBlockType(mutable.setComponents(originX, originY, originZ - 1)).getMaterial().isAir() && !extent.getBlockType(mutable.setComponents(originX, originY, originZ + 1)).getMaterial().isAir()) { if (!extent.getBlock(mutable.setComponents(originX, originY, originZ - 1)).getMaterial().isAir() && !extent.getBlock(mutable.setComponents(originX, originY, originZ + 1)).getMaterial().isAir()) {
mode &= 4; mode &= 4;
} }
if (!extent.getBlockType(mutable.setComponents(originX, originY - 1, originZ + 1)).getMaterial().isAir() && !extent.getBlockType(mutable.setComponents(originX, originY + 1, originZ + 1)).getMaterial().isAir()) { if (!extent.getBlock(mutable.setComponents(originX, originY - 1, originZ + 1)).getMaterial().isAir() && !extent.getBlock(mutable.setComponents(originX, originY + 1, originZ + 1)).getMaterial().isAir()) {
mode &= 2; mode &= 2;
} }
if (Integer.bitCount(mode) >= 3) { if (Integer.bitCount(mode) >= 3) {

View File

@ -4,16 +4,13 @@ import com.boydti.fawe.Fawe;
import com.boydti.fawe.util.TextureHolder; import com.boydti.fawe.util.TextureHolder;
import com.boydti.fawe.util.TextureUtil; import com.boydti.fawe.util.TextureUtil;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.awt.Color; import java.awt.Color;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream;
public class AverageColorPattern extends AbstractExtentPattern { public class AverageColorPattern extends AbstractExtentPattern {
private transient TextureHolder holder; private transient TextureHolder holder;
@ -36,7 +33,7 @@ public class AverageColorPattern extends AbstractExtentPattern {
@Override @Override
public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException {
BlockType blockType = extent.getBlockType(getPosition); BlockType blockType = extent.getBlock(getPosition).getBlockType();
TextureUtil util = holder.getTextureUtil(); TextureUtil util = holder.getTextureUtil();
int currentColor = util.getColor(blockType); int currentColor = util.getColor(blockType);
if (currentColor == 0) return false; if (currentColor == 0) return false;
@ -46,7 +43,7 @@ public class AverageColorPattern extends AbstractExtentPattern {
return extent.setBlock(setPosition, newBlock.getDefaultState()); return extent.setBlock(setPosition, newBlock.getDefaultState());
} }
private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject(); stream.defaultReadObject();
holder = Fawe.get().getCachedTextureUtil(true, 0, 100); holder = Fawe.get().getCachedTextureUtil(true, 0, 100);
} }

View File

@ -4,15 +4,13 @@ import com.boydti.fawe.Fawe;
import com.boydti.fawe.util.TextureHolder; import com.boydti.fawe.util.TextureHolder;
import com.boydti.fawe.util.TextureUtil; import com.boydti.fawe.util.TextureUtil;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.AbstractPattern;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockType;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream;
public class DesaturatePattern extends AbstractPattern { public class DesaturatePattern extends AbstractPattern {
private transient TextureHolder holder; private transient TextureHolder holder;
@ -27,7 +25,7 @@ public class DesaturatePattern extends AbstractPattern {
@Override @Override
public BaseBlock apply(BlockVector3 position) { public BaseBlock apply(BlockVector3 position) {
BlockType block = extent.getBlockType(position); BlockType block = extent.getBlock(position).getBlockType();
TextureUtil util = holder.getTextureUtil(); TextureUtil util = holder.getTextureUtil();
int color = util.getColor(block); int color = util.getColor(block);
int r = (color >> 16) & 0xFF; int r = (color >> 16) & 0xFF;
@ -44,7 +42,7 @@ public class DesaturatePattern extends AbstractPattern {
@Override @Override
public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException {
BlockType block = extent.getBlockType(getPosition); BlockType block = extent.getBlock(getPosition).getBlockType();
TextureUtil util = holder.getTextureUtil(); TextureUtil util = holder.getTextureUtil();
int color = util.getColor(block); int color = util.getColor(block);
int r = (color >> 16) & 0xFF; int r = (color >> 16) & 0xFF;
@ -66,7 +64,7 @@ public class DesaturatePattern extends AbstractPattern {
return extent.setBlock(setPosition, newBlock.getDefaultState()); return extent.setBlock(setPosition, newBlock.getDefaultState());
} }
private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject(); stream.defaultReadObject();
holder = Fawe.get().getCachedTextureUtil(true, 0, 100); holder = Fawe.get().getCachedTextureUtil(true, 0, 100);
} }

View File

@ -4,16 +4,14 @@ import com.boydti.fawe.Fawe;
import com.boydti.fawe.util.TextureHolder; import com.boydti.fawe.util.TextureHolder;
import com.boydti.fawe.util.TextureUtil; import com.boydti.fawe.util.TextureUtil;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.AbstractPattern;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockType;
import java.awt.Color; import java.awt.Color;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream;
public class SaturatePattern extends AbstractPattern { public class SaturatePattern extends AbstractPattern {
private transient TextureHolder holder; private transient TextureHolder holder;
@ -29,7 +27,7 @@ public class SaturatePattern extends AbstractPattern {
@Override @Override
public BaseBlock apply(BlockVector3 position) { public BaseBlock apply(BlockVector3 position) {
BlockType block = extent.getBlockType(position); BlockType block = extent.getBlock(position).getBlockType();
TextureUtil util = holder.getTextureUtil(); TextureUtil util = holder.getTextureUtil();
int currentColor = util.getColor(block); int currentColor = util.getColor(block);
int newColor = util.multiplyColor(currentColor, color); int newColor = util.multiplyColor(currentColor, color);
@ -38,7 +36,7 @@ public class SaturatePattern extends AbstractPattern {
@Override @Override
public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException { public boolean apply(Extent extent, BlockVector3 setPosition, BlockVector3 getPosition) throws WorldEditException {
BlockType block = extent.getBlockType(getPosition); BlockType block = extent.getBlock(getPosition).getBlockType();
TextureUtil util = holder.getTextureUtil(); TextureUtil util = holder.getTextureUtil();
int currentColor = util.getColor(block); int currentColor = util.getColor(block);
if (currentColor == 0) return false; if (currentColor == 0) return false;
@ -48,7 +46,7 @@ public class SaturatePattern extends AbstractPattern {
return extent.setBlock(setPosition, newBlock.getDefaultState()); return extent.setBlock(setPosition, newBlock.getDefaultState());
} }
private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject(); stream.defaultReadObject();
holder = Fawe.get().getCachedTextureUtil(true, 0, 100); holder = Fawe.get().getCachedTextureUtil(true, 0, 100);
} }

View File

@ -1,20 +1,16 @@
package com.boydti.fawe.object.pattern; package com.boydti.fawe.object.pattern;
import static com.google.common.base.Preconditions.checkNotNull;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.util.TextureUtil; import com.boydti.fawe.util.TextureUtil;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.function.pattern.AbstractPattern; import com.sk89q.worldedit.function.pattern.AbstractPattern;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockType;
import java.io.IOException; import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull;
public class ShadePattern extends AbstractPattern { public class ShadePattern extends AbstractPattern {
private transient TextureUtil util; private transient TextureUtil util;
private final Extent extent; private final Extent extent;
@ -29,7 +25,7 @@ public class ShadePattern extends AbstractPattern {
@Override @Override
public BaseBlock apply(BlockVector3 position) { public BaseBlock apply(BlockVector3 position) {
BlockType block = extent.getBlockType(position); BlockType block = extent.getBlock(position).getBlockType();
return (darken ? util.getDarkerBlock(block) : util.getLighterBlock(block)).getDefaultState().toBaseBlock(); return (darken ? util.getDarkerBlock(block) : util.getLighterBlock(block)).getDefaultState().toBaseBlock();
} }

View File

@ -38,6 +38,7 @@ import javax.annotation.Nullable;
public interface IDelegateFaweQueue extends FaweQueue { public interface IDelegateFaweQueue extends FaweQueue {
@Override
FaweQueue getQueue(); FaweQueue getQueue();
@Override @Override

View File

@ -88,6 +88,7 @@ public class FuzzyRegion extends AbstractRegion {
setMinMax(x, y, z); setMinMax(x, y, z);
} }
@Override
public boolean contains(int x, int y, int z) { public boolean contains(int x, int y, int z) {
return set.contains(x, y, z); return set.contains(x, y, z);
} }

View File

@ -154,8 +154,4 @@ public class FuzzyRegionSelector extends AbstractDelegateExtent implements Regio
return lines; return lines;
} }
@Override
public List<BlockVector3> getVerticies() {
return positions;
}
} }

View File

@ -229,8 +229,4 @@ public class PolyhedralRegionSelector implements RegionSelector, CUIRegion {
} }
} }
@Override
public List<BlockVector3> getVerticies() {
return new ArrayList<>(region.getVertices());
}
} }

View File

@ -176,7 +176,7 @@ public class Schematic {
if (transform != null) { if (transform != null) {
copy.setTransform(transform); copy.setTransform(transform);
} }
copy.setCopyBiomes(!(clipboard instanceof BlockArrayClipboard) || ((BlockArrayClipboard) clipboard).IMP.hasBiomes()); copy.setCopyingBiomes(!(clipboard instanceof BlockArrayClipboard) || ((BlockArrayClipboard) clipboard).IMP.hasBiomes());
if (extent instanceof EditSession) { if (extent instanceof EditSession) {
EditSession editSession = (EditSession) extent; EditSession editSession = (EditSession) extent;
Mask sourceMask = editSession.getSourceMask(); Mask sourceMask = editSession.getSourceMask();

View File

@ -27,12 +27,12 @@ public class Fast2DIterator implements Iterable<BlockVector2> {
} }
public Fast2DIterator(@Nonnull Iterable<? extends BlockVector2> iter, @Nullable HasFaweQueue editSession) { public Fast2DIterator(@Nonnull Iterable<? extends BlockVector2> iter, @Nullable HasFaweQueue editSession) {
this(iter, (FaweQueue) (editSession != null ? editSession.getQueue() : null)); this(iter, editSession != null ? editSession.getQueue() : null);
} }
public Fast2DIterator(@Nonnull Iterable<? extends BlockVector2> iter, @Nullable FaweQueue faweQueue) { public Fast2DIterator(@Nonnull Iterable<? extends BlockVector2> iter, @Nullable FaweQueue faweQueue) {
this.iterable = iter; this.iterable = iter;
this.queue = faweQueue != null && faweQueue instanceof MappedFaweQueue ? (MappedFaweQueue) faweQueue : null; this.queue = faweQueue instanceof MappedFaweQueue ? (MappedFaweQueue) faweQueue : null;
} }
public Iterable<? extends BlockVector2> getIterable() { public Iterable<? extends BlockVector2> getIterable() {

View File

@ -8,7 +8,6 @@ import com.boydti.fawe.util.EditSessionBuilder;
import com.boydti.fawe.util.IOUtil; import com.boydti.fawe.util.IOUtil;
import com.boydti.fawe.util.SetQueue; import com.boydti.fawe.util.SetQueue;
import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.PlotSquared; import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Location;
import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper;
@ -27,7 +26,6 @@ import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.SpongeSchematicWriter; import com.sk89q.worldedit.extent.clipboard.io.SpongeSchematicWriter;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.File; import java.io.File;

View File

@ -20,7 +20,7 @@ import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3;
import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea;
import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; import com.github.intellectualsites.plotsquared.plot.util.SetupUtils;
import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
@CommandDeclaration( @CommandDeclaration(
command = "replaceall", command = "replaceall",
@ -57,7 +57,7 @@ public class ReplaceAll extends Command {
FakePlayer actor = FakePlayer.getConsole(); FakePlayer actor = FakePlayer.getConsole();
String cmd = "/replaceallpattern " + worldName + " " + StringMan.join(args, " "); String cmd = "/replaceallpattern " + worldName + " " + StringMan.join(args, " ");
CommandEvent event = new CommandEvent(actor, cmd); CommandEvent event = new CommandEvent(actor, cmd);
CommandManager.getInstance().handleCommandOnCurrentThread(event); PlatformCommandManager.getInstance().handleCommandOnCurrentThread(event);
TaskManager.IMP.sync(new RunnableVal<Object>() { TaskManager.IMP.sync(new RunnableVal<Object>() {
@Override @Override
public void run(Object value) { public void run(Object value) {

View File

@ -25,7 +25,7 @@ public final class BrushCache {
return item.hasNbtData() ? item.getNbtData() : null; return item.hasNbtData() ? item.getNbtData() : null;
} }
private static final Object getKey(BaseItem item) { private static Object getKey(BaseItem item) {
return item.getNativeItem(); return item.getNativeItem();
} }

View File

@ -21,7 +21,7 @@ package com.boydti.fawe.util;
import com.boydti.fawe.command.AnvilCommands; import com.boydti.fawe.command.AnvilCommands;
import com.boydti.fawe.command.CFICommands; import com.boydti.fawe.command.CFICommands;
import com.sk89q.minecraft.util.commands.Command; import org.enginehub.piston.annotation.Command;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.NestedCommand; import com.sk89q.minecraft.util.commands.NestedCommand;
import com.sk89q.worldedit.command.BiomeCommands; import com.sk89q.worldedit.command.BiomeCommands;

View File

@ -4,21 +4,27 @@ import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweAPI; import com.boydti.fawe.FaweAPI;
import com.boydti.fawe.config.Settings; import com.boydti.fawe.config.Settings;
import com.boydti.fawe.logging.rollback.RollbackOptimizedHistory; import com.boydti.fawe.logging.rollback.RollbackOptimizedHistory;
import com.boydti.fawe.object.*; import com.boydti.fawe.object.FaweLimit;
import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.object.FaweQueue;
import com.boydti.fawe.object.NullChangeSet;
import com.boydti.fawe.object.RegionWrapper;
import com.boydti.fawe.object.changeset.DiskStorageHistory; import com.boydti.fawe.object.changeset.DiskStorageHistory;
import com.boydti.fawe.object.changeset.FaweChangeSet; import com.boydti.fawe.object.changeset.FaweChangeSet;
import com.boydti.fawe.object.changeset.MemoryOptimizedHistory; import com.boydti.fawe.object.changeset.MemoryOptimizedHistory;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.event.extent.EditSessionEvent; import com.sk89q.worldedit.event.extent.EditSessionEvent;
import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.eventbus.EventBus; import com.sk89q.worldedit.util.eventbus.EventBus;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import java.util.UUID;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkNotNull;
public class EditSessionBuilder { public class EditSessionBuilder {
private World world; private World world;
@ -102,8 +108,8 @@ public class EditSessionBuilder {
} }
/** /**
* @param disk If it should be stored on disk * @param disk If it should be stored on disk
* @param uuid The uuid to store it under (if on disk) * @param uuid The uuid to store it under (if on disk)
* @param compression Compression level (0-9) * @param compression Compression level (0-9)
* @return * @return
*/ */
@ -180,17 +186,15 @@ public class EditSessionBuilder {
return this; return this;
} }
public EditSessionBuilder eventBus(@Nullable EventBus eventBus) {
this.eventBus = eventBus;
return this;
}
public EditSessionBuilder event(@Nullable EditSessionEvent event) { public EditSessionBuilder event(@Nullable EditSessionEvent event) {
this.event = event; this.event = event;
return this; return this;
} }
public EditSession build() { public EditSession build() {
return new EditSession(worldName, world, queue, player, limit, changeSet, allowedRegions, autoQueue, fastmode, checkMemory, combineStages, blockBag, eventBus, event); if (eventBus == null) {
eventBus = WorldEdit.getInstance().getEventBus();
}
return new EditSession(worldName, world, queue, player, limit, changeSet, allowedRegions, autoQueue, fastmode, checkMemory, combineStages, blockBag, eventBus, event);
} }
} }

View File

@ -1,5 +1,7 @@
package com.boydti.fawe.util; package com.boydti.fawe.util;
import static java.lang.System.arraycopy;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.BBC;
import com.boydti.fawe.config.Settings; import com.boydti.fawe.config.Settings;
@ -12,7 +14,6 @@ import com.boydti.fawe.object.RunnableVal2;
import com.boydti.fawe.object.changeset.CPUOptimizedChangeSet; import com.boydti.fawe.object.changeset.CPUOptimizedChangeSet;
import com.boydti.fawe.object.changeset.FaweStreamChangeSet; import com.boydti.fawe.object.changeset.FaweStreamChangeSet;
import com.boydti.fawe.object.io.AbstractDelegateOutputStream; import com.boydti.fawe.object.io.AbstractDelegateOutputStream;
import com.github.luben.zstd.ZstdInputStream; import com.github.luben.zstd.ZstdInputStream;
import com.github.luben.zstd.ZstdOutputStream; import com.github.luben.zstd.ZstdOutputStream;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
@ -27,20 +28,19 @@ import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormats;
import com.sk89q.worldedit.history.changeset.ChangeSet; import com.sk89q.worldedit.history.changeset.ChangeSet;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import static java.lang.System.arraycopy; import java.awt.Graphics2D;
import net.jpountz.lz4.LZ4BlockInputStream;
import net.jpountz.lz4.LZ4BlockOutputStream;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;
import net.jpountz.lz4.LZ4InputStream;
import net.jpountz.lz4.LZ4Utils;
import javax.annotation.Nullable;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.*; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@ -77,6 +77,15 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater; import java.util.zip.Inflater;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import javax.annotation.Nullable;
import javax.imageio.ImageIO;
import net.jpountz.lz4.LZ4BlockInputStream;
import net.jpountz.lz4.LZ4BlockOutputStream;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;
import net.jpountz.lz4.LZ4InputStream;
import net.jpountz.lz4.LZ4Utils;
public class MainUtil { public class MainUtil {
/* /*
@ -853,33 +862,4 @@ public class MainUtil {
} }
} }
public static void warnDeprecated(Class... alternatives) {
StackTraceElement[] stacktrace = new RuntimeException().getStackTrace();
if (stacktrace.length > 1) {
for (int i = 1; i < stacktrace.length; i++) {
StackTraceElement stack = stacktrace[i];
String s = stack.toString();
if (s.startsWith("com.sk89q")) {
continue;
}
try {
StackTraceElement creatorElement = stacktrace[1];
String className = creatorElement.getClassName();
Class clazz = Class.forName(className);
String creator = clazz.getSimpleName();
String packageName = clazz.getPackage().getName();
StackTraceElement deprecatedElement = stack;
String myName = Class.forName(deprecatedElement.getClassName()).getSimpleName();
Fawe.debug("@" + creator + " used by " + myName + "." + deprecatedElement.getMethodName() + "():" + deprecatedElement.getLineNumber() + " is deprecated.");
Fawe.debug(" - Alternatives: " + StringMan.getString(alternatives));
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
break;
}
}
}
}
} }

View File

@ -171,16 +171,7 @@ public class SetQueue {
e.printStackTrace(); e.printStackTrace();
} }
if (pool.getQueuedSubmissionCount() != 0 || pool.getRunningThreadCount() != 0 || pool.getQueuedTaskCount() != 0) { if (pool.getQueuedSubmissionCount() != 0 || pool.getRunningThreadCount() != 0 || pool.getQueuedTaskCount() != 0) {
// if (Fawe.get().isJava8()) pool.awaitQuiescence(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
{
pool.awaitQuiescence(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
// else {
// pool.shutdown();
// pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// pool = new ForkJoinPool();
// completer = new ExecutorCompletionService(pool);
// }
} }
queue.endSet(parallel); queue.endSet(parallel);
} catch (Throwable e) { } catch (Throwable e) {

View File

@ -3,8 +3,9 @@ package com.boydti.fawe.util.chat;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.BBC;
import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FawePlayer;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import java.util.Objects; import java.util.Objects;
public class Message { public class Message {
@ -75,7 +76,7 @@ public class Message {
} }
public Message command(String command) { public Message command(String command) {
Fawe.get().getChatManager().command(this, (WorldEdit.getInstance().getConfiguration().noDoubleSlash ? "" : "/") + command); Fawe.get().getChatManager().command(this, ("/") + command);
return this; return this;
} }

View File

@ -6,7 +6,7 @@ import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.StringMan; import com.boydti.fawe.util.StringMan;
import com.sk89q.minecraft.util.commands.CommandLocals; import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.minecraft.util.commands.Link; import com.sk89q.minecraft.util.commands.Link;
import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.util.command.CommandCallable; import com.sk89q.worldedit.util.command.CommandCallable;
import com.sk89q.worldedit.util.command.CommandMapping; import com.sk89q.worldedit.util.command.CommandMapping;
import com.sk89q.worldedit.util.command.Description; import com.sk89q.worldedit.util.command.Description;
@ -57,7 +57,7 @@ public class UsageMessage extends Message {
String prefix = !commandString.isEmpty() ? commandString + " " : ""; String prefix = !commandString.isEmpty() ? commandString + " " : "";
List<CommandMapping> list = new ArrayList<>(dispatcher.getCommands()); List<CommandMapping> list = new ArrayList<>(dispatcher.getCommands());
list.sort(new PrimaryAliasComparator(CommandManager.COMMAND_CLEAN_PATTERN)); list.sort(new PrimaryAliasComparator(PlatformCommandManager.COMMAND_CLEAN_PATTERN));
for (CommandMapping mapping : list) { for (CommandMapping mapping : list) {
boolean perm = locals == null || mapping.getCallable().testPermission(locals); boolean perm = locals == null || mapping.getCallable().testPermission(locals);

View File

@ -87,8 +87,9 @@ public class SchemSync implements Runnable {
UtilityCommands.allFiles(dir.listFiles(), true, new Consumer<File>() { UtilityCommands.allFiles(dir.listFiles(), true, new Consumer<File>() {
@Override @Override
public void accept(File file) { public void accept(File file) {
String path = dir.toURI().relativize(file.toURI()).getPath();
try { try {
String path = dir.toURI()
.relativize(file.toURI()).getPath();
out.writeUTF(path); out.writeUTF(path);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -23,6 +23,7 @@ import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.util.HandSide;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.TargetBlock; import com.sk89q.worldedit.util.TargetBlock;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypes;
@ -120,6 +121,10 @@ public class PlayerWrapper extends AbstractPlayerActor {
parent.printError(msg); parent.printError(msg);
} }
@Override public void print(Component component) {
parent.print(component);
}
@Override @Override
public String[] getGroups() { public String[] getGroups() {
return parent.getGroups(); return parent.getGroups();

View File

@ -181,6 +181,18 @@ public class CompoundTagBuilder {
return put(key, new StringTag(value)); return put(key, new StringTag(value));
} }
/**
* Remove the given key from the compound tag. Does nothing if the key doesn't exist.
*
* @param key the key
* @return this object
*/
public CompoundTagBuilder remove(String key) {
checkNotNull(key);
entries.remove(key);
return this;
}
/** /**
* Put all the entries from the given map into this map. * Put all the entries from the given map into this map.
* *

View File

@ -1,10 +1,9 @@
package com.sk89q.jnbt; package com.sk89q.jnbt;
import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import net.jpountz.lz4.LZ4BlockInputStream;
public abstract class CompressedCompoundTag<T> extends CompoundTag { public abstract class CompressedCompoundTag<T> extends CompoundTag {
private T in; private T in;
@ -20,7 +19,7 @@ public abstract class CompressedCompoundTag<T> extends CompoundTag {
return super.getValue(); return super.getValue();
} }
public abstract DataInputStream adapt(T src) throws IOException; public abstract LZ4BlockInputStream adapt(T src) throws IOException;
public T getSource() { public T getSource() {
return in; return in;

View File

@ -2,15 +2,12 @@ package com.sk89q.jnbt;
import com.boydti.fawe.object.io.FastByteArrayOutputStream; import com.boydti.fawe.object.io.FastByteArrayOutputStream;
import com.boydti.fawe.object.io.FastByteArraysInputStream; import com.boydti.fawe.object.io.FastByteArraysInputStream;
import com.boydti.fawe.object.io.PGZIPOutputStream;
import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.SpongeSchematicWriter; import com.sk89q.worldedit.extent.clipboard.io.SpongeSchematicWriter;
import net.jpountz.lz4.LZ4BlockInputStream; import net.jpountz.lz4.LZ4BlockInputStream;
import net.jpountz.lz4.LZ4BlockOutputStream; import net.jpountz.lz4.LZ4BlockOutputStream;
import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.zip.GZIPInputStream;
public class CompressedSchematicTag extends CompressedCompoundTag<Clipboard> { public class CompressedSchematicTag extends CompressedCompoundTag<Clipboard> {
public CompressedSchematicTag(Clipboard holder) { public CompressedSchematicTag(Clipboard holder) {
@ -18,7 +15,7 @@ public class CompressedSchematicTag extends CompressedCompoundTag<Clipboard> {
} }
@Override @Override
public DataInputStream adapt(Clipboard src) throws IOException { public LZ4BlockInputStream adapt(Clipboard src) throws IOException {
FastByteArrayOutputStream blocksOut = new FastByteArrayOutputStream(); FastByteArrayOutputStream blocksOut = new FastByteArrayOutputStream();
try (LZ4BlockOutputStream lz4out = new LZ4BlockOutputStream(blocksOut)) { try (LZ4BlockOutputStream lz4out = new LZ4BlockOutputStream(blocksOut)) {
NBTOutputStream nbtOut = new NBTOutputStream(lz4out); NBTOutputStream nbtOut = new NBTOutputStream(lz4out);
@ -27,6 +24,6 @@ public class CompressedSchematicTag extends CompressedCompoundTag<Clipboard> {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
FastByteArraysInputStream in = new FastByteArraysInputStream(blocksOut.toByteArrays()); FastByteArraysInputStream in = new FastByteArraysInputStream(blocksOut.toByteArrays());
return new DataInputStream(new LZ4BlockInputStream(in)); return new LZ4BlockInputStream(in);
} }
} }

View File

@ -21,6 +21,8 @@ package com.sk89q.jnbt;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Locale;
/** /**
* The {@code TAG_Int_Array} tag. * The {@code TAG_Int_Array} tag.
*/ */
@ -48,7 +50,7 @@ public final class IntArrayTag extends Tag {
public String toString() { public String toString() {
StringBuilder hex = new StringBuilder(); StringBuilder hex = new StringBuilder();
for (int b : value) { for (int b : value) {
String hexDigits = Integer.toHexString(b).toUpperCase(); String hexDigits = Integer.toHexString(b).toUpperCase(Locale.ROOT);
if (hexDigits.length() == 1) { if (hexDigits.length() == 1) {
hex.append("0"); hex.append("0");
} }

View File

@ -21,6 +21,8 @@ package com.sk89q.jnbt;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Locale;
/** /**
* The {@code TAG_Long_Array} tag. * The {@code TAG_Long_Array} tag.
*/ */
@ -48,7 +50,7 @@ public class LongArrayTag extends Tag {
public String toString() { public String toString() {
StringBuilder hex = new StringBuilder(); StringBuilder hex = new StringBuilder();
for (long b : value) { for (long b : value) {
String hexDigits = Long.toHexString(b).toUpperCase(); String hexDigits = Long.toHexString(b).toUpperCase(Locale.ROOT);
if (hexDigits.length() == 1) { if (hexDigits.length() == 1) {
hex.append("0"); hex.append("0");
} }

View File

@ -152,39 +152,21 @@ public final class NBTInputStream implements Closeable {
if (reader instanceof NBTStreamer.ByteReader) { if (reader instanceof NBTStreamer.ByteReader) {
NBTStreamer.ByteReader byteReader = (NBTStreamer.ByteReader) reader; NBTStreamer.ByteReader byteReader = (NBTStreamer.ByteReader) reader;
int i = 0; int i = 0;
if (is instanceof InputStream) { DataInputStream dis = is;
DataInputStream dis = is; if (length > 1024) {
if (length > 1024) { if (buf == null) {
if (buf == null) { buf = new byte[1024];
buf = new byte[1024]; }
} int left = length;
int left = length; for (; left > 1024; left -= 1024) {
for (; left > 1024; left -= 1024) { dis.readFully(buf);
dis.readFully(buf); for (byte b : buf) {
for (byte b : buf) { byteReader.run(i++, b & 0xFF);
byteReader.run(i++, b & 0xFF);
}
} }
} }
for (; i < length; i++) { }
byteReader.run(i, dis.read()); for (; i < length; i++) {
} byteReader.run(i, dis.read());
} else {
if (length > 1024) {
if (buf == null) {
buf = new byte[1024];
}
int left = length;
for (; left > 1024; left -= 1024) {
is.readFully(buf);
for (byte b : buf) {
byteReader.run(i++, b & 0xFF);
}
}
}
for (; i < length; i++) {
byteReader.run(i, is.readByte() & 0xFF);
}
} }
} else if (reader instanceof NBTStreamer.LazyReader) { } else if (reader instanceof NBTStreamer.LazyReader) {
reader.accept(length, is); reader.accept(length, is);
@ -410,88 +392,6 @@ public final class NBTInputStream implements Closeable {
} }
} }
public Object readDataPayload(int type, int depth) throws IOException {
switch (type) {
case NBTConstants.TYPE_END:
if (depth == 0) {
throw new IOException(
"TAG_End found without a TAG_Compound/TAG_List tag preceding it.");
} else {
return null;
}
case NBTConstants.TYPE_BYTE:
return is.readByte();
case NBTConstants.TYPE_SHORT:
return is.readShort();
case NBTConstants.TYPE_INT:
return is.readInt();
case NBTConstants.TYPE_LONG:
return is.readLong();
case NBTConstants.TYPE_FLOAT:
return is.readFloat();
case NBTConstants.TYPE_DOUBLE:
return is.readDouble();
case NBTConstants.TYPE_BYTE_ARRAY:
int length = is.readInt();
byte[] bytes = new byte[length];
is.readFully(bytes);
return bytes;
case NBTConstants.TYPE_STRING:
length = is.readShort();
bytes = new byte[length];
is.readFully(bytes);
return new String(bytes, NBTConstants.CHARSET);
case NBTConstants.TYPE_LIST:
int childType = is.readByte();
if (childType == NBTConstants.TYPE_LIST) {
childType = NBTConstants.TYPE_COMPOUND;
}
length = is.readInt();
ArrayList<Object> list = new ArrayList<>();
for (int i = 0; i < length; ++i) {
Object obj = readDataPayload(childType, depth + 1);
if (obj == null) {
throw new IOException("TAG_End not permitted in a list.");
}
list.add(obj);
}
return list;
case NBTConstants.TYPE_COMPOUND:
Map<String, Object> map = new HashMap<>();
while (true) {
int newType = is.readByte();
String name = readNamedTagName(newType);
Object data = readDataPayload(newType, depth + 1);
if (data == null) {
break;
} else {
map.put(name, data);
}
}
return map;
case NBTConstants.TYPE_INT_ARRAY: {
length = is.readInt();
int[] data = new int[length];
for (int i = 0; i < length; i++) {
data[i] = is.readInt();
}
return data;
}
case NBTConstants.TYPE_LONG_ARRAY: {
length = is.readInt();
long[] data = new long[length];
for (int i = 0; i < length; i++) {
data[i] = is.readLong();
}
return data;
}
default:
throw new IOException("Invalid tag type: " + type + ".");
}
}
/** /**
* Reads the payload of a tag given the type. * Reads the payload of a tag given the type.
* *
@ -560,22 +460,20 @@ public final class NBTInputStream implements Closeable {
} }
return new CompoundTag(tagMap); return new CompoundTag(tagMap);
case NBTConstants.TYPE_INT_ARRAY: { case NBTConstants.TYPE_INT_ARRAY:
length = is.readInt(); length = is.readInt();
int[] data = new int[length]; int[] data = new int[length];
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
data[i] = is.readInt(); data[i] = is.readInt();
} }
return new IntArrayTag(data); return new IntArrayTag(data);
} case NBTConstants.TYPE_LONG_ARRAY:
case NBTConstants.TYPE_LONG_ARRAY: {
length = is.readInt(); length = is.readInt();
long[] longData = new long[length]; long[] longData = new long[length];
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
longData[i] = is.readLong(); longData[i] = is.readLong();
} }
return new LongArrayTag(longData); return new LongArrayTag(longData);
}
default: default:
throw new IOException("Invalid tag type: " + type + "."); throw new IOException("Invalid tag type: " + type + ".");
} }
@ -583,13 +481,7 @@ public final class NBTInputStream implements Closeable {
@Override @Override
public void close() throws IOException { public void close() throws IOException {
if (is instanceof AutoCloseable) { is.close();
try {
((AutoCloseable) is).close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} }
} }

View File

@ -19,8 +19,6 @@
package com.sk89q.jnbt; package com.sk89q.jnbt;
import com.boydti.fawe.object.io.LittleEndianOutputStream;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import java.io.Closeable; import java.io.Closeable;
@ -45,7 +43,7 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
/** /**
* The output stream. * The output stream.
*/ */
private DataOutput os; private final DataOutputStream os;
/** /**
* Creates a new {@code NBTOutputStream}, which will write data to the * Creates a new {@code NBTOutputStream}, which will write data to the
@ -60,23 +58,10 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
this.os = new DataOutputStream(os); this.os = new DataOutputStream(os);
} }
public NBTOutputStream(DataOutput os) throws IOException {
this.os = os;
}
public DataOutput getOutputStream() { public DataOutput getOutputStream() {
return os; return os;
} }
/**
* Use a little endian output stream
*/
public void setLittleEndian() {
if (!(os instanceof LittleEndianOutputStream)) {
this.os = new LittleEndianOutputStream((OutputStream) os);
}
}
/** /**
* Writes a tag. * Writes a tag.
* *
@ -159,7 +144,7 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
writeNamedEmptyList(name, NBTConstants.TYPE_COMPOUND); writeNamedEmptyList(name, NBTConstants.TYPE_COMPOUND);
} }
public void writeNamedEmptyList(String name, int type) throws IOException { private void writeNamedEmptyList(String name, int type) throws IOException {
writeNamedTagName(name, NBTConstants.TYPE_LIST); writeNamedTagName(name, NBTConstants.TYPE_LIST);
os.writeByte(type); os.writeByte(type);
os.writeInt(0); os.writeInt(0);
@ -420,7 +405,7 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
@Override @Override
public void close() throws IOException { public void close() throws IOException {
if (os instanceof Closeable) ((Closeable) os).close(); os.close();
} }
@Override @Override
@ -500,6 +485,6 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
*/ */
@Override @Override
public void flush() throws IOException { public void flush() throws IOException {
if (os instanceof Flushable) ((Flushable) os).flush(); ((Flushable) os).flush();
} }
} }

View File

@ -30,6 +30,7 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -60,6 +61,7 @@ import java.util.Set;
* @param <T> command sender class * @param <T> command sender class
*/ */
@SuppressWarnings("ProtectedField") @SuppressWarnings("ProtectedField")
@Deprecated
public abstract class CommandsManager<T> { public abstract class CommandsManager<T> {
protected static final Logger logger = protected static final Logger logger =
@ -253,7 +255,7 @@ public abstract class CommandsManager<T> {
* @return true if the command exists * @return true if the command exists
*/ */
public boolean hasCommand(String command) { public boolean hasCommand(String command) {
return commands.get(null).containsKey(command.toLowerCase()); return commands.get(null).containsKey(command.toLowerCase(Locale.ROOT));
} }
/** /**
@ -433,7 +435,7 @@ public abstract class CommandsManager<T> {
String cmdName = args[level]; String cmdName = args[level];
Map<String, Method> map = commands.get(parent); Map<String, Method> map = commands.get(parent);
Method method = map.get(cmdName.toLowerCase()); Method method = map.get(cmdName.toLowerCase(Locale.ROOT));
if (method == null) { if (method == null) {
if (parent == null) { // Root if (parent == null) { // Root

View File

@ -0,0 +1,24 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* 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 <http://www.gnu.org/licenses/>.
*/
/**
* This package contains the old command system. It is no longer in use. Please switch
* to Piston, Intake, ACF, or similar systems.
*/
package com.sk89q.minecraft.util.commands;

View File

@ -310,7 +310,7 @@ public final class StringUtil {
} }
public static List<String> parseListInQuotes(String[] input, char delimiter, char quoteOpen, char quoteClose, boolean appendLeftover) { public static List<String> parseListInQuotes(String[] input, char delimiter, char quoteOpen, char quoteClose, boolean appendLeftover) {
List<String> parsableBlocks = new ArrayList<>(); List<String> parsableBlocks = new ArrayList<>();
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
for (String split : input) { for (String split : input) {
if (split.indexOf(quoteOpen) != -1 && split.indexOf(quoteClose) == -1) { if (split.indexOf(quoteOpen) != -1 && split.indexOf(quoteClose) == -1) {

View File

@ -19,6 +19,12 @@
package com.sk89q.worldedit; package com.sk89q.worldedit;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.worldedit.regions.Regions.asFlatRegion;
import static com.sk89q.worldedit.regions.Regions.maximumBlockY;
import static com.sk89q.worldedit.regions.Regions.minimumBlockY;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweAPI; import com.boydti.fawe.FaweAPI;
import com.boydti.fawe.config.BBC; import com.boydti.fawe.config.BBC;
@ -26,7 +32,6 @@ import com.boydti.fawe.config.Settings;
import com.boydti.fawe.example.MappedFaweQueue; import com.boydti.fawe.example.MappedFaweQueue;
import com.boydti.fawe.jnbt.anvil.MCAQueue; import com.boydti.fawe.jnbt.anvil.MCAQueue;
import com.boydti.fawe.jnbt.anvil.MCAWorld; import com.boydti.fawe.jnbt.anvil.MCAWorld;
import com.boydti.fawe.logging.LoggingChangeSet;
import com.boydti.fawe.logging.rollback.RollbackOptimizedHistory; import com.boydti.fawe.logging.rollback.RollbackOptimizedHistory;
import com.boydti.fawe.object.FaweLimit; import com.boydti.fawe.object.FaweLimit;
import com.boydti.fawe.object.FawePlayer; import com.boydti.fawe.object.FawePlayer;
@ -44,7 +49,17 @@ import com.boydti.fawe.object.changeset.FaweChangeSet;
import com.boydti.fawe.object.changeset.MemoryOptimizedHistory; import com.boydti.fawe.object.changeset.MemoryOptimizedHistory;
import com.boydti.fawe.object.collection.LocalBlockVectorSet; import com.boydti.fawe.object.collection.LocalBlockVectorSet;
import com.boydti.fawe.object.exception.FaweException; import com.boydti.fawe.object.exception.FaweException;
import com.boydti.fawe.object.extent.*; import com.boydti.fawe.object.extent.FastWorldEditExtent;
import com.boydti.fawe.object.extent.FaweRegionExtent;
import com.boydti.fawe.object.extent.HeightBoundExtent;
import com.boydti.fawe.object.extent.MultiRegionExtent;
import com.boydti.fawe.object.extent.NullExtent;
import com.boydti.fawe.object.extent.ProcessedWEExtent;
import com.boydti.fawe.object.extent.ResettableExtent;
import com.boydti.fawe.object.extent.SingleRegionExtent;
import com.boydti.fawe.object.extent.SlowExtent;
import com.boydti.fawe.object.extent.SourceMaskExtent;
import com.boydti.fawe.object.extent.StripNBTExtent;
import com.boydti.fawe.object.function.SurfaceRegionFunction; import com.boydti.fawe.object.function.SurfaceRegionFunction;
import com.boydti.fawe.object.mask.ResettableMask; import com.boydti.fawe.object.mask.ResettableMask;
import com.boydti.fawe.object.pattern.ExistingPattern; import com.boydti.fawe.object.pattern.ExistingPattern;
@ -58,9 +73,6 @@ import com.boydti.fawe.util.Perm;
import com.boydti.fawe.util.SetQueue; import com.boydti.fawe.util.SetQueue;
import com.boydti.fawe.util.TaskManager; import com.boydti.fawe.util.TaskManager;
import com.boydti.fawe.wrappers.WorldWrapper; import com.boydti.fawe.wrappers.WorldWrapper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.blocks.BaseItemStack;
@ -81,7 +93,16 @@ import com.sk89q.worldedit.function.block.BlockReplace;
import com.sk89q.worldedit.function.block.Naturalizer; import com.sk89q.worldedit.function.block.Naturalizer;
import com.sk89q.worldedit.function.generator.ForestGenerator; import com.sk89q.worldedit.function.generator.ForestGenerator;
import com.sk89q.worldedit.function.generator.GardenPatchGenerator; import com.sk89q.worldedit.function.generator.GardenPatchGenerator;
import com.sk89q.worldedit.function.mask.*; import com.sk89q.worldedit.function.mask.BlockMaskBuilder;
import com.sk89q.worldedit.function.mask.BlockTypeMask;
import com.sk89q.worldedit.function.mask.BoundedHeightMask;
import com.sk89q.worldedit.function.mask.ExistingBlockMask;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.mask.MaskIntersection;
import com.sk89q.worldedit.function.mask.MaskUnion;
import com.sk89q.worldedit.function.mask.Masks;
import com.sk89q.worldedit.function.mask.NoiseFilter2D;
import com.sk89q.worldedit.function.mask.RegionMask;
import com.sk89q.worldedit.function.operation.ChangeSetExecutor; import com.sk89q.worldedit.function.operation.ChangeSetExecutor;
import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.ForwardExtentCopy;
import com.sk89q.worldedit.function.operation.Operation; import com.sk89q.worldedit.function.operation.Operation;
@ -122,15 +143,13 @@ import com.sk89q.worldedit.regions.EllipsoidRegion;
import com.sk89q.worldedit.regions.FlatRegion; import com.sk89q.worldedit.regions.FlatRegion;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.Regions; import com.sk89q.worldedit.regions.Regions;
import static com.sk89q.worldedit.regions.Regions.asFlatRegion;
import static com.sk89q.worldedit.regions.Regions.maximumBlockY;
import static com.sk89q.worldedit.regions.Regions.minimumBlockY;
import com.sk89q.worldedit.regions.shape.ArbitraryBiomeShape; import com.sk89q.worldedit.regions.shape.ArbitraryBiomeShape;
import com.sk89q.worldedit.regions.shape.ArbitraryShape; import com.sk89q.worldedit.regions.shape.ArbitraryShape;
import com.sk89q.worldedit.regions.shape.RegionShape; import com.sk89q.worldedit.regions.shape.RegionShape;
import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment; import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment;
import com.sk89q.worldedit.util.Countable; import com.sk89q.worldedit.util.Countable;
import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.util.eventbus.EventBus; import com.sk89q.worldedit.util.eventbus.EventBus;
import com.sk89q.worldedit.world.SimpleWorld; import com.sk89q.worldedit.world.SimpleWorld;
@ -144,11 +163,7 @@ import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.weather.WeatherType; import com.sk89q.worldedit.world.weather.WeatherType;
import org.slf4j.Logger; import java.nio.file.Path;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -156,6 +171,11 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* An {@link Extent} that handles history, {@link BlockBag}s, change limits, * An {@link Extent} that handles history, {@link BlockBag}s, change limits,
@ -229,20 +249,17 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
public static final UUID CONSOLE = UUID.fromString("1-1-3-3-7"); public static final UUID CONSOLE = UUID.fromString("1-1-3-3-7");
@Deprecated @Deprecated
public EditSession(@Nonnull World world, @Nullable FaweQueue queue, @Nullable FawePlayer player, @Nullable FaweLimit limit, @Nullable FaweChangeSet changeSet, @Nullable RegionWrapper[] allowedRegions, @Nullable Boolean autoQueue, @Nullable Boolean fastmode, @Nullable Boolean checkMemory, @Nullable Boolean combineStages, @Nullable BlockBag blockBag, @Nullable EventBus bus, @Nullable EditSessionEvent event) { public EditSession(@Nonnull World world, @Nullable FaweQueue queue, @Nullable FawePlayer player, @Nullable FaweLimit limit, @Nullable FaweChangeSet changeSet, @Nullable RegionWrapper[] allowedRegions, @Nullable Boolean autoQueue, @Nullable Boolean fastmode, @Nullable Boolean checkMemory, @Nullable Boolean combineStages, @Nullable BlockBag blockBag, @NotNull EventBus bus, @Nullable EditSessionEvent event) {
this(null, world, queue, player, limit, changeSet, allowedRegions, autoQueue, fastmode, checkMemory, combineStages, blockBag, bus, event); this(null, world, queue, player, limit, changeSet, allowedRegions, autoQueue, fastmode, checkMemory, combineStages, blockBag, bus, event);
} }
public EditSession(@Nullable String worldName, @Nullable World world, @Nullable FaweQueue queue, @Nullable FawePlayer player, @Nullable FaweLimit limit, @Nullable FaweChangeSet changeSet, @Nullable Region[] allowedRegions, @Nullable Boolean autoQueue, @Nullable Boolean fastmode, @Nullable Boolean checkMemory, @Nullable Boolean combineStages, @Nullable BlockBag blockBag, @Nullable EventBus bus, @Nullable EditSessionEvent event) { public EditSession(@Nullable String worldName, @Nullable World world, @Nullable FaweQueue queue, @Nullable FawePlayer player, @Nullable FaweLimit limit, @Nullable FaweChangeSet changeSet, @Nullable Region[] allowedRegions, @Nullable Boolean autoQueue, @Nullable Boolean fastmode, @Nullable Boolean checkMemory, @Nullable Boolean combineStages, @Nullable BlockBag blockBag, @NotNull EventBus bus, @Nullable EditSessionEvent event) {
super(world); super(world);
this.worldName = worldName == null ? world == null ? queue == null ? "" : queue.getWorldName() : world.getName() : worldName; this.worldName = worldName == null ? world == null ? queue == null ? "" : queue.getWorldName() : world.getName() : worldName;
if (world == null && this.worldName != null) world = FaweAPI.getWorld(this.worldName); if (world == null && this.worldName != null) world = FaweAPI.getWorld(this.worldName);
this.world = world; this.world = world;
if (bus == null) {
bus = WorldEdit.getInstance().getEventBus();
}
if (event == null) { if (event == null) {
event = new EditSessionEvent(world, player == null ? null : (player.getPlayer()), -1, null); event = new EditSessionEvent(world, player == null ? null : (player.getPlayer()), -1, null);
} }
@ -344,13 +361,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
if (this.limit.SPEED_REDUCTION > 0) { if (this.limit.SPEED_REDUCTION > 0) {
this.bypassHistory = new SlowExtent(this.bypassHistory, this.limit.SPEED_REDUCTION); this.bypassHistory = new SlowExtent(this.bypassHistory, this.limit.SPEED_REDUCTION);
} }
if (changeSet instanceof NullChangeSet && Fawe.imp().getBlocksHubApi() != null && player != null) {
changeSet = LoggingChangeSet.wrap(player, changeSet);
}
if (!(changeSet instanceof NullChangeSet)) { if (!(changeSet instanceof NullChangeSet)) {
if (!(changeSet instanceof LoggingChangeSet) && player != null && Fawe.imp().getBlocksHubApi() != null) {
changeSet = LoggingChangeSet.wrap(player, changeSet);
}
if (this.blockBag != null) { if (this.blockBag != null) {
changeSet = new BlockBagChangeSet(changeSet, blockBag, limit.INVENTORY_MODE == 1); changeSet = new BlockBagChangeSet(changeSet, blockBag, limit.INVENTORY_MODE == 1);
} }
@ -416,7 +427,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
public void resetLimit() { public void resetLimit() {
this.limit.set(this.originalLimit); this.limit.set(this.originalLimit);
ExtentTraverser<ProcessedWEExtent> find = new ExtentTraverser(extent).find(ProcessedWEExtent.class); ExtentTraverser<ProcessedWEExtent> find = new ExtentTraverser<>(extent).find(ProcessedWEExtent.class);
if (find != null && find.get() != null) { if (find != null && find.get() != null) {
find.get().setLimit(this.limit); find.get().setLimit(this.limit);
} }
@ -455,7 +466,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return FaweRegionExtent (may be null) * @return FaweRegionExtent (may be null)
*/ */
public FaweRegionExtent getRegionExtent() { public FaweRegionExtent getRegionExtent() {
ExtentTraverser<FaweRegionExtent> traverser = new ExtentTraverser(this.extent).find(FaweRegionExtent.class); ExtentTraverser<FaweRegionExtent> traverser = new ExtentTraverser<>(this.extent).find(FaweRegionExtent.class);
return traverser == null ? null : traverser.get(); return traverser == null ? null : traverser.get();
} }
@ -467,6 +478,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return bypassHistory; return bypassHistory;
} }
@Override
public Extent getExtent() { public Extent getExtent() {
return extent; return extent;
} }
@ -532,27 +544,17 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} }
} }
/**
* Send a debug message to the Actor responsible for this EditSession (or Console)
*
* @param message
* @param args
*/
public void debug(BBC message, Object... args) {
message.send(player, args);
}
/** /**
* Get the FaweQueue this EditSession uses to queue the changes<br> * Get the FaweQueue this EditSession uses to queue the changes<br>
* - Note: All implementation queues for FAWE are instances of NMSMappedFaweQueue * - Note: All implementation queues for FAWE are instances of NMSMappedFaweQueue
* *
* @return * @return
*/ */
@Override
public FaweQueue getQueue() { public FaweQueue getQueue() {
return queue; return queue;
} }
@Deprecated
private AbstractDelegateExtent wrapExtent(Extent extent, EventBus eventBus, EditSessionEvent event, Stage stage) { private AbstractDelegateExtent wrapExtent(Extent extent, EventBus eventBus, EditSessionEvent event, Stage stage) {
event = event.clone(stage); event = event.clone(stage);
event.setExtent(extent); event.setExtent(extent);
@ -739,7 +741,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return mask, may be null * @return mask, may be null
*/ */
public Mask getMask() { public Mask getMask() {
ExtentTraverser<MaskingExtent> maskingExtent = new ExtentTraverser(this.extent).find(MaskingExtent.class); ExtentTraverser<MaskingExtent> maskingExtent = new ExtentTraverser<>(this.extent).find(MaskingExtent.class);
return maskingExtent != null ? maskingExtent.get().getMask() : null; return maskingExtent != null ? maskingExtent.get().getMask() : null;
} }
@ -749,18 +751,18 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return mask, may be null * @return mask, may be null
*/ */
public Mask getSourceMask() { public Mask getSourceMask() {
ExtentTraverser<SourceMaskExtent> maskingExtent = new ExtentTraverser(this.extent).find(SourceMaskExtent.class); ExtentTraverser<SourceMaskExtent> maskingExtent = new ExtentTraverser<>(this.extent).find(SourceMaskExtent.class);
return maskingExtent != null ? maskingExtent.get().getMask() : null; return maskingExtent != null ? maskingExtent.get().getMask() : null;
} }
public void addTransform(ResettableExtent transform) { public void addTransform(ResettableExtent transform) {
wrapped = true; wrapped = true;
if (transform == null) { if (transform == null) {
ExtentTraverser<AbstractDelegateExtent> traverser = new ExtentTraverser(this.extent).find(ResettableExtent.class); ExtentTraverser traverser = new ExtentTraverser(this.extent).find(ResettableExtent.class);
AbstractDelegateExtent next = extent; AbstractDelegateExtent next = extent;
while (traverser != null && traverser.get() instanceof ResettableExtent) { while (traverser != null && traverser.get() instanceof ResettableExtent) {
traverser = traverser.next(); traverser = traverser.next();
next = traverser.get(); next = (AbstractDelegateExtent) traverser.get();
} }
this.extent = next; this.extent = next;
return; return;
@ -770,7 +772,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} }
public @Nullable ResettableExtent getTransform() { public @Nullable ResettableExtent getTransform() {
ExtentTraverser<AbstractDelegateExtent> traverser = new ExtentTraverser(this.extent).find(ResettableExtent.class); ExtentTraverser traverser = new ExtentTraverser(this.extent).find(ResettableExtent.class);
if (traverser != null) { if (traverser != null) {
return (ResettableExtent) traverser.get(); return (ResettableExtent) traverser.get();
} }
@ -788,7 +790,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} else { } else {
new MaskTraverser(mask).reset(this); new MaskTraverser(mask).reset(this);
} }
ExtentTraverser<SourceMaskExtent> maskingExtent = new ExtentTraverser(this.extent).find(SourceMaskExtent.class); ExtentTraverser<SourceMaskExtent> maskingExtent = new ExtentTraverser<>(this.extent).find(SourceMaskExtent.class);
if (maskingExtent != null && maskingExtent.get() != null) { if (maskingExtent != null && maskingExtent.get() != null) {
Mask oldMask = maskingExtent.get().getMask(); Mask oldMask = maskingExtent.get().getMask();
if (oldMask instanceof ResettableMask) { if (oldMask instanceof ResettableMask) {
@ -845,7 +847,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return the survival simulation extent * @return the survival simulation extent
*/ */
public SurvivalModeExtent getSurvivalExtent() { public SurvivalModeExtent getSurvivalExtent() {
ExtentTraverser<SurvivalModeExtent> survivalExtent = new ExtentTraverser(this.extent).find(SurvivalModeExtent.class); ExtentTraverser<SurvivalModeExtent> survivalExtent = new ExtentTraverser<>(this.extent).find(SurvivalModeExtent.class);
if (survivalExtent != null) { if (survivalExtent != null) {
return survivalExtent.get(); return survivalExtent.get();
} else { } else {
@ -878,7 +880,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
if (history == null) { if (history == null) {
return; return;
} }
ExtentTraverser traverseHistory = new ExtentTraverser(this.extent).find(HistoryExtent.class); ExtentTraverser<HistoryExtent> traverseHistory = new ExtentTraverser<>(this.extent).find(HistoryExtent.class);
if (disableHistory) { if (disableHistory) {
if (traverseHistory != null && traverseHistory.exists()) { if (traverseHistory != null && traverseHistory.exists()) {
ExtentTraverser beforeHistory = traverseHistory.previous(); ExtentTraverser beforeHistory = traverseHistory.previous();
@ -890,7 +892,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} }
} }
} else if (traverseHistory == null || !traverseHistory.exists()) { } else if (traverseHistory == null || !traverseHistory.exists()) {
ExtentTraverser traverseBypass = new ExtentTraverser(this.extent).find(bypassHistory); ExtentTraverser traverseBypass = new ExtentTraverser<>(this.extent).find(bypassHistory);
if (traverseBypass != null) { if (traverseBypass != null) {
ExtentTraverser beforeHistory = traverseBypass.previous(); ExtentTraverser beforeHistory = traverseBypass.previous();
beforeHistory.setNext(history); beforeHistory.setNext(history);
@ -939,19 +941,19 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* *
* @return a map of missing blocks * @return a map of missing blocks
*/ */
public Map<com.sk89q.worldedit.world.block.BlockType, Integer> popMissingBlocks() { public Map<BlockType, Integer> popMissingBlocks() {
BlockBag bag = getBlockBag(); BlockBag bag = getBlockBag();
if (bag != null) { if (bag != null) {
bag.flushChanges(); bag.flushChanges();
Map<com.sk89q.worldedit.world.block.BlockType, Integer> missingBlocks; Map<BlockType, Integer> missingBlocks;
ChangeSet changeSet = getChangeSet(); ChangeSet changeSet = getChangeSet();
if (changeSet instanceof BlockBagChangeSet) { if (changeSet instanceof BlockBagChangeSet) {
missingBlocks = ((BlockBagChangeSet) changeSet).popMissing(); missingBlocks = ((BlockBagChangeSet) changeSet).popMissing();
} else { } else {
ExtentTraverser<BlockBagExtent> find = new ExtentTraverser(extent).find(BlockBagExtent.class); ExtentTraverser<BlockBagExtent> find = new ExtentTraverser<>(extent).find(BlockBagExtent.class);
if (find != null && find.get() != null) { if (find != null && find.get() != null) {
missingBlocks = find.get().popMissing(); missingBlocks = find.get().popMissing();
} else { } else {
@ -1065,6 +1067,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return getLazyBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ()); return getLazyBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ());
} }
@Override
public BlockState getLazyBlock(int x, int y, int z) { public BlockState getLazyBlock(int x, int y, int z) {
return extent.getLazyBlock(x, y, z); return extent.getLazyBlock(x, y, z);
} }
@ -1083,18 +1086,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return extent.getFullBlock(position); return extent.getFullBlock(position);
} }
/**
* Get a block type at the given position.
*
* @param position the position
* @return the block type
* @deprecated Use {@link #getLazyBlock(BlockVector3)} or {@link #getBlock(BlockVector3)}
*/
@Deprecated
public BlockType getBlockType(final BlockVector3 position) {
return getBlockType(position.getBlockX(), position.getBlockY(), position.getBlockZ());
}
/** /**
* Returns the highest solid 'terrain' block. * Returns the highest solid 'terrain' block.
* *
@ -1104,6 +1095,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @param maxY maximal height * @param maxY maximal height
* @return height of highest block found or 'minY' * @return height of highest block found or 'minY'
*/ */
@Override
public int getHighestTerrainBlock(int x, int z, int minY, int maxY) { public int getHighestTerrainBlock(int x, int z, int minY, int maxY) {
for (int y = maxY; y >= minY; --y) { for (int y = maxY; y >= minY; --y) {
if (getBlock(x, y, z).getBlockType().getMaterial().isMovementBlocker()) { if (getBlock(x, y, z).getBlockType().getMaterial().isMovementBlocker()) {
@ -1123,6 +1115,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @param filter a mask of blocks to consider, or null to consider any solid (movement-blocking) block * @param filter a mask of blocks to consider, or null to consider any solid (movement-blocking) block
* @return height of highest block found or 'minY' * @return height of highest block found or 'minY'
*/ */
@Override
public int getHighestTerrainBlock(int x, int z, int minY, int maxY, Mask filter) { public int getHighestTerrainBlock(int x, int z, int minY, int maxY, Mask filter) {
for (int y = maxY; y >= minY; --y) { for (int y = maxY; y >= minY; --y) {
if (filter.test(mutablebv.setComponents(x, y, z))) { if (filter.test(mutablebv.setComponents(x, y, z))) {
@ -1209,6 +1202,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} }
@Override
public <B extends BlockStateHolder<B>> boolean setBlock(int x, int y, int z, B block) { public <B extends BlockStateHolder<B>> boolean setBlock(int x, int y, int z, B block) {
this.changes++; this.changes++;
try { try {
@ -1301,7 +1295,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
@Override @Override
@Nullable @Nullable
public Entity createEntity(com.sk89q.worldedit.util.Location location, final BaseEntity entity) { public Entity createEntity(Location location, final BaseEntity entity) {
return this.extent.createEntity(location, entity); return this.extent.createEntity(location, entity);
} }
@ -1472,12 +1466,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} }
if (searchIDs.size() == 1) { if (searchIDs.size() == 1) {
final BlockType id = searchIDs.iterator().next(); final BlockType id = searchIDs.iterator().next();
RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { RegionVisitor visitor = new RegionVisitor(region, position -> getBlock(position).getBlockType() == id, this);
@Override
public boolean apply(BlockVector3 position) throws WorldEditException {
return getBlockType(position) == id;
}
}, this);
Operations.completeBlindly(visitor); Operations.completeBlindly(visitor);
return visitor.getAffected(); return visitor.getAffected();
} }
@ -1489,23 +1478,14 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} }
public int countBlock(final Region region, final boolean[] ids) { public int countBlock(final Region region, final boolean[] ids) {
RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { RegionVisitor visitor = new RegionVisitor(region,
@Override position -> ids[getBlock(position).getInternalId()], this);
public boolean apply(BlockVector3 position) throws WorldEditException {
return ids[getBlockType(position).getInternalId()];
}
}, this);
Operations.completeBlindly(visitor); Operations.completeBlindly(visitor);
return visitor.getAffected(); return visitor.getAffected();
} }
public int countBlock(final Region region, final Mask mask) { public int countBlock(final Region region, final Mask mask) {
RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { RegionVisitor visitor = new RegionVisitor(region, mask::test, this);
@Override
public boolean apply(BlockVector3 position) throws WorldEditException {
return mask.test(position);
}
}, this);
Operations.completeBlindly(visitor); Operations.completeBlindly(visitor);
return visitor.getAffected(); return visitor.getAffected();
} }
@ -1519,12 +1499,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
*/ */
public int countBlocks(Region region, Set<BaseBlock> searchBlocks) { public int countBlocks(Region region, Set<BaseBlock> searchBlocks) {
Mask mask = new BlockMaskBuilder().addBlocks(searchBlocks).build(extent); Mask mask = new BlockMaskBuilder().addBlocks(searchBlocks).build(extent);
RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { RegionVisitor visitor = new RegionVisitor(region, mask::test, this);
@Override
public boolean apply(BlockVector3 position) throws WorldEditException {
return mask.test(position);
}
}, this);
Operations.completeBlindly(visitor); Operations.completeBlindly(visitor);
return visitor.getAffected(); return visitor.getAffected();
} }
@ -1534,30 +1509,27 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
final int startPerformY = region.getMinimumPoint().getBlockY(); final int startPerformY = region.getMinimumPoint().getBlockY();
final int startCheckY = fullHeight ? 0 : startPerformY; final int startCheckY = fullHeight ? 0 : startPerformY;
final int endY = region.getMaximumPoint().getBlockY(); final int endY = region.getMaximumPoint().getBlockY();
RegionVisitor visitor = new RegionVisitor(flat, new RegionFunction() { RegionVisitor visitor = new RegionVisitor(flat, pos -> {
@Override int x = pos.getBlockX();
public boolean apply(BlockVector3 pos) throws WorldEditException { int z = pos.getBlockZ();
int x = pos.getBlockX(); int freeSpot = startCheckY;
int z = pos.getBlockZ(); for (int y = startCheckY; y <= endY; y++) {
int freeSpot = startCheckY; if (y < startPerformY) {
for (int y = startCheckY; y <= endY; y++) { if (!getBlockType(x, y, z).getMaterial().isAir()) {
if (y < startPerformY) { freeSpot = y + 1;
if (!getBlockType(x, y, z).getMaterial().isAir()) {
freeSpot = y + 1;
}
continue;
}
BlockType block = getBlockType(x, y, z);
if (!block.getMaterial().isAir()) {
if (freeSpot != y) {
setBlock(x, freeSpot, z, block);
setBlock(x, y, z, replace);
}
freeSpot++;
} }
continue;
}
BlockType block = getBlockType(x, y, z);
if (!block.getMaterial().isAir()) {
if (freeSpot != y) {
setBlock(x, freeSpot, z, block);
setBlock(x, y, z, replace);
}
freeSpot++;
} }
return true;
} }
return true;
}, this); }, this);
Operations.completeBlindly(visitor); Operations.completeBlindly(visitor);
return this.changes; return this.changes;
@ -1574,7 +1546,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return number of blocks affected * @return number of blocks affected
* @throws MaxChangedBlocksException thrown if too many blocks are changed * @throws MaxChangedBlocksException thrown if too many blocks are changed
*/ */
public int fillDirection(final BlockVector3 origin, final Pattern pattern, final double radius, final int depth, BlockVector3 direction) { public int fillDirection(final BlockVector3 origin, final Pattern pattern, final double radius, final int depth, BlockVector3 direction) throws MaxChangedBlocksException {
checkNotNull(origin); checkNotNull(origin);
checkNotNull(pattern); checkNotNull(pattern);
checkArgument(radius >= 0, "radius >= 0"); checkArgument(radius >= 0, "radius >= 0");
@ -1727,12 +1699,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
FaweRegionExtent regionExtent = getRegionExtent(); FaweRegionExtent regionExtent = getRegionExtent();
if (!(region instanceof CuboidRegion)) return false; if (!(region instanceof CuboidRegion)) return false;
if (regionExtent != null) { if (regionExtent != null) {
if (!(region instanceof CuboidRegion)) return false;
BlockVector3 pos1 = region.getMinimumPoint(); BlockVector3 pos1 = region.getMinimumPoint();
BlockVector3 pos2 = region.getMaximumPoint(); BlockVector3 pos2 = region.getMaximumPoint();
boolean contains = false; boolean contains = false;
for (Region current : regionExtent.getRegions()) { for (Region current : regionExtent.getRegions()) {
if (current.contains((int) pos1.getX(), pos1.getBlockY(), pos1.getBlockZ()) && current.contains(pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ())) { if (current.contains(pos1.getX(), pos1.getBlockY(), pos1.getBlockZ()) && current.contains(pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ())) {
contains = true; contains = true;
break; break;
} }
@ -1745,8 +1716,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return false; return false;
if (getChangeTask() != getChangeSet()) return false; if (getChangeTask() != getChangeSet()) return false;
if (!Masks.isNull(getMask()) || !Masks.isNull(getSourceMask())) return false; if (!Masks.isNull(getMask()) || !Masks.isNull(getSourceMask())) return false;
if (getBlockBag() != null) return false; return getBlockBag() == null;
return true;
} }
public boolean hasExtraExtents() { public boolean hasExtraExtents() {
@ -1772,7 +1742,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
getWorld(), // Causes clamping of Y range getWorld(), // Causes clamping of Y range
position.add(adjustment.multiply(-1)), position.add(adjustment.multiply(-1)),
position.add(adjustment)); position.add(adjustment));
Pattern pattern = (BlockTypes.AIR.getDefaultState()); Pattern pattern = BlockTypes.AIR.getDefaultState();
return replaceBlocks(region, mask, pattern); return replaceBlocks(region, mask, pattern);
} }
@ -1787,7 +1757,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
public <B extends BlockStateHolder<B>> int setBlocks(Region region, B block) throws MaxChangedBlocksException { public <B extends BlockStateHolder<B>> int setBlocks(Region region, B block) throws MaxChangedBlocksException {
checkNotNull(region); checkNotNull(region);
checkNotNull(block); checkNotNull(block);
boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData(); boolean hasNbt = block instanceof BaseBlock && block.hasNbtData();
if (canBypassAll(region, false, true) && !hasNbt) { if (canBypassAll(region, false, true) && !hasNbt) {
return changes = queue.setBlocks((CuboidRegion) region, block.getInternalId()); return changes = queue.setBlocks((CuboidRegion) region, block.getInternalId());
@ -1845,7 +1815,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @throws MaxChangedBlocksException thrown if too many blocks are changed * @throws MaxChangedBlocksException thrown if too many blocks are changed
*/ */
public <B extends BlockStateHolder<B>> int replaceBlocks(Region region, Set<BaseBlock> filter, B replacement) throws MaxChangedBlocksException { public <B extends BlockStateHolder<B>> int replaceBlocks(Region region, Set<BaseBlock> filter, B replacement) throws MaxChangedBlocksException {
return replaceBlocks(region, filter, (replacement)); return replaceBlocks(region, filter, replacement);
} }
/** /**
@ -1917,7 +1887,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @throws MaxChangedBlocksException thrown if too many blocks are changed * @throws MaxChangedBlocksException thrown if too many blocks are changed
*/ */
public <B extends BlockStateHolder<B>> int makeCuboidFaces(Region region, B block) throws MaxChangedBlocksException { public <B extends BlockStateHolder<B>> int makeCuboidFaces(Region region, B block) throws MaxChangedBlocksException {
return makeCuboidFaces(region, (block)); return makeCuboidFaces(region, block);
} }
/** /**
@ -1969,7 +1939,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @throws MaxChangedBlocksException thrown if too many blocks are changed * @throws MaxChangedBlocksException thrown if too many blocks are changed
*/ */
public <B extends BlockStateHolder<B>> int makeCuboidWalls(Region region, B block) throws MaxChangedBlocksException { public <B extends BlockStateHolder<B>> int makeCuboidWalls(Region region, B block) throws MaxChangedBlocksException {
return makeCuboidWalls(region, (block)); return makeCuboidWalls(region, block);
} }
/** /**
@ -2094,7 +2064,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
BlockVector3 to = region.getMinimumPoint(); BlockVector3 to = region.getMinimumPoint();
ForwardExtentCopy copy = new ForwardExtentCopy(this, region, this, to); ForwardExtentCopy copy = new ForwardExtentCopy(this, region, this, to);
copy.setCopyingEntities(copyEntities); copy.setCopyingEntities(copyEntities);
copy.setCopyBiomes(copyBiomes); copy.setCopyingBiomes(copyBiomes);
copy.setRepetitions(count); copy.setRepetitions(count);
copy.setTransform(new AffineTransform().translate(dir.multiply(size))); copy.setTransform(new AffineTransform().translate(dir.multiply(size)));
Mask sourceMask = getSourceMask(); Mask sourceMask = getSourceMask();
@ -2140,8 +2110,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
ForwardExtentCopy copy = new ForwardExtentCopy(this, region, this, to); ForwardExtentCopy copy = new ForwardExtentCopy(this, region, this, to);
if (replacement == null) replacement = BlockTypes.AIR.getDefaultState(); if (replacement == null) replacement = BlockTypes.AIR.getDefaultState();
final BlockReplace remove = replacement instanceof ExistingPattern ? null : new BlockReplace(this, replacement); BlockReplace remove = replacement instanceof ExistingPattern ? null : new BlockReplace(this, replacement);
copy.setCopyBiomes(copyBiomes); copy.setCopyingBiomes(copyBiomes);
copy.setCopyingEntities(copyEntities); copy.setCopyingEntities(copyEntities);
copy.setSourceFunction(remove); // Remove copy.setSourceFunction(remove); // Remove
copy.setRemovingEntities(true); copy.setRemovingEntities(true);
@ -2170,7 +2140,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return number of blocks moved * @return number of blocks moved
* @throws MaxChangedBlocksException thrown if too many blocks are changed * @throws MaxChangedBlocksException thrown if too many blocks are changed
*/ */
public int moveCuboidRegion(Region region, BlockVector3 dir, int distance, boolean copyAir, Pattern replacement) { public int moveCuboidRegion(Region region, BlockVector3 dir, int distance, boolean copyAir, Pattern replacement) throws MaxChangedBlocksException {
return moveRegion(region, dir, distance, copyAir, true, false, replacement); return moveRegion(region, dir, distance, copyAir, true, false, replacement);
} }
@ -2214,7 +2184,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
if (waterlogged) { if (waterlogged) {
replace = new BlockReplace(this, new WaterloggedRemover(this)); replace = new BlockReplace(this, new WaterloggedRemover(this));
} else { } else {
replace = new BlockReplace(this, (BlockTypes.AIR.getDefaultState())); replace = new BlockReplace(this, BlockTypes.AIR.getDefaultState());
} }
RecursiveVisitor visitor = new RecursiveVisitor(mask, replace, (int) (radius * 2 + 1), this); RecursiveVisitor visitor = new RecursiveVisitor(mask, replace, (int) (radius * 2 + 1), this);
@ -2256,7 +2226,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
blockMask blockMask
); );
BlockReplace replace = new BlockReplace(this, (fluid.getDefaultState())); BlockReplace replace = new BlockReplace(this, fluid.getDefaultState());
NonRisingVisitor visitor = new NonRisingVisitor(mask, replace); NonRisingVisitor visitor = new NonRisingVisitor(mask, replace);
// Around the origin in a 3x3 block // Around the origin in a 3x3 block
@ -2298,15 +2268,15 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return number of blocks changed * @return number of blocks changed
* @throws MaxChangedBlocksException thrown if too many blocks are changed * @throws MaxChangedBlocksException thrown if too many blocks are changed
*/ */
public int makeCylinder(BlockVector3 pos, Pattern block, double radiusX, double radiusZ, int height, boolean filled) throws MaxChangedBlocksException{ public int makeCylinder(BlockVector3 pos, Pattern block, double radiusX, double radiusZ, int height, boolean filled) throws MaxChangedBlocksException {
return makeCylinder(pos, block, radiusX, radiusZ, height, 0, filled); return makeCylinder(pos, block, radiusX, radiusZ, height, 0, filled);
} }
public int makeHollowCylinder(BlockVector3 pos, final Pattern block, double radiusX, double radiusZ, int height, double thickness) { public int makeHollowCylinder(BlockVector3 pos, final Pattern block, double radiusX, double radiusZ, int height, double thickness) throws MaxChangedBlocksException {
return makeCylinder(pos, block, radiusX, radiusZ, height, thickness, false); return makeCylinder(pos, block, radiusX, radiusZ, height, thickness, false);
} }
private int makeCylinder(BlockVector3 pos, final Pattern block, double radiusX, double radiusZ, int height, double thickness, final boolean filled) { private int makeCylinder(BlockVector3 pos, Pattern block, double radiusX, double radiusZ, int height, double thickness, boolean filled) throws MaxChangedBlocksException {
int affected = 0; int affected = 0;
radiusX += 0.5; radiusX += 0.5;
@ -2322,12 +2292,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
if (posv.getBlockY() < 0) { if (posv.getBlockY() < 0) {
posv.mutY(0); posv.mutY(0);
} else if (((posv.getBlockY() + height) - 1) > maxY) { } else if (posv.getBlockY() + height - 1 > maxY) {
height = (maxY - posv.getBlockY()) + 1; height = maxY - posv.getBlockY() + 1;
} }
final double invRadiusX = 1 / (radiusX); final double invRadiusX = 1 / radiusX;
final double invRadiusZ = 1 / (radiusZ); final double invRadiusZ = 1 / radiusZ;
int px = posv.getBlockX(); int px = posv.getBlockX();
int py = posv.getBlockY(); int py = posv.getBlockY();
@ -2336,7 +2306,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
final int ceilRadiusX = (int) Math.ceil(radiusX); final int ceilRadiusX = (int) Math.ceil(radiusX);
final int ceilRadiusZ = (int) Math.ceil(radiusZ); final int ceilRadiusZ = (int) Math.ceil(radiusZ);
double dx, dxz, dz; double distanceSq;
double nextXn = 0; double nextXn = 0;
if (thickness != 0) { if (thickness != 0) {
@ -2350,15 +2320,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
nextMinXn = (x + 1) * minInvRadiusX; nextMinXn = (x + 1) * minInvRadiusX;
double nextZn = 0; double nextZn = 0;
double nextMinZn = 0; double nextMinZn = 0;
dx = xn * xn;
forZ: for (int z = 0; z <= ceilRadiusZ; ++z) { forZ: for (int z = 0; z <= ceilRadiusZ; ++z) {
final double zn = nextZn; final double zn = nextZn;
double dz2 = nextMinZn * nextMinZn; double dz2 = nextMinZn * nextMinZn;
nextZn = (z + 1) * invRadiusZ; nextZn = (z + 1) * invRadiusZ;
nextMinZn = (z + 1) * minInvRadiusZ; nextMinZn = (z + 1) * minInvRadiusZ;
dz = zn * zn; distanceSq = lengthSq(xn, zn);
dxz = dx + dz; if (distanceSq > 1) {
if (dxz > 1) {
if (z == 0) { if (z == 0) {
break forX; break forX;
} }
@ -2381,14 +2349,14 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
forX: for (int x = 0; x <= ceilRadiusX; ++x) { forX: for (int x = 0; x <= ceilRadiusX; ++x) {
final double xn = nextXn; final double xn = nextXn;
nextXn = (x + 1) * invRadiusX; nextXn = (x + 1) * invRadiusX;
double dx = xn * xn;
double nextZn = 0; double nextZn = 0;
dx = xn * xn;
forZ: for (int z = 0; z <= ceilRadiusZ; ++z) { forZ: for (int z = 0; z <= ceilRadiusZ; ++z) {
final double zn = nextZn; final double zn = nextZn;
nextZn = (z + 1) * invRadiusZ; nextZn = (z + 1) * invRadiusZ;
dz = zn * zn; double dz = zn * zn;
dxz = dx + dz; distanceSq = lengthSq(xn,zn);
if (dxz > 1) { if (distanceSq > 1) {
if (z == 0) { if (z == 0) {
break forX; break forX;
} }
@ -2414,7 +2382,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return this.changes; return this.changes;
} }
public int makeCircle(BlockVector3 pos, final Pattern block, double radiusX, double radiusY, double radiusZ, boolean filled, Vector3 normal) { public int makeCircle(BlockVector3 pos, final Pattern block, double radiusX, double radiusY, double radiusZ, boolean filled, Vector3 normal) throws MaxChangedBlocksException {
radiusX += 0.5; radiusX += 0.5;
radiusY += 0.5; radiusY += 0.5;
radiusZ += 0.5; radiusZ += 0.5;
@ -2549,20 +2517,18 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
double nextXn = invRadiusX; double nextXn = invRadiusX;
forX: for (int x = 0; x <= ceilRadiusX; ++x) { forX: for (int x = 0; x <= ceilRadiusX; ++x) {
final double xn = nextXn; final double xn = nextXn;
double dx = xn * xn;
nextXn = (x + 1) * invRadiusX; nextXn = (x + 1) * invRadiusX;
double nextZn = invRadiusZ; double nextZn = invRadiusZ;
double dx = xn * xn;
forZ: for (int z = 0; z <= ceilRadiusZ; ++z) { forZ: for (int z = 0; z <= ceilRadiusZ; ++z) {
final double zn = nextZn; final double zn = nextZn;
double dz = zn * zn; double dz = zn * zn;
double dxz = dx + dz;
nextZn = (z + 1) * invRadiusZ; nextZn = (z + 1) * invRadiusZ;
double nextYn = invRadiusY; double nextYn = invRadiusY;
forY: for (int y = 0; y <= ceilRadiusY; ++y) { forY: for (int y = 0; y <= ceilRadiusY; ++y) {
final double yn = nextYn; final double yn = nextYn;
double dy = yn * yn; double dxyz = lengthSq(zn, yn, zn);
double dxyz = dxz + dy;
nextYn = (y + 1) * invRadiusY; nextYn = (y + 1) * invRadiusY;
if (dxyz > 1) { if (dxyz > 1) {
@ -2576,7 +2542,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} }
if (!filled) { if (!filled) {
if (nextXn * nextXn + dy + dz <= 1 && nextYn * nextYn + dx + dz <= 1 && nextZn * nextZn + dx + dy <= 1) { double dy = yn * yn;
if (lengthSq(nextXn, yn, zn) <= 1 && lengthSq(xn, nextYn, zn) <= 1 && lengthSq(xn, yn, nextZn) <= 1) {
continue; continue;
} }
} }
@ -2763,11 +2730,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return number of blocks affected * @return number of blocks affected
* @throws MaxChangedBlocksException thrown if too many blocks are changed * @throws MaxChangedBlocksException thrown if too many blocks are changed
*/ */
public int green(BlockVector3 position, double radius, final boolean onlyNormalDirt) public int green(BlockVector3 position, double radius, boolean onlyNormalDirt)
throws MaxChangedBlocksException { throws MaxChangedBlocksException {
int affected = 0;
final double radiusSq = radius * radius; final double radiusSq = radius * radius;
final int ox = position.getBlockX(); final int ox = position.getBlockX();
final int oy = position.getBlockY();
final int oz = position.getBlockZ(); final int oz = position.getBlockZ();
final BlockState grass = BlockTypes.GRASS_BLOCK.getDefaultState(); final BlockState grass = BlockTypes.GRASS_BLOCK.getDefaultState();
@ -2776,27 +2745,25 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
for (int x = ox - ceilRadius; x <= ox + ceilRadius; ++x) { for (int x = ox - ceilRadius; x <= ox + ceilRadius; ++x) {
int dx = x - ox; int dx = x - ox;
int dx2 = dx * dx; int dx2 = dx * dx;
for (int z = oz - ceilRadius; z <= (oz + ceilRadius); ++z) { for (int z = oz - ceilRadius; z <= oz + ceilRadius; ++z) {
int dz = z - oz; int dz = z - oz;
int dz2 = dz * dz; int dz2 = dz * dz;
if (dx2 + dz2 > radiusSq) { if (dx2 + dz2 > radiusSq) {
continue; continue;
} }
loop:
for (int y = maxY; y >= 1; --y) { for (int y = maxY; y >= 1; --y) {
BlockType block = getBlockType(x, y, z); final BlockState block = getBlock(x, y, z);
switch (block.getInternalId()) {
case BlockID.COARSE_DIRT: if (block.getBlockType() == BlockTypes.DIRT ||
if (onlyNormalDirt) break loop; (!onlyNormalDirt && block.getBlockType() == BlockTypes.COARSE_DIRT)) {
case BlockID.DIRT: this.setBlock(x, y, z, grass);
this.setBlock(x, y, z, BlockTypes.GRASS_BLOCK.getDefaultState());
break loop; break;
case BlockID.WATER: } else if (block.getBlockType() == BlockTypes.WATER || block.getBlockType() == BlockTypes.LAVA) {
case BlockID.LAVA: break;
default: } else if (block.getBlockType().getMaterial().isMovementBlocker()) {
if (block.getMaterial().isMovementBlocker()) { break;
break loop;
}
} }
} }
} }
@ -2813,11 +2780,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return number of patches created * @return number of patches created
* @throws MaxChangedBlocksException thrown if too many blocks are changed * @throws MaxChangedBlocksException thrown if too many blocks are changed
*/ */
public int makePumpkinPatches(final BlockVector3 position, final int apothem) { public int makePumpkinPatches(BlockVector3 position, int apothem) throws MaxChangedBlocksException {
return makePumpkinPatches(position, apothem, 0.02); return makePumpkinPatches(position, apothem, 0.02);
} }
public int makePumpkinPatches(final BlockVector3 position, final int apothem, double density) { public int makePumpkinPatches(BlockVector3 position, int apothem, double density) throws MaxChangedBlocksException {
// We want to generate pumpkins // We want to generate pumpkins
GardenPatchGenerator generator = new GardenPatchGenerator(this); GardenPatchGenerator generator = new GardenPatchGenerator(this);
generator.setPlant(GardenPatchGenerator.getPumpkinPattern()); generator.setPlant(GardenPatchGenerator.getPumpkinPattern());
@ -2846,7 +2813,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @throws MaxChangedBlocksException thrown if too many blocks are changed * @throws MaxChangedBlocksException thrown if too many blocks are changed
*/ */
public int makeForest(BlockVector3 basePosition, int size, double density, TreeGenerator.TreeType treeType) throws MaxChangedBlocksException { public int makeForest(BlockVector3 basePosition, int size, double density, TreeGenerator.TreeType treeType) throws MaxChangedBlocksException {
try {
for (int x = basePosition.getBlockX() - size; x <= (basePosition.getBlockX() + size); ++x) { for (int x = basePosition.getBlockX() - size; x <= (basePosition.getBlockX() + size); ++x) {
for (int z = basePosition.getBlockZ() - size; z <= (basePosition.getBlockZ() + size); ++z) { for (int z = basePosition.getBlockZ() - size; z <= (basePosition.getBlockZ() + size); ++z) {
// Don't want to be in the ground // Don't want to be in the ground
@ -2873,7 +2839,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} }
} }
} }
} catch (MaxChangedBlocksException ignore) {}
return this.changes; return this.changes;
} }
@ -2928,7 +2893,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} }
} else { } else {
for (final BlockVector3 pt : region) { for (final BlockVector3 pt : region) {
BlockType type = getBlockType(pt); BlockType type = getBlock(pt).getBlockType();
counter[type.getInternalId()]++; counter[type.getInternalId()]++;
} }
} }
@ -3100,6 +3065,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
final RValue x = expression.getVariable("x", false).optimize(); final RValue x = expression.getVariable("x", false).optimize();
final RValue y = expression.getVariable("y", false).optimize(); final RValue y = expression.getVariable("y", false).optimize();
final RValue z = expression.getVariable("z", false).optimize(); final RValue z = expression.getVariable("z", false).optimize();
final WorldEditExpressionEnvironment environment = new WorldEditExpressionEnvironment(this, unit, zero); final WorldEditExpressionEnvironment environment = new WorldEditExpressionEnvironment(this, unit, zero);
expression.setEnvironment(environment); expression.setEnvironment(environment);
final Vector3 zero2 = zero.add(0.5, 0.5, 0.5); final Vector3 zero2 = zero.add(0.5, 0.5, 0.5);
@ -3142,7 +3108,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @throws MaxChangedBlocksException thrown if too many blocks are changed * @throws MaxChangedBlocksException thrown if too many blocks are changed
*/ */
public int hollowOutRegion(Region region, int thickness, Pattern pattern) throws MaxChangedBlocksException { public int hollowOutRegion(Region region, int thickness, Pattern pattern) throws MaxChangedBlocksException {
try {
final Set<BlockVector3> outside = new LocalBlockVectorSet(); final Set<BlockVector3> outside = new LocalBlockVectorSet();
final BlockVector3 min = region.getMinimumPoint(); final BlockVector3 min = region.getMinimumPoint();
@ -3201,12 +3166,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} }
} }
this.changes++; this.changes++;
try {
pattern.apply(this.extent, position, position); pattern.apply(this.extent, position, position);
} catch (WorldEditException e) {
e.printStackTrace();
} }
} catch (WorldEditException e) {
throw new RuntimeException(e);
} }
return changes; return changes;
} }
@ -3276,12 +3241,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} }
Set<BlockVector3> newVset; Set<BlockVector3> newVset;
if (flat) { if (flat) {
newVset = this.getStretched(vset, radius); newVset = getStretched(vset, radius);
if (!filled) { if (!filled) {
newVset = this.getOutline(newVset); newVset = this.getOutline(newVset);
} }
} else { } else {
newVset = this.getBallooned(vset, radius); newVset = getBallooned(vset, radius);
if (!filled) { if (!filled) {
newVset = this.getHollowed(newVset); newVset = this.getHollowed(newVset);
} }
@ -3324,16 +3289,20 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
interpol.setNodes(nodes); interpol.setNodes(nodes);
double splinelength = interpol.arcLength(0, 1); double splinelength = interpol.arcLength(0, 1);
for (double loop = 0; loop <= 1; loop += 1D / splinelength / quality) { for (double loop = 0; loop <= 1; loop += 1D / splinelength / quality) {
final BlockVector3 tipv = interpol.getPosition(loop).toBlockPoint(); BlockVector3 tipv = interpol.getPosition(loop).toBlockPoint();
if (radius == 0) { if (radius == 0) {
pattern.apply(this, tipv, tipv); try {
pattern.apply(this, tipv, tipv);
} catch (WorldEditException e) {
e.printStackTrace();
}
} else { } else {
vset.add(tipv); vset.add(tipv);
} }
} }
Set<BlockVector3> newVset; Set<BlockVector3> newVset;
if (radius != 0) { if (radius != 0) {
newVset = this.getBallooned(vset, radius); newVset = getBallooned(vset, radius);
if (!filled) { if (!filled) {
newVset = this.getHollowed(newVset); newVset = this.getHollowed(newVset);
} }
@ -3342,7 +3311,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return changes; return changes;
} }
private Set<BlockVector3> getBallooned(Set<BlockVector3> vset, double radius) { private static Set<BlockVector3> getBallooned(Set<BlockVector3> vset, double radius) {
if (radius < 1) { if (radius < 1) {
return vset; return vset;
} }
@ -3352,9 +3321,9 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
for (BlockVector3 v : vset) { for (BlockVector3 v : vset) {
int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ(); int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ();
for (int loopx = tipx - ceilrad; loopx <= (tipx + ceilrad); loopx++) { for (int loopx = tipx - ceilrad; loopx <= tipx + ceilrad; loopx++) {
for (int loopy = tipy - ceilrad; loopy <= (tipy + ceilrad); loopy++) { for (int loopy = tipy - ceilrad; loopy <= tipy + ceilrad; loopy++) {
for (int loopz = tipz - ceilrad; loopz <= (tipz + ceilrad); loopz++) { for (int loopz = tipz - ceilrad; loopz <= tipz + ceilrad; loopz++) {
if (MathMan.hypot(loopx - tipx, loopy - tipy, loopz - tipz) <= radius) { if (MathMan.hypot(loopx - tipx, loopy - tipy, loopz - tipz) <= radius) {
returnset.add(loopx, loopy, loopz); returnset.add(loopx, loopy, loopz);
} }
@ -3365,7 +3334,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return returnset; return returnset;
} }
public Set<BlockVector3> getStretched(final Set<BlockVector3> vset, final double radius) { public static Set<BlockVector3> getStretched(Set<BlockVector3> vset, double radius) {
if (radius < 1) { if (radius < 1) {
return vset; return vset;
} }
@ -3373,8 +3342,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
final int ceilrad = (int) Math.ceil(radius); final int ceilrad = (int) Math.ceil(radius);
for (final BlockVector3 v : vset) { for (final BlockVector3 v : vset) {
final int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ(); final int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ();
for (int loopx = tipx - ceilrad; loopx <= (tipx + ceilrad); loopx++) { for (int loopx = tipx - ceilrad; loopx <= tipx + ceilrad; loopx++) {
for (int loopz = tipz - ceilrad; loopz <= (tipz + ceilrad); loopz++) { for (int loopz = tipz - ceilrad; loopz <= tipz + ceilrad; loopz++) {
if (MathMan.hypot(loopx - tipx, 0, loopz - tipz) <= radius) { if (MathMan.hypot(loopx - tipx, 0, loopz - tipz) <= radius) {
returnset.add(loopx, v.getBlockY(), loopz); returnset.add(loopx, v.getBlockY(), loopz);
} }
@ -3384,7 +3353,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return returnset; return returnset;
} }
public Set<BlockVector3> getOutline(final Set<BlockVector3> vset) { public Set<BlockVector3> getOutline(Set<BlockVector3> vset) {
final LocalBlockVectorSet returnset = new LocalBlockVectorSet(); final LocalBlockVectorSet returnset = new LocalBlockVectorSet();
final LocalBlockVectorSet newset = new LocalBlockVectorSet(); final LocalBlockVectorSet newset = new LocalBlockVectorSet();
newset.addAll(vset); newset.addAll(vset);
@ -3400,7 +3369,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return returnset; return returnset;
} }
public Set<BlockVector3> getHollowed(final Set<BlockVector3> vset) { public Set<BlockVector3> getHollowed(Set<BlockVector3> vset) {
final Set<BlockVector3> returnset = new LocalBlockVectorSet(); final Set<BlockVector3> returnset = new LocalBlockVectorSet();
final LocalBlockVectorSet newset = new LocalBlockVectorSet(); final LocalBlockVectorSet newset = new LocalBlockVectorSet();
newset.addAll(vset); newset.addAll(vset);
@ -3421,6 +3390,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
private void recurseHollow(Region region, BlockVector3 origin, Set<BlockVector3> outside) { private void recurseHollow(Region region, BlockVector3 origin, Set<BlockVector3> outside) {
final LocalBlockVectorSet queue = new LocalBlockVectorSet(); final LocalBlockVectorSet queue = new LocalBlockVectorSet();
queue.add(origin); queue.add(origin);
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
final BlockVector3 current = queue.getIndex(0); final BlockVector3 current = queue.getIndex(0);
queue.remove(current); queue.remove(current);
@ -3518,6 +3488,10 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return worldName; return worldName;
} }
@Override public @org.jetbrains.annotations.Nullable Path getStoragePath() {
return null;
}
@Override @Override
public int getBlockLightLevel(BlockVector3 position) { public int getBlockLightLevel(BlockVector3 position) {
return queue.getEmmittedLight(position.getBlockX(), position.getBlockY(), position.getBlockZ()); return queue.getEmmittedLight(position.getBlockX(), position.getBlockY(), position.getBlockZ());
@ -3666,12 +3640,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return false; return false;
} }
// public void dropItem(BlockVector3 position, BaseItemStack item) {
// if (getWorld() != null) {
// getWorld().dropItem(position, item);
// }
// }
@Override @Override
public void simulateBlockMine(BlockVector3 position) { public void simulateBlockMine(BlockVector3 position) {
TaskManager.IMP.sync((Supplier<Object>) () -> { TaskManager.IMP.sync((Supplier<Object>) () -> {

View File

@ -20,13 +20,13 @@
package com.sk89q.worldedit; package com.sk89q.worldedit;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extent.NullExtent; import com.sk89q.worldedit.extent.NullExtent;
import com.sk89q.worldedit.function.mask.BlockMask; import com.sk89q.worldedit.function.mask.BlockMask;
import com.sk89q.worldedit.function.mask.BlockMaskBuilder; import com.sk89q.worldedit.function.mask.BlockMaskBuilder;
import com.sk89q.worldedit.util.logging.LogFormat; import com.sk89q.worldedit.util.logging.LogFormat;
import com.sk89q.worldedit.world.block.BlockStateHolder; import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType; import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.registry.LegacyMapper; import com.sk89q.worldedit.world.registry.LegacyMapper;
import com.sk89q.worldedit.world.snapshot.SnapshotRepository; import com.sk89q.worldedit.world.snapshot.SnapshotRepository;
@ -59,11 +59,10 @@ public abstract class LocalConfiguration {
public boolean logCommands = false; public boolean logCommands = false;
public String logFile = ""; public String logFile = "";
public String logFormat = LogFormat.DEFAULT_FORMAT; public String logFormat = LogFormat.DEFAULT_FORMAT;
public boolean registerHelp = true; // what is the point of this, it's not even used public boolean registerHelp = true; // unused
public String wandItem = "minecraft:wooden_axe"; public String wandItem = "minecraft:wooden_axe";
public boolean superPickaxeDrop = true; public boolean superPickaxeDrop = true;
public boolean superPickaxeManyDrop = true; public boolean superPickaxeManyDrop = true;
public boolean noDoubleSlash = false;
public boolean useInventory = false; public boolean useInventory = false;
public boolean useInventoryOverride = false; public boolean useInventoryOverride = false;
public boolean useInventoryCreativeOverride = false; public boolean useInventoryCreativeOverride = false;
@ -76,7 +75,7 @@ public abstract class LocalConfiguration {
public Set<String> allowedDataCycleBlocks = new HashSet<>(); public Set<String> allowedDataCycleBlocks = new HashSet<>();
public String saveDir = "schematics"; public String saveDir = "schematics";
public String scriptsDir = "craftscripts"; public String scriptsDir = "craftscripts";
public boolean showHelpInfo = true; public boolean showHelpInfo = true; // unused
public int butcherDefaultRadius = -1; public int butcherDefaultRadius = -1;
public int butcherMaxRadius = -1; public int butcherMaxRadius = -1;
public boolean allowSymlinks = false; public boolean allowSymlinks = false;
@ -158,7 +157,11 @@ public abstract class LocalConfiguration {
if (disallowedBlocksMask == null) { if (disallowedBlocksMask == null) {
BlockMaskBuilder builder = new BlockMaskBuilder(); BlockMaskBuilder builder = new BlockMaskBuilder();
for (String blockRegex : disallowedBlocks) { for (String blockRegex : disallowedBlocks) {
builder.addRegex(blockRegex); try {
builder.addRegex(blockRegex);
} catch (InputParseException e) {
e.printStackTrace();
}
} }
disallowedBlocksMask = builder.build(new NullExtent()); disallowedBlocksMask = builder.build(new NullExtent());
} }

View File

@ -19,6 +19,8 @@
package com.sk89q.worldedit; package com.sk89q.worldedit;
import static com.google.common.base.Preconditions.checkNotNull;
import com.boydti.fawe.Fawe; import com.boydti.fawe.Fawe;
import com.boydti.fawe.config.Settings; import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.FaweInputStream; import com.boydti.fawe.object.FaweInputStream;
@ -39,8 +41,6 @@ import com.boydti.fawe.util.StringMan;
import com.boydti.fawe.util.TextureHolder; import com.boydti.fawe.util.TextureHolder;
import com.boydti.fawe.util.TextureUtil; import com.boydti.fawe.util.TextureUtil;
import com.boydti.fawe.wrappers.WorldWrapper; import com.boydti.fawe.wrappers.WorldWrapper;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.jchronic.Chronic; import com.sk89q.jchronic.Chronic;
import com.sk89q.jchronic.Options; import com.sk89q.jchronic.Options;
import com.sk89q.jchronic.utils.Span; import com.sk89q.jchronic.utils.Span;
@ -71,19 +71,19 @@ import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.regions.selector.RegionSelectorType; import com.sk89q.worldedit.regions.selector.RegionSelectorType;
import com.sk89q.worldedit.session.ClipboardHolder; import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.session.request.Request; import com.sk89q.worldedit.session.request.Request;
import com.sk89q.worldedit.util.Countable;
import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.util.HandSide;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.item.ItemTypes; import com.sk89q.worldedit.world.item.ItemTypes;
import com.sk89q.worldedit.world.snapshot.Snapshot; import com.sk89q.worldedit.world.snapshot.Snapshot;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.time.ZoneId;
import java.util.Calendar; import java.util.Calendar;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedList; import java.util.LinkedList;
@ -93,17 +93,19 @@ import java.util.Map;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/** /**
* Stores session information. * Stores session information.
*/ */
public class LocalSession implements TextureHolder { public class LocalSession implements TextureHolder {
public transient static int MAX_HISTORY_SIZE = 15; public static transient int MAX_HISTORY_SIZE = 15;
// Non-session related fields // Non-session related fields
private transient LocalConfiguration config; private transient LocalConfiguration config;
private transient final AtomicBoolean dirty = new AtomicBoolean(); private final transient AtomicBoolean dirty = new AtomicBoolean();
private transient int failedCuiAttempts = 0; private transient int failedCuiAttempts = 0;
// Session related // Session related
@ -127,7 +129,6 @@ public class LocalSession implements TextureHolder {
}); });
private transient volatile Integer historyNegativeIndex; private transient volatile Integer historyNegativeIndex;
private transient ClipboardHolder clipboard; private transient ClipboardHolder clipboard;
private transient boolean toolControl = true;
private transient boolean superPickaxe = false; private transient boolean superPickaxe = false;
private transient BlockTool pickaxeMode = new SinglePickaxe(); private transient BlockTool pickaxeMode = new SinglePickaxe();
private transient boolean hasTool = false; private transient boolean hasTool = false;
@ -143,18 +144,21 @@ public class LocalSession implements TextureHolder {
private transient Mask sourceMask; private transient Mask sourceMask;
private transient TextureUtil texture; private transient TextureUtil texture;
private transient ResettableExtent transform = null; private transient ResettableExtent transform = null;
private transient TimeZone timezone = TimeZone.getDefault(); private transient ZoneId timezone = ZoneId.systemDefault();
private transient World currentWorld; private transient World currentWorld;
private transient UUID uuid; private transient UUID uuid;
private transient volatile long historySize = 0; private transient volatile long historySize = 0;
private transient VirtualWorld virtual; private transient VirtualWorld virtual;
private transient BlockVector3 cuiTemporaryBlock; private transient BlockVector3 cuiTemporaryBlock;
private transient List<Countable<BlockState>> lastDistribution;
// Saved properties // Saved properties
private String lastScript; private String lastScript;
private RegionSelectorType defaultSelector; private RegionSelectorType defaultSelector;
private boolean useServerCUI = false; // Save this to not annoy players. private boolean useServerCUI = false; // Save this to not annoy players.
private String wandItem;
private String navWandItem;
/** /**
* Construct the object. * Construct the object.
@ -193,11 +197,6 @@ public class LocalSession implements TextureHolder {
} }
} }
/**
* @param uuid
* @param world
* @return If any loading occured
*/
public boolean loadSessionHistoryFromDisk(UUID uuid, World world) { public boolean loadSessionHistoryFromDisk(UUID uuid, World world) {
if (world == null || uuid == null) { if (world == null || uuid == null) {
return false; return false;
@ -344,7 +343,7 @@ public class LocalSession implements TextureHolder {
* *
* @return the timezone * @return the timezone
*/ */
public TimeZone getTimeZone() { public ZoneId getTimeZone() {
return timezone; return timezone;
} }
@ -353,7 +352,7 @@ public class LocalSession implements TextureHolder {
* *
* @param timezone the user's timezone * @param timezone the user's timezone
*/ */
public void setTimezone(TimeZone timezone) { public void setTimezone(ZoneId timezone) {
checkNotNull(timezone); checkNotNull(timezone);
this.timezone = timezone; this.timezone = timezone;
} }
@ -409,7 +408,6 @@ public class LocalSession implements TextureHolder {
} }
loadSessionHistoryFromDisk(player.getUniqueId(), world); loadSessionHistoryFromDisk(player.getUniqueId(), world);
if (changeSet instanceof FaweChangeSet) { if (changeSet instanceof FaweChangeSet) {
int size = getHistoryNegativeIndex();
ListIterator<Object> iter = history.listIterator(); ListIterator<Object> iter = history.listIterator();
int i = 0; int i = 0;
int cutoffIndex = history.size() - getHistoryNegativeIndex(); int cutoffIndex = history.size() - getHistoryNegativeIndex();
@ -454,9 +452,8 @@ public class LocalSession implements TextureHolder {
return; return;
} }
// Don't store anything if no changes were made // Don't store anything if no changes were made
if (editSession.size() == 0) { if (editSession.size() == 0) return;
return;
}
FaweChangeSet changeSet = (FaweChangeSet) editSession.getChangeSet(); FaweChangeSet changeSet = (FaweChangeSet) editSession.getChangeSet();
if (changeSet.isEmpty()) { if (changeSet.isEmpty()) {
return; return;
@ -468,7 +465,6 @@ public class LocalSession implements TextureHolder {
} }
// Destroy any sessions after this undo point // Destroy any sessions after this undo point
if (append) { if (append) {
int size = getHistoryNegativeIndex();
ListIterator<Object> iter = history.listIterator(); ListIterator<Object> iter = history.listIterator();
int i = 0; int i = 0;
int cutoffIndex = history.size() - getHistoryNegativeIndex(); int cutoffIndex = history.size() - getHistoryNegativeIndex();
@ -518,7 +514,7 @@ public class LocalSession implements TextureHolder {
loadSessionHistoryFromDisk(player.getUniqueId(), fp.getWorldForEditing()); loadSessionHistoryFromDisk(player.getUniqueId(), fp.getWorldForEditing());
if (getHistoryNegativeIndex() < history.size()) { if (getHistoryNegativeIndex() < history.size()) {
FaweChangeSet changeSet = getChangeSet(history.get(getHistoryIndex())); FaweChangeSet changeSet = getChangeSet(history.get(getHistoryIndex()));
EditSession newEditSession = new EditSessionBuilder(changeSet.getWorld()) try (EditSession newEditSession = new EditSessionBuilder(changeSet.getWorld())
.allowedRegionsEverywhere() .allowedRegionsEverywhere()
.checkMemory(false) .checkMemory(false)
.changeSetNull() .changeSetNull()
@ -526,11 +522,12 @@ public class LocalSession implements TextureHolder {
.limitUnprocessed(fp) .limitUnprocessed(fp)
.player(fp) .player(fp)
.blockBag(getBlockBag(player)) .blockBag(getBlockBag(player))
.build(); .build()) {
newEditSession.setBlocks(changeSet, ChangeSetExecutor.Type.UNDO); newEditSession.setBlocks(changeSet, ChangeSetExecutor.Type.UNDO);
setDirty(); setDirty();
historyNegativeIndex++; historyNegativeIndex++;
return newEditSession; return newEditSession;
}
} else { } else {
int size = history.size(); int size = history.size();
if (getHistoryNegativeIndex() != size) { if (getHistoryNegativeIndex() != size) {
@ -556,7 +553,7 @@ public class LocalSession implements TextureHolder {
setDirty(); setDirty();
historyNegativeIndex--; historyNegativeIndex--;
FaweChangeSet changeSet = getChangeSet(history.get(getHistoryIndex())); FaweChangeSet changeSet = getChangeSet(history.get(getHistoryIndex()));
EditSession newEditSession = new EditSessionBuilder(changeSet.getWorld()) try (EditSession newEditSession = new EditSessionBuilder(changeSet.getWorld())
.allowedRegionsEverywhere() .allowedRegionsEverywhere()
.checkMemory(false) .checkMemory(false)
.changeSetNull() .changeSetNull()
@ -564,9 +561,10 @@ public class LocalSession implements TextureHolder {
.limitUnprocessed(fp) .limitUnprocessed(fp)
.player(fp) .player(fp)
.blockBag(getBlockBag(player)) .blockBag(getBlockBag(player))
.build(); .build()) {
newEditSession.setBlocks(changeSet, ChangeSetExecutor.Type.REDO); newEditSession.setBlocks(changeSet, ChangeSetExecutor.Type.REDO);
return newEditSession; return newEditSession;
}
} }
return null; return null;
@ -707,27 +705,6 @@ public class LocalSession implements TextureHolder {
return world; return world;
} }
/**
* Get the world selection.
*
* @return the current selection
*/
public Region getWorldSelection() throws IncompleteRegionException {
return getSelection(getSelectionWorld());
}
/**
* This is an alias for {@link #getSelection(World)}.
* It enables CraftScripts to get a world selection as it is
* not possible to use getSelection which have two default
* implementations.
*
* @return Get the selection region in the world.
*/
public Region getWorldSelection(World world) throws IncompleteRegionException {
return getSelection(world);
}
/** /**
* Gets the clipboard. * Gets the clipboard.
* *
@ -783,21 +760,20 @@ public class LocalSession implements TextureHolder {
} }
/** /**
* See if tool control is enabled. * @return true always - see deprecation notice
* * @deprecated The wand is now a tool that can be bound/unbound.
* @return true if enabled
*/ */
@Deprecated
public boolean isToolControlEnabled() { public boolean isToolControlEnabled() {
return toolControl; return true;
} }
/** /**
* Change tool control setting. * @param toolControl unused - see deprecation notice
* * @deprecated The wand is now a tool that can be bound/unbound.
* @param toolControl true to enable tool control
*/ */
@Deprecated
public void setToolControl(boolean toolControl) { public void setToolControl(boolean toolControl) {
this.toolControl = toolControl;
} }
/** /**
@ -962,15 +938,12 @@ public class LocalSession implements TextureHolder {
@Nullable @Nullable
public Tool getTool(Player player) { public Tool getTool(Player player) {
if (!Settings.IMP.EXPERIMENTAL.PERSISTENT_BRUSHES && !hasTool) {
return null;
}
BaseItem item = player.getItemInHand(HandSide.MAIN_HAND); BaseItem item = player.getItemInHand(HandSide.MAIN_HAND);
return getTool(item, player); return getTool(item, player);
} }
public Tool getTool(BaseItem item, Player player) { public Tool getTool(BaseItem item, Player player) {
if (Settings.IMP.EXPERIMENTAL.PERSISTENT_BRUSHES && item.getNativeItem() != null) { if (item.getNativeItem() != null) {
BrushTool tool = BrushCache.getTool(player, this, item); BrushTool tool = BrushCache.getTool(player, this, item);
if (tool != null) return tool; if (tool != null) return tool;
} }
@ -987,7 +960,7 @@ public class LocalSession implements TextureHolder {
* @throws InvalidToolBindException if the item can't be bound to that item * @throws InvalidToolBindException if the item can't be bound to that item
*/ */
public BrushTool getBrushTool(ItemType item) throws InvalidToolBindException { public BrushTool getBrushTool(ItemType item) throws InvalidToolBindException {
return getBrushTool(item.getDefaultState(), null, true); return getBrushTool(item, null, true);
} }
public BrushTool getBrushTool(Player player) throws InvalidToolBindException { public BrushTool getBrushTool(Player player) throws InvalidToolBindException {
@ -995,17 +968,19 @@ public class LocalSession implements TextureHolder {
} }
public BrushTool getBrushTool(Player player, boolean create) throws InvalidToolBindException { public BrushTool getBrushTool(Player player, boolean create) throws InvalidToolBindException {
BaseItem item = player.getItemInHand(HandSide.MAIN_HAND); ItemType item = player.getItemInHand(HandSide.MAIN_HAND).getType();
return getBrushTool(item, player, create); return getBrushTool(item, player, create);
} }
public BrushTool getBrushTool(ItemType item, boolean create) throws InvalidToolBindException {
return getBrushTool(item, null, create);
}
public BrushTool getBrushTool(ItemType item, Player player, boolean create) throws InvalidToolBindException {
public BrushTool getBrushTool(BaseItem item, Player player, boolean create) throws InvalidToolBindException { Tool tool = getTool(item.getDefaultState(), player);
Tool tool = getTool(item, player);
if (!(tool instanceof BrushTool)) { if (!(tool instanceof BrushTool)) {
if (create) { if (create) {
tool = new BrushTool(); tool = new BrushTool();
setTool(item, tool, player); setTool(item.getDefaultState(), tool, player);
} else { } else {
return null; return null;
} }
@ -1032,7 +1007,7 @@ public class LocalSession implements TextureHolder {
setTool(item.getDefaultState(), tool, null); setTool(item.getDefaultState(), tool, null);
} }
public void setTool(@Nullable Tool tool, Player player) throws InvalidToolBindException { public void setTool(Player player, @Nullable Tool tool) throws InvalidToolBindException {
BaseItemStack item = player.getItemInHand(HandSide.MAIN_HAND); BaseItemStack item = player.getItemInHand(HandSide.MAIN_HAND);
setTool(item, tool, player); setTool(item, tool, player);
} }
@ -1047,7 +1022,7 @@ public class LocalSession implements TextureHolder {
throw new InvalidToolBindException(type, "Already used for the navigation wand"); throw new InvalidToolBindException(type, "Already used for the navigation wand");
} }
Tool previous; Tool previous;
if (player != null && (tool instanceof BrushTool || tool == null) && Settings.IMP.EXPERIMENTAL.PERSISTENT_BRUSHES && item.getNativeItem() != null) { if (player != null && (tool instanceof BrushTool || tool == null) && item.getNativeItem() != null) {
previous = BrushCache.getCachedTool(item); previous = BrushCache.getCachedTool(item);
BrushCache.setTool(item, (BrushTool) tool); BrushCache.setTool(item, (BrushTool) tool);
if (tool != null) { if (tool != null) {
@ -1068,7 +1043,7 @@ public class LocalSession implements TextureHolder {
} }
} }
} }
if (previous != null && player != null && previous instanceof BrushTool) { if (player != null && previous instanceof BrushTool) {
BrushTool brushTool = (BrushTool) previous; BrushTool brushTool = (BrushTool) previous;
brushTool.clear(player); brushTool.clear(player);
} }
@ -1259,9 +1234,9 @@ public class LocalSession implements TextureHolder {
* *
* @param text the message * @param text the message
*/ */
public void handleCUIInitializationMessage(String text) { public void handleCUIInitializationMessage(String text, Actor actor) {
checkNotNull(text); checkNotNull(text);
if (this.failedCuiAttempts > 3) { if (this.hasCUISupport || this.failedCuiAttempts > 3) {
return; return;
} }
@ -1271,13 +1246,18 @@ public class LocalSession implements TextureHolder {
this.failedCuiAttempts ++; this.failedCuiAttempts ++;
return; return;
} }
setCUISupport(true);
int version;
try { try {
setCUIVersion(Integer.parseInt(split[1])); version = Integer.parseInt(split[1]);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
WorldEdit.logger.warn("Error while reading CUI init message: " + e.getMessage()); WorldEdit.logger.warn("Error while reading CUI init message: " + e.getMessage());
this.failedCuiAttempts ++; this.failedCuiAttempts ++;
return;
} }
setCUISupport(true);
setCUIVersion(version);
dispatchCUISelection(actor);
} }
} }
@ -1327,9 +1307,10 @@ public class LocalSession implements TextureHolder {
public Calendar detectDate(String input) { public Calendar detectDate(String input) {
checkNotNull(input); checkNotNull(input);
Time.setTimeZone(getTimeZone()); TimeZone tz = TimeZone.getTimeZone(getTimeZone());
Time.setTimeZone(tz);
Options opt = new com.sk89q.jchronic.Options(); Options opt = new com.sk89q.jchronic.Options();
opt.setNow(Calendar.getInstance(getTimeZone())); opt.setNow(Calendar.getInstance(tz));
Span date = Chronic.parse(input, opt); Span date = Chronic.parse(input, opt);
if (date == null) { if (date == null) {
return null; return null;
@ -1349,16 +1330,13 @@ public class LocalSession implements TextureHolder {
BlockBag blockBag = getBlockBag(player); BlockBag blockBag = getBlockBag(player);
World world = player.getWorld(); // Create an edit session
boolean isPlayer = player.isPlayer(); EditSession editSession = WorldEdit.getInstance().getEditSessionFactory()
EditSessionBuilder builder = new EditSessionBuilder(world); .getEditSession(player.isPlayer() ? player.getWorld() : null,
if (player.isPlayer()) builder.player(FawePlayer.wrap(player)); getBlockChangeLimit(), blockBag, player);
builder.blockBag(blockBag);
builder.fastmode(fastMode);
EditSession editSession = builder.build();
Request.request().setEditSession(editSession); Request.request().setEditSession(editSession);
editSession.setFastMode(fastMode);
if (mask != null) { if (mask != null) {
editSession.setMask(mask); editSession.setMask(mask);
} }
@ -1368,6 +1346,7 @@ public class LocalSession implements TextureHolder {
if (transform != null) { if (transform != null) {
editSession.addTransform(transform); editSession.addTransform(transform);
} }
return editSession; return editSession;
} }
@ -1465,6 +1444,38 @@ public class LocalSession implements TextureHolder {
return tmp; return tmp;
} }
/**
* Get the preferred wand item for this user, or {@code null} to use the default
* @return item id of wand item, or {@code null}
*/
public String getWandItem() {
return wandItem;
}
/**
* Get the preferred navigation wand item for this user, or {@code null} to use the default
* @return item id of nav wand item, or {@code null}
*/
public String getNavWandItem() {
return navWandItem;
}
/**
* Get the last block distribution stored in this session.
*
* @return block distribution or {@code null}
*/
public List<Countable<BlockState>> getLastDistribution() {
return lastDistribution == null ? null : Collections.unmodifiableList(lastDistribution);
}
/**
* Store a block distribution in this session.
*/
public void setLastDistribution(List<Countable<BlockState>> dist) {
lastDistribution = dist;
}
public ResettableExtent getTransform() { public ResettableExtent getTransform() {
return transform; return transform;
} }

View File

@ -32,6 +32,7 @@ public class UnknownDirectionException extends WorldEditException {
* @param dir the input that was tried * @param dir the input that was tried
*/ */
public UnknownDirectionException(String dir) { public UnknownDirectionException(String dir) {
super("Unknown direction: " + dir);
this.dir = dir; this.dir = dir;
} }

View File

@ -19,9 +19,13 @@
package com.sk89q.worldedit; package com.sk89q.worldedit;
import com.boydti.fawe.config.BBC; import static com.sk89q.worldedit.event.platform.Interaction.HIT;
import static com.sk89q.worldedit.event.platform.Interaction.OPEN;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.blocks.BaseItem;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.platform.BlockInteractEvent; import com.sk89q.worldedit.event.platform.BlockInteractEvent;
@ -48,6 +52,7 @@ import com.sk89q.worldedit.scripting.RhinoCraftScriptEngine;
import com.sk89q.worldedit.session.SessionManager; import com.sk89q.worldedit.session.SessionManager;
import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.concurrency.EvenMoreExecutors;
import com.sk89q.worldedit.util.eventbus.EventBus; import com.sk89q.worldedit.util.eventbus.EventBus;
import com.sk89q.worldedit.util.io.file.FileSelectionAbortedException; import com.sk89q.worldedit.util.io.file.FileSelectionAbortedException;
import com.sk89q.worldedit.util.io.file.FilenameException; import com.sk89q.worldedit.util.io.file.FilenameException;
@ -60,11 +65,6 @@ import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.registry.BundledBlockData; import com.sk89q.worldedit.world.registry.BundledBlockData;
import com.sk89q.worldedit.world.registry.BundledItemData; import com.sk89q.worldedit.world.registry.BundledItemData;
import com.sk89q.worldedit.world.registry.LegacyMapper; import com.sk89q.worldedit.world.registry.LegacyMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.script.ScriptException;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -76,10 +76,12 @@ import java.nio.file.Paths;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.annotation.Nullable;
import static com.sk89q.worldedit.event.platform.Interaction.HIT; import javax.script.ScriptException;
import static com.sk89q.worldedit.event.platform.Interaction.OPEN; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* The entry point and container for a working implementation of WorldEdit. * The entry point and container for a working implementation of WorldEdit.
@ -105,6 +107,7 @@ public final class WorldEdit {
private final PlatformManager platformManager = new PlatformManager(this); private final PlatformManager platformManager = new PlatformManager(this);
private final EditSessionFactory editSessionFactory = new EditSessionFactory.EditSessionFactoryImpl(eventBus); private final EditSessionFactory editSessionFactory = new EditSessionFactory.EditSessionFactoryImpl(eventBus);
private final SessionManager sessions = new SessionManager(this); private final SessionManager sessions = new SessionManager(this);
private final ListeningExecutorService executorService = MoreExecutors.listeningDecorator(EvenMoreExecutors.newBoundedCachedThreadPool(0, 1, 20));
private final Supervisor supervisor = new SimpleSupervisor(); private final Supervisor supervisor = new SimpleSupervisor();
private final BlockFactory blockFactory = new BlockFactory(this); private final BlockFactory blockFactory = new BlockFactory(this);
@ -155,7 +158,7 @@ public final class WorldEdit {
} }
/** /**
* Get the supervisor. * Get the supervisor. Internal, not for API use.
* *
* @return the supervisor * @return the supervisor
*/ */
@ -163,6 +166,15 @@ public final class WorldEdit {
return supervisor; return supervisor;
} }
/**
* Get the executor service. Internal, not for API use.
*
* @return the executor service
*/
public ListeningExecutorService getExecutorService() {
return executorService;
}
/** /**
* Get the block factory from which new {@link BlockStateHolder}s can be * Get the block factory from which new {@link BlockStateHolder}s can be
* constructed. * constructed.
@ -307,6 +319,17 @@ public final class WorldEdit {
if (exts.size() != 1) { if (exts.size() != 1) {
exts = exts.subList(0, 1); exts = exts.subList(0, 1);
} }
} else {
int dot = filename.lastIndexOf('.');
if (dot < 0 || dot == filename.length() - 1) {
String currentExt = filename.substring(dot + 1);
if (exts.contains(currentExt) && checkFilename(filename)) {
File f = new File(dir, filename);
if (f.exists()) {
return f;
}
}
}
} }
File result = null; File result = null;
for (Iterator<String> iter = exts.iterator(); iter.hasNext() && (result == null || (!isSave && !result.exists()));) { for (Iterator<String> iter = exts.iterator(); iter.hasNext() && (result == null || (!isSave && !result.exists()));) {
@ -321,7 +344,7 @@ public final class WorldEdit {
private File getSafeFileWithExtension(File dir, String filename, String extension) { private File getSafeFileWithExtension(File dir, String filename, String extension) {
if (extension != null) { if (extension != null) {
int dot = filename.lastIndexOf('.'); int dot = filename.lastIndexOf('.');
if (dot < 0 || !filename.substring(dot).equalsIgnoreCase(extension)) { if (dot < 0 || dot == filename.length() - 1 || !filename.substring(dot + 1).equalsIgnoreCase(extension)) {
filename += "." + extension; filename += "." + extension;
} }
} }
@ -396,16 +419,15 @@ public final class WorldEdit {
} }
/** /**
* Get the direction vector for a player's direction. May return * Get the direction vector for a player's direction.
* null if a direction could not be found.
* *
* @param player the player * @param player the player
* @param dirStr the direction string * @param dirStr the direction string
* @return a direction vector * @return a direction vector
* @throws UnknownDirectionException thrown if the direction is not known * @throws UnknownDirectionException thrown if the direction is not known, or a relative direction is used with null player
*/ */
public BlockVector3 getDirection(Player player, String dirStr) throws UnknownDirectionException { public BlockVector3 getDirection(@Nullable Player player, String dirStr) throws UnknownDirectionException {
dirStr = dirStr.toLowerCase(); dirStr = dirStr.toLowerCase(Locale.ROOT);
final Direction dir = getPlayerDirection(player, dirStr); final Direction dir = getPlayerDirection(player, dirStr);
@ -417,16 +439,15 @@ public final class WorldEdit {
} }
/** /**
* Get the direction vector for a player's direction. May return * Get the direction vector for a player's direction.
* null if a direction could not be found.
* *
* @param player the player * @param player the player
* @param dirStr the direction string * @param dirStr the direction string
* @return a direction vector * @return a direction vector
* @throws UnknownDirectionException thrown if the direction is not known * @throws UnknownDirectionException thrown if the direction is not known, or a relative direction is used with null player
*/ */
public BlockVector3 getDiagonalDirection(Player player, String dirStr) throws UnknownDirectionException { public BlockVector3 getDiagonalDirection(@Nullable Player player, String dirStr) throws UnknownDirectionException {
dirStr = dirStr.toLowerCase(); dirStr = dirStr.toLowerCase(Locale.ROOT);
final Direction dir = getPlayerDirection(player, dirStr); final Direction dir = getPlayerDirection(player, dirStr);
@ -438,15 +459,14 @@ public final class WorldEdit {
} }
/** /**
* Get the direction vector for a player's direction. May return * Get the direction vector for a player's direction.
* null if a direction could not be found.
* *
* @param player the player * @param player the player
* @param dirStr the direction string * @param dirStr the direction string
* @return a direction enum value * @return a direction enum value
* @throws UnknownDirectionException thrown if the direction is not known * @throws UnknownDirectionException thrown if the direction is not known, or a relative direction is used with null player
*/ */
private Direction getPlayerDirection(Player player, String dirStr) throws UnknownDirectionException { private Direction getPlayerDirection(@Nullable Player player, String dirStr) throws UnknownDirectionException {
final Direction dir; final Direction dir;
switch (dirStr.charAt(0)) { switch (dirStr.charAt(0)) {
@ -490,19 +510,19 @@ public final class WorldEdit {
case 'm': // me case 'm': // me
case 'f': // forward case 'f': // forward
dir = player.getCardinalDirection(0); dir = getDirectionRelative(player, 0);
break; break;
case 'b': // back case 'b': // back
dir = player.getCardinalDirection(180); dir = getDirectionRelative(player, 180);
break; break;
case 'l': // left case 'l': // left
dir = player.getCardinalDirection(-90); dir = getDirectionRelative(player, -90);
break; break;
case 'r': // right case 'r': // right
dir = player.getCardinalDirection(90); dir = getDirectionRelative(player, 90);
break; break;
default: default:
@ -511,6 +531,13 @@ public final class WorldEdit {
return dir; return dir;
} }
private Direction getDirectionRelative(Player player, int yawOffset) throws UnknownDirectionException {
if (player != null) {
return player.getCardinalDirection(yawOffset);
}
throw new UnknownDirectionException("Only a player can use relative directions");
}
/** /**
* Flush a block bag's changes to a player. * Flush a block bag's changes to a player.
* *
@ -650,9 +677,9 @@ public final class WorldEdit {
try { try {
engine = new RhinoCraftScriptEngine(); engine = new RhinoCraftScriptEngine();
} catch (NoClassDefFoundError e) { } catch (NoClassDefFoundError ignored) {
player.printError("Failed to find an installed script engine."); player.printError("Failed to find an installed script engine.");
player.printError("Please see http://wiki.sk89q.com/wiki/WorldEdit/Installation"); player.printError("Please see https://worldedit.readthedocs.io/en/latest/usage/other/craftscripts/");
return; return;
} }

View File

@ -19,16 +19,13 @@
package com.sk89q.worldedit.blocks; package com.sk89q.worldedit.blocks;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.command.tool.Tool;
import com.sk89q.worldedit.world.NbtValued; import com.sk89q.worldedit.world.NbtValued;
import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.item.ItemTypes;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Represents an item, without an amount value. See {@link BaseItemStack} * Represents an item, without an amount value. See {@link BaseItemStack}
* for an instance with stack amount information. * for an instance with stack amount information.

View File

@ -0,0 +1,144 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* 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 <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.command;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseItem;
import com.sk89q.worldedit.command.factory.ItemUseFactory;
import com.sk89q.worldedit.command.factory.ReplaceFactory;
import com.sk89q.worldedit.command.factory.TreeGeneratorFactory;
import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.command.util.PermissionCondition;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.function.Contextual;
import com.sk89q.worldedit.function.RegionFunction;
import com.sk89q.worldedit.function.factory.Apply;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.internal.annotation.Direction;
import com.sk89q.worldedit.internal.command.CommandRegistrationHandler;
import com.sk89q.worldedit.regions.factory.RegionFactory;
import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldedit.util.formatting.text.format.TextDecoration;
import org.enginehub.piston.CommandManager;
import org.enginehub.piston.CommandManagerService;
import org.enginehub.piston.CommandParameters;
import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg;
import org.enginehub.piston.inject.Key;
import org.enginehub.piston.part.CommandArgument;
import org.enginehub.piston.part.SubCommandPart;
import java.util.stream.Collectors;
import static java.util.Objects.requireNonNull;
import static org.enginehub.piston.part.CommandParts.arg;
@CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class)
public class ApplyBrushCommands {
private static final CommandArgument REGION_FACTORY = arg(TranslatableComponent.of("shape"), TextComponent.of("The shape of the region"))
.defaultsTo(ImmutableList.of())
.ofTypes(ImmutableList.of(Key.of(RegionFactory.class)))
.build();
private static final CommandArgument RADIUS = arg(TranslatableComponent.of("radius"), TextComponent.of("The size of the brush"))
.defaultsTo(ImmutableList.of("5"))
.ofTypes(ImmutableList.of(Key.of(double.class)))
.build();
public static void register(CommandManagerService service, CommandManager commandManager, CommandRegistrationHandler registration) {
commandManager.register("apply", builder -> {
builder.description(TextComponent.of("Apply brush, apply a function to every block"));
builder.action(org.enginehub.piston.Command.Action.NULL_ACTION);
CommandManager manager = service.newCommandManager();
registration.register(
manager,
ApplyBrushCommandsRegistration.builder(),
new ApplyBrushCommands()
);
builder.condition(new PermissionCondition(ImmutableSet.of("worldedit.brush.apply")));
builder.addParts(REGION_FACTORY, RADIUS);
builder.addPart(SubCommandPart.builder(TranslatableComponent.of("type"), TextComponent.of("Type of brush to use"))
.withCommands(manager.getAllCommands().collect(Collectors.toList()))
.required()
.build());
});
}
private void setApplyBrush(CommandParameters parameters, Player player, LocalSession localSession,
Contextual<? extends RegionFunction> generatorFactory) throws WorldEditException {
double radius = requireNonNull(RADIUS.value(parameters).asSingle(double.class));
RegionFactory regionFactory = REGION_FACTORY.value(parameters).asSingle(RegionFactory.class);
BrushCommands.setOperationBasedBrush(player, localSession, radius,
new Apply(generatorFactory), regionFactory, "worldedit.brush.apply");
}
@Command(
name = "forest",
desc = "Plant trees"
)
public void forest(CommandParameters parameters,
Player player, LocalSession localSession,
@Arg(desc = "The type of tree to plant")
TreeGenerator.TreeType type) throws WorldEditException {
setApplyBrush(parameters, player, localSession, new TreeGeneratorFactory(type));
}
@Command(
name = "item",
desc = "Use an item"
)
@CommandPermissions("worldedit.brush.item")
public void item(CommandParameters parameters,
Player player, LocalSession localSession,
@Arg(desc = "The type of item to use")
BaseItem item,
@Arg(desc = "The direction in which the item will be applied", def = "up")
@Direction(includeDiagonals = true)
com.sk89q.worldedit.util.Direction direction) throws WorldEditException {
player.print(TextComponent.builder().append("WARNING: ", TextColor.RED, TextDecoration.BOLD)
.append("This brush simulates item usages. Its effects may not work on all platforms, may not be undo-able," +
" and may cause strange interactions with other mods/plugins. Use at your own risk.").build());
setApplyBrush(parameters, player, localSession, new ItemUseFactory(item, direction));
}
@Command(
name = "set",
desc = "Place a block"
)
public void set(CommandParameters parameters,
Player player, LocalSession localSession,
@Arg(desc = "The pattern of blocks to use")
Pattern pattern) throws WorldEditException {
setApplyBrush(parameters, player, localSession, new ReplaceFactory(pattern));
}
}

View File

@ -19,25 +19,23 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import com.boydti.fawe.config.BBC; import static com.sk89q.worldedit.command.util.Logging.LogMode.REGION;
import com.boydti.fawe.config.Commands;
import com.boydti.fawe.object.visitor.Fast2DIterator;
import com.boydti.fawe.util.chat.Message;
import com.sk89q.minecraft.util.commands.Command; import com.boydti.fawe.config.BBC;
import com.sk89q.minecraft.util.commands.CommandContext; import com.boydti.fawe.object.visitor.Fast2DIterator;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.command.util.Logging;
import com.sk89q.worldedit.command.util.WorldEditAsyncCommandBuilder;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.function.FlatRegionFunction; import com.sk89q.worldedit.function.FlatRegionFunction;
import com.sk89q.worldedit.function.FlatRegionMaskingFilter; import com.sk89q.worldedit.function.FlatRegionMaskingFilter;
import com.sk89q.worldedit.function.RegionFunction;
import com.sk89q.worldedit.function.biome.BiomeReplace; import com.sk89q.worldedit.function.biome.BiomeReplace;
import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.mask.Mask2D; import com.sk89q.worldedit.function.mask.Mask2D;
@ -45,106 +43,84 @@ import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.function.visitor.FlatRegionVisitor; import com.sk89q.worldedit.function.visitor.FlatRegionVisitor;
import com.sk89q.worldedit.function.visitor.RegionVisitor; import com.sk89q.worldedit.function.visitor.RegionVisitor;
import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.FlatRegion; import com.sk89q.worldedit.regions.FlatRegion;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.Regions; import com.sk89q.worldedit.regions.Regions;
import com.sk89q.worldedit.util.Countable;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.command.binding.Switch; import com.sk89q.worldedit.util.formatting.component.PaginationBox;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeData; import com.sk89q.worldedit.world.biome.BiomeData;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.registry.BiomeRegistry; import com.sk89q.worldedit.world.registry.BiomeRegistry;
import java.util.HashSet;
import java.util.ArrayList; import java.util.Set;
import java.util.Collection; import java.util.stream.Collectors;
import java.util.Collections; import org.enginehub.piston.annotation.Command;
import java.util.List; import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.Arg;
import org.enginehub.piston.annotation.param.ArgFlag;
import org.enginehub.piston.annotation.param.Switch;
/** /**
* Implements biome-related commands such as "/biomelist". * Implements biome-related commands such as "/biomelist".
*/ */
@Command(aliases = {}, desc = "Change, list and inspect biomes") @CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class)
public class BiomeCommands extends MethodCommands { public class BiomeCommands {
/** /**
* Create a new instance. * Create a new instance.
*
* @param worldEdit reference to WorldEdit
*/ */
public BiomeCommands(WorldEdit worldEdit) { public BiomeCommands() {
super(worldEdit);
}
private BiomeRegistry getBiomeRegistry() {
return worldEdit.getPlatformManager().queryCapability(Capability.GAME_HOOKS).getRegistries().getBiomeRegistry();
} }
@Command( @Command(
aliases = { "biomelist", "biomels" }, name = "biomelist",
usage = "[page]", aliases = { "biomels" },
desc = "Gets all biomes available.", desc = "Gets all biomes available."
max = 1
) )
@CommandPermissions("worldedit.biome.list") @CommandPermissions("worldedit.biome.list")
public void biomeList(Player player, CommandContext args) throws WorldEditException { public void biomeList(Actor actor,
int page; @ArgFlag(name = 'p', desc = "Page number.", def = "1")
int offset; int page) {
int count = 0; WorldEditAsyncCommandBuilder.createAndSendMessage(actor, () -> {
BiomeRegistry biomeRegistry = WorldEdit.getInstance().getPlatformManager()
.queryCapability(Capability.GAME_HOOKS).getRegistries().getBiomeRegistry();
if (args.argsLength() == 0 || (page = args.getInteger(0)) < 2) { PaginationBox paginationBox = PaginationBox.fromStrings("Available Biomes", "/biomelist -p %page%",
page = 1; BiomeType.REGISTRY.values().stream()
offset = 0; .map(biomeType -> {
} else { String id = biomeType.getId();
offset = (page - 1) * 19; final BiomeData data = biomeRegistry.getData(biomeType);
} if (data != null) {
String name = data.getName();
BiomeRegistry biomeRegistry = getBiomeRegistry(); return id + " (" + name + ")";
Collection<BiomeType> biomes = BiomeTypes.values(); } else {
int totalPages = biomes.size() / 19 + 1; return id;
Message msg = BBC.BIOME_LIST_HEADER.m(page, totalPages); }
String setBiome = Commands.getAlias(BiomeCommands.class, "/setbiome"); })
for (BiomeType biome : biomes) { .collect(Collectors.toList()));
if (offset > 0) { return paginationBox.create(page);
offset--; }, null);
} else {
BiomeData data = biomeRegistry.getData(biome);
if (data != null) {
msg.newline().text(data.getName()).cmdTip(setBiome + " " + data.getName());
} else {
msg.newline().text("<? #" + biome.getId() + ">").cmdTip(setBiome + " " + biome.getId());
}
if (++count == 18) {
break;
}
}
}
msg.newline().paginate(getCommand().aliases()[0], page, totalPages);
msg.send(player);
} }
@Command( @Command(
aliases = { "biomeinfo" }, name = "biomeinfo",
flags = "pt",
desc = "Get the biome of the targeted block.", desc = "Get the biome of the targeted block.",
help = descFooter = "By default, uses all blocks in your selection."
"Get the biome of the block.\n" +
"By default use all the blocks contained in your selection.\n" +
"-t use the block you are looking at.\n" +
"-p use the block you are currently in",
max = 0
) )
@CommandPermissions("worldedit.biome.info") @CommandPermissions("worldedit.biome.info")
public void biomeInfo(Player player, LocalSession session, final EditSession editSession, CommandContext args) throws WorldEditException { public void biomeInfo(Player player, LocalSession session, EditSession editSession,
BiomeRegistry biomeRegistry = getBiomeRegistry(); @Switch(name = 't', desc = "Use the block you are looking at.")
Collection<BiomeType> values = BiomeTypes.values(); boolean useLineOfSight,
final int[] biomes = new int[values.size()]; @Switch(name = 'p', desc = "Use the block you are currently in.")
boolean usePosition) throws WorldEditException {
BiomeRegistry biomeRegistry = WorldEdit.getInstance().getPlatformManager()
.queryCapability(Capability.GAME_HOOKS).getRegistries().getBiomeRegistry();
Set<BiomeType> biomes = new HashSet<>();
String qualifier;
int size = 0; if (useLineOfSight) {
if (args.hasFlag('t')) {
Location blockPosition = player.getBlockTrace(300); Location blockPosition = player.getBlockTrace(300);
if (blockPosition == null) { if (blockPosition == null) {
BBC.NO_BLOCK.send(player); BBC.NO_BLOCK.send(player);
@ -152,68 +128,56 @@ public class BiomeCommands extends MethodCommands {
} }
BiomeType biome = player.getWorld().getBiome(blockPosition.toBlockPoint().toBlockVector2()); BiomeType biome = player.getWorld().getBiome(blockPosition.toBlockPoint().toBlockVector2());
biomes[biome.getInternalId()]++; biomes.add(biome);
size = 1;
} else if (args.hasFlag('p')) { qualifier = "at line of sight point";
} else if (usePosition) {
BiomeType biome = player.getWorld().getBiome(player.getLocation().toBlockPoint().toBlockVector2()); BiomeType biome = player.getWorld().getBiome(player.getLocation().toBlockPoint().toBlockVector2());
biomes[biome.getInternalId()]++; biomes.add(biome);
size = 1;
qualifier = "at your position";
} else { } else {
World world = player.getWorld(); World world = player.getWorld();
Region region = session.getSelection(world); Region region = session.getSelection(world);
if (region instanceof FlatRegion) { if (region instanceof FlatRegion) {
for (BlockVector2 pt : new Fast2DIterator(((FlatRegion) region).asFlatRegion(), editSession)) { for (BlockVector2 pt : new Fast2DIterator(((FlatRegion) region).asFlatRegion(), editSession)) {
biomes[editSession.getBiome(pt).getInternalId()]++; biomes.add(world.getBiome(pt));
size++;
} }
} else { } else {
RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() { RegionVisitor visitor = new RegionVisitor(region, position -> {
@Override biomes.add(world.getBiome(position.toBlockVector2()));
public boolean apply(BlockVector3 position) throws WorldEditException { return true;
biomes[editSession.getBiome(position.toBlockVector2()).getInternalId()]++;
return true;
}
}, editSession); }, editSession);
Operations.completeBlindly(visitor); Operations.completeBlindly(visitor);
size += visitor.getAffected();
} }
qualifier = "in your selection";
} }
BBC.BIOME_LIST_HEADER.send(player, 1, 1); BBC.BIOME_LIST_HEADER.send(player, 1, 1);
player.print(biomes.size() != 1 ? "Biomes " + qualifier + ":" : "Biome " + qualifier + ":");
List<Countable<BiomeType>> distribution = new ArrayList<>(); for (BiomeType biome : biomes) {
for (int i = 0; i < biomes.length; i++) { BiomeData data = biomeRegistry.getData(biome);
int count = biomes[i]; if (data != null) {
if (count != 0) { player.print(" " + data.getName());
distribution.add(new Countable<>(BiomeTypes.get(i), count)); } else {
player.print(" <unknown #" + biome.getId() + ">");
} }
} }
Collections.sort(distribution);
for (Countable<BiomeType> c : distribution) {
BiomeData data = biomeRegistry.getData(c.getID());
String str = String.format("%-7s (%.3f%%) %s #%d",
String.valueOf(c.getAmount()),
c.getAmount() / (double) size * 100,
data == null ? "Unknown" : data.getName(),
c.getID().getInternalId());
player.print(str);
}
} }
@Command( @Command(
aliases = { "/setbiome" }, name = "/setbiome",
usage = "<biome>", desc = "Sets the biome of your current block or region.",
flags = "p", descFooter = "By default, uses all the blocks in your selection"
desc = "Sets the biome of the player's current block or region.",
help =
"Set the biome of the region.\n" +
"By default use all the blocks contained in your selection.\n" +
"-p use the block you are currently in"
) )
@Logging(REGION) @Logging(REGION)
@CommandPermissions("worldedit.biome.set") @CommandPermissions("worldedit.biome.set")
public void setBiome(Player player, LocalSession session, EditSession editSession, BiomeType target, @Switch('p') boolean atPosition) throws WorldEditException { public void setBiome(Player player, LocalSession session, EditSession editSession,
@Arg(desc = "Biome type.") BiomeType target,
@Switch(name = 'p', desc = "Use your current position")
boolean atPosition) throws WorldEditException {
World world = player.getWorld(); World world = player.getWorld();
Region region; Region region;
Mask mask = editSession.getMask(); Mask mask = editSession.getMask();
@ -233,8 +197,9 @@ public class BiomeCommands extends MethodCommands {
Operations.completeLegacy(visitor); Operations.completeLegacy(visitor);
BBC.BIOME_CHANGED.send(player, visitor.getAffected()); BBC.BIOME_CHANGED.send(player, visitor.getAffected());
if (!player.hasPermission("fawe.tips")) if (!player.hasPermission("fawe.tips")) {
BBC.TIP_BIOME_PATTERN.or(BBC.TIP_BIOME_MASK).send(player); BBC.TIP_BIOME_PATTERN.or(BBC.TIP_BIOME_MASK).send(player);
}
} }
} }

View File

@ -11,30 +11,27 @@ import com.boydti.fawe.object.extent.ResettableExtent;
import com.boydti.fawe.object.io.PGZIPOutputStream; import com.boydti.fawe.object.io.PGZIPOutputStream;
import com.boydti.fawe.util.MainUtil; import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.MathMan; import com.boydti.fawe.util.MathMan;
import com.sk89q.minecraft.util.commands.Command;
import org.enginehub.piston.annotation.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalSession; import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.blocks.BaseItem;
import com.sk89q.worldedit.command.tool.BrushTool; import com.sk89q.worldedit.command.tool.BrushTool;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.platform.CommandEvent; import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.extension.input.ParserContext; import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.CommandManager; import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.util.HandSide; import com.sk89q.worldedit.util.HandSide;
import com.sk89q.worldedit.util.command.binding.Range; import com.sk89q.worldedit.util.command.binding.Range;
import com.sk89q.worldedit.util.command.binding.Switch; import com.sk89q.worldedit.util.command.binding.Switch;
import com.sk89q.worldedit.util.command.parametric.Optional; import com.sk89q.worldedit.util.command.parametric.Optional;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
@ -163,16 +160,14 @@ public class BrushOptionsCommands extends MethodCommands {
max = 0 max = 0
) )
public void none(Player player, LocalSession session, CommandContext args) throws WorldEditException { public void none(Player player, LocalSession session, CommandContext args) throws WorldEditException {
session.setTool(null, player); session.setTool(player, null);
BBC.TOOL_NONE.send(player); BBC.TOOL_NONE.send(player);
} }
@Command( @Command(
aliases = {"/", ","}, aliases = {"/", ","},
usage = "[on|off]", usage = "[on|off]",
desc = "Toggle the super pickaxe function", desc = "Toggle the super pickaxe function"
min = 0,
max = 1
) )
@CommandPermissions("worldedit.superpickaxe") @CommandPermissions("worldedit.superpickaxe")
public void togglePickaxe(Player player, LocalSession session, CommandContext args) throws WorldEditException { public void togglePickaxe(Player player, LocalSession session, CommandContext args) throws WorldEditException {
@ -210,8 +205,8 @@ public class BrushOptionsCommands extends MethodCommands {
session.setTool(item, null, player); session.setTool(item, null, player);
String cmd = "brush " + args.getJoinedStrings(0); String cmd = "brush " + args.getJoinedStrings(0);
CommandEvent event = new CommandEvent(player, cmd); CommandEvent event = new CommandEvent(player, cmd);
CommandManager.getInstance().handleCommandOnCurrentThread(event); PlatformCommandManager.getInstance().handleCommandOnCurrentThread(event);
BrushTool newTool = session.getBrushTool(item, player, false); BrushTool newTool = session.getBrushTool(item.getType(), player, false);
if (newTool != null && tool != null) { if (newTool != null && tool != null) {
newTool.setSecondary(tool.getSecondary()); newTool.setSecondary(tool.getSecondary());
} }
@ -231,8 +226,8 @@ public class BrushOptionsCommands extends MethodCommands {
session.setTool(item, null, player); session.setTool(item, null, player);
String cmd = "brush " + args.getJoinedStrings(0); String cmd = "brush " + args.getJoinedStrings(0);
CommandEvent event = new CommandEvent(player, cmd); CommandEvent event = new CommandEvent(player, cmd);
CommandManager.getInstance().handleCommandOnCurrentThread(event); PlatformCommandManager.getInstance().handleCommandOnCurrentThread(event);
BrushTool newTool = session.getBrushTool(item, player, false); BrushTool newTool = session.getBrushTool(item.getType(), player, false);
if (newTool != null && tool != null) { if (newTool != null && tool != null) {
newTool.setPrimary(tool.getPrimary()); newTool.setPrimary(tool.getPrimary());
} }

Some files were not shown because too many files have changed in this diff Show More