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,13 +38,14 @@ println """
*******************************************
"""
group = 'com.boydti.fawe'
allprojects {
group = 'com.boydti.fawe'
def rootVersion = "1.13"
def revision = ""
def buildNumber = ""
def date = ""
ext {
def rootVersion = "1.13"
def revision = ""
def buildNumber = ""
def date = ""
ext {
git = Grgit.open(dir: '.git')
date = git.head().getDate().format("yy.MM.dd")
revision = "-${git.head().abbreviatedId}"
@ -58,10 +59,10 @@ ext {
}
buildNumber = "${index}"
}
}
version = String.format("%s.%s", rootVersion, buildNumber)
}
version = String.format("%s.%s", rootVersion, buildNumber)
description = rootProject.name
subprojects {
@ -97,6 +98,7 @@ configure(['worldedit-core', 'worldedit-bukkit', 'favs'].collect { project("$it"
apply plugin: 'maven'
// apply plugin: 'checkstyle'
apply plugin: 'com.github.johnrengelman.shadow'
// apply plugin: 'com.jfrog.artifactory'
// Enable this requires putting license header files in many, many FAWE files
// 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) {
classifier = 'sources'
from sourceSets.main.allSource
@ -131,6 +133,11 @@ configure(['worldedit-core', 'worldedit-bukkit', 'favs'].collect { project("$it"
// build.dependsOn(checkstyleMain)
// build.dependsOn(checkstyleTest)
// build.dependsOn(javadocJar)
//
// artifactoryPublish {
// publishConfigs('archives')
// }
dependencies {
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.world.block.BlockTypes;
import com.thevoxelbox.voxelsniper.brush.IBrush;
import com.thevoxelbox.voxelsniper.brush.JockeyBrush;
import com.thevoxelbox.voxelsniper.brush.SnipeBrush;
import com.thevoxelbox.voxelsniper.brush.perform.PerformBrush;
import com.thevoxelbox.voxelsniper.brush.perform.Performer;
@ -201,7 +202,7 @@ public class Sniper {
changeQueue = new ChangeSetFaweQueue(changeSet, maskQueue);
}
LocalSession session = fp.getSession();
{ // Set mask etc
// Set mask etc
Mask destMask = session.getMask();
if (!Masks.isNull(destMask)) {
new MaskTraverser(destMask).reset(changeQueue);
@ -217,7 +218,6 @@ public class Sniper {
transform.setExtent(changeQueue);
changeQueue = new FaweQueueDelegateExtent(changeQueue, transform);
}
}
AsyncWorld world = getWorld();
world.changeWorld(bukkitWorld, changeQueue);
@ -369,22 +369,19 @@ public class Sniper {
snipeData.setExtent(world);
Request.reset();
Request.request().setExtent(world);
switch (brush.getClass().getSimpleName()) {
case "JockeyBrush":
if (brush instanceof JockeyBrush) {
TaskManager.IMP.sync(new RunnableVal<Object>() {
@Override
public void run(Object value) {
brush.perform(snipeAction, snipeData, targetBlock, lastBlock);
}
});
break;
default:
} else {
if (sniperTool.getCurrentBrush() instanceof PerformBrush) {
PerformBrush performerBrush = (PerformBrush) sniperTool.getCurrentBrush();
performerBrush.initP(snipeData);
}
brush.perform(snipeAction, snipeData, targetBlock, lastBlock);
break;
}
} finally {
snipeData.setExtent(null);

View File

@ -3,7 +3,7 @@ package com.thevoxelbox.voxelsniper;
import com.boydti.fawe.config.BBC;
import com.boydti.fawe.object.FawePlayer;
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.thevoxelbox.voxelsniper.api.command.VoxelCommand;
import com.thevoxelbox.voxelsniper.command.*;
@ -71,7 +71,7 @@ public class VoxelSniperListener implements Listener {
FawePlayer fp = FawePlayer.wrap(player);
if (!fp.runAction(() -> {
ExceptionConverter exceptionConverter = CommandManager.getInstance().getExceptionConverter();
ExceptionConverter exceptionConverter = PlatformCommandManager.getInstance().getExceptionConverter();
try {
try {
found.onCommand(player, split);

View File

@ -37,8 +37,6 @@ dependencies {
compile 'com.thevoxelbox.voxelsniper:voxelsniper:5.171.0'
compile 'com.comphenix.protocol:ProtocolLib-API:4.4.0-SNAPSHOT'
compile 'com.wasteofplastic:askyblock:3.0.8.2'
compileOnly 'com.sk89q.worldguard:worldguard-core:7.0.0-20190215.210421-39'
compileOnly 'com.sk89q.worldguard:worldguard-legacy:7.0.0-20190215.210421-39'
}
processResources {
@ -49,6 +47,10 @@ processResources {
)
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"

View File

@ -3,22 +3,10 @@ package com.boydti.fawe.bukkit;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.IFawe;
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.BukkitImageListener;
import com.boydti.fawe.bukkit.listener.RenderListener;
import com.boydti.fawe.bukkit.listener.SyncTabCompleteListener;
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.regions.*;
import com.boydti.fawe.bukkit.util.BukkitReflectionUtils;
import com.boydti.fawe.bukkit.util.BukkitTaskMan;
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.TaskManager;
import com.boydti.fawe.util.image.ImageViewer;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.world.World;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
@ -127,18 +115,6 @@ public class FaweBukkit implements IFawe, Listener {
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() {
final Plugin worldguardPlugin = Bukkit.getServer().getPluginManager().getPlugin("WorldGuard");
final ArrayList<FaweMaskManager> managers = new ArrayList<>();
if ((worldguardPlugin != null) && worldguardPlugin.isEnabled()) {
if (worldguardPlugin != null && worldguardPlugin.isEnabled()) {
try {
managers.add(new Worldguard(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");
if ((townyPlugin != null) && townyPlugin.isEnabled()) {
if (townyPlugin != null && townyPlugin.isEnabled()) {
try {
managers.add(new TownyFeature(townyPlugin, this));
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");
if ((factionsPlugin != null) && factionsPlugin.isEnabled()) {
if (factionsPlugin != null && factionsPlugin.isEnabled()) {
try {
managers.add(new FactionsFeature(factionsPlugin));
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");
if ((residencePlugin != null) && residencePlugin.isEnabled()) {
if (residencePlugin != null && residencePlugin.isEnabled()) {
try {
managers.add(new ResidenceFeature(residencePlugin, this));
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");
if ((griefpreventionPlugin != null) && griefpreventionPlugin.isEnabled()) {
if (griefpreventionPlugin != null && griefpreventionPlugin.isEnabled()) {
try {
managers.add(new GriefPreventionFeature(griefpreventionPlugin));
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");
if ((preciousstonesPlugin != null) && preciousstonesPlugin.isEnabled()) {
if (preciousstonesPlugin != null && preciousstonesPlugin.isEnabled()) {
try {
managers.add(new PreciousStonesFeature(preciousstonesPlugin, this));
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");
if ((aSkyBlock != null) && aSkyBlock.isEnabled()) {
if (aSkyBlock != null && aSkyBlock.isEnabled()) {
try {
managers.add(new ASkyBlockHook(aSkyBlock));
Fawe.debug("Plugin 'ASkyBlock' found. Using it now.");
@ -492,20 +468,6 @@ public class FaweBukkit implements IFawe, Listener {
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)
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;
import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.object.brush.MovableTool;
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.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.Plugin;
public class BrushListener implements Listener {
@ -47,16 +44,7 @@ public class BrushListener implements Listener {
}
ScrollTool scrollable = (ScrollTool) tool;
if (scrollable.increment(player, ri)) {
if (Settings.IMP.EXPERIMENTAL.PERSISTENT_BRUSHES) {
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;
public class BukkitImageListener implements Listener {
private Location mutable = new Location(Bukkit.getWorlds().get(0), 0, 0, 0);
public BukkitImageListener(Plugin plugin) {
@ -61,19 +62,20 @@ public class BukkitImageListener implements Listener {
Iterator<Player> iter = recipients.iterator();
while (iter.hasNext()) {
Player player = iter.next();
if (player.equals(event.getPlayer())) continue;
FawePlayer<Object> fp = FawePlayer.wrap(player);
if (!fp.hasMeta()) continue;
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();
if (!event.getMessage().toLowerCase().contains(name)) {
ArrayDeque<String> buffered = fp.getMeta("CFIBufferedMessages");
if (buffered == null) fp.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque<>());
String full = String.format(event.getFormat(), event.getPlayer().getDisplayName(), event.getMessage());
if (buffered == null) {
fp.setMeta("CFIBufferedMessaged", buffered = new ArrayDeque<>());
}
String full = String.format(event.getFormat(), event.getPlayer().getDisplayName(),
event.getMessage());
buffered.add(full);
iter.remove();
}
@ -82,29 +84,42 @@ public class BukkitImageListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
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);
}
@EventHandler(priority = EventPriority.LOWEST)
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);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.useItemInHand() == Event.Result.DENY) return;
if (event.useItemInHand() == Event.Result.DENY) {
return;
}
Player player = event.getPlayer();
FawePlayer<Object> fp = FawePlayer.wrap(player);
if (fp.getMeta("CFISettings") == null) return;
if (fp.getMeta("CFISettings") == null) {
return;
}
try {
if (event.getHand() == EquipmentSlot.OFF_HAND) return;
} catch (NoSuchFieldError | NoSuchMethodError ignored) {}
if (event.getHand() == EquipmentSlot.OFF_HAND) {
return;
}
} catch (NoSuchFieldError | NoSuchMethodError ignored) {
}
List<Block> target = player.getLastTwoTargetBlocks(null, 100);
if (target.isEmpty()) return;
if (target.isEmpty()) {
return;
}
Block targetBlock = target.get(0);
World world = player.getWorld();
@ -116,7 +131,8 @@ public class BukkitImageListener implements Listener {
if (!entities.isEmpty()) {
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;
ItemFrame minItemFrame = null;
@ -137,7 +153,9 @@ public class BukkitImageListener implements Listener {
}
if (minItemFrame != null) {
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) {
if (generator == null) return null;
if (generator == null) {
return null;
}
ImageViewer viewer = generator.getImageViewer();
if (!(viewer instanceof BukkitImageViewer)) return null;
if (!(viewer instanceof BukkitImageViewer)) {
return null;
}
return (BukkitImageViewer) viewer;
}
@ -161,14 +183,18 @@ public class BukkitImageListener implements Listener {
}
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;
FawePlayer<Object> fp = FawePlayer.wrap(player);
CFICommands.CFISettings settings = fp.getMeta("CFISettings");
HeightMapMCAGenerator generator = settings == null ? null : settings.getGenerator();
BukkitImageViewer viewer = get(generator);
if (viewer == null) return;
if (viewer == null) {
return;
}
if (itemFrame.getRotation() != Rotation.NONE) {
itemFrame.setRotation(Rotation.NONE);
@ -178,7 +204,9 @@ public class BukkitImageListener implements Listener {
BrushTool tool;
try {
tool = session.getBrushTool(fp.getPlayer(), false);
} catch (InvalidToolBindException e) { return; }
} catch (InvalidToolBindException e) {
return;
}
ItemFrame[][] frames = viewer.getItemFrames();
if (frames == null || tool == null) {
@ -190,7 +218,9 @@ public class BukkitImageListener implements Listener {
BrushSettings context = primary ? tool.getPrimary() : tool.getSecondary();
Brush brush = context.getBrush();
if (brush == null) return;
if (brush == null) {
return;
}
tool.setContext(context);
if (event instanceof Cancellable) {
@ -208,7 +238,7 @@ public class BukkitImageListener implements Listener {
double zRat = Math.sin(yawRad) * a;
BlockFace facing = itemFrame.getFacing();
double thickness = 1/32D + 1/128D;
double thickness = 1 / 32D + 1 / 128D;
double modX = facing.getModX();
double modZ = facing.getModZ();
double dx = source.getX() - target.getX() - modX * thickness;
@ -225,8 +255,8 @@ public class BukkitImageListener implements Listener {
localX = (modZ) * (dx - offset * xRat);
}
double localY = dy - offset * Math.sin(pitchRad);
int localPixelX = (int)((localX + 0.5) * 128);
int localPixelY = (int)((localY + 0.5) * 128);
int localPixelX = (int) ((localX + 0.5) * 128);
int localPixelY = (int) ((localY + 0.5) * 128);
UUID uuid = itemFrame.getUniqueId();
for (int blockX = 0; blockX < frames.length; blockX++) {
@ -240,18 +270,25 @@ public class BukkitImageListener implements Listener {
int worldX = (int) (pixelX * width / (frames.length * 128d));
int worldZ = (int) (pixelY * length / (frames[0].length * 128d));
if (worldX < 0 || worldX > width || worldZ < 0 || worldZ > length) return;
if (worldX < 0 || worldX > width || worldZ < 0 || worldZ > length) {
return;
}
fp.runAction(() -> {
BlockVector3 wPos = BlockVector3.at(worldX, 0, worldZ);
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);
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();
if (last.get() instanceof FastWorldEditExtent) last = last.previous();
if (last.get() instanceof FastWorldEditExtent) {
last = last.previous();
}
last.setNext(generator);
try {
brush.build(es, wPos, context.getMaterial(), context.getSize());
@ -262,9 +299,6 @@ public class BukkitImageListener implements Listener {
viewer.view(generator);
}, true, true);
return;
}
}

View File

@ -2,7 +2,6 @@ package com.boydti.fawe.bukkit.listener;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.util.TaskManager;
import java.util.Iterator;
import java.util.Map;
@ -14,7 +13,9 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.plugin.Plugin;
@ -46,7 +47,6 @@ public class RenderListener implements Listener {
OFFSET = 8;
timeOut = 2;
} else {
int tpsSqr = tps32 * tps32;
OFFSET = 1 + (tps32 / 102400);
timeOut = 162 - (tps32 / 2560);
}
@ -75,7 +75,7 @@ public class RenderListener implements Listener {
}, 1);
}
public void setViewDistance(Player player, int value) {
private void setViewDistance(Player player, int value) {
UUID uuid = player.getUniqueId();
if (value == Settings.IMP.EXPERIMENTAL.DYNAMIC_CHUNK_RENDERING) {
views.remove(uuid);
@ -99,7 +99,7 @@ public class RenderListener implements Listener {
player.setViewDistance(value);
}
public int getViewDistance(Player player) {
private int getViewDistance(Player player) {
int[] value = views.get(player.getUniqueId());
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)
public void onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent event) {
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
setViewDistance(player, 1);
FawePlayer fp = FawePlayer.wrap(player);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerLeave(org.bukkit.event.player.PlayerQuitEvent event) {
public void onPlayerLeave(PlayerQuitEvent event) {
Player player = event.getPlayer();
UUID uid = player.getUniqueId();
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;
}
@Override
public FaweQueue getQueue() {
return queue;
}
@ -174,6 +175,7 @@ public class AsyncWorld extends DelegateFaweQueue implements World, HasFaweQueue
return wrap(world);
}
@Override
public Operation commit() {
flush();
return null;

View File

@ -19,7 +19,7 @@
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.CommandsManager;
import org.bukkit.command.CommandExecutor;
@ -31,6 +31,8 @@ import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Deprecated
@SuppressWarnings("deprecation")
public class CommandsManagerRegistration extends CommandRegistration {
protected CommandsManager<?> commands;

View File

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

View File

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

View File

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

View File

@ -21,31 +21,25 @@ package com.sk89q.worldedit.bukkit;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Function;
import com.sk89q.worldedit.NotABlockException;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.IBukkitAdapter;
import com.sk89q.worldedit.bukkit.adapter.SimpleBukkitAdapter;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldedit.world.item.ItemType;
import org.bukkit.Material;
import org.bukkit.block.Biome;
import org.bukkit.block.data.BlockData;
@ -74,6 +68,12 @@ public enum BukkitAdapter {
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
*
@ -112,6 +112,26 @@ public enum BukkitAdapter {
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.
*
@ -134,10 +154,24 @@ public enum BukkitAdapter {
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) {
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) {
checkNotNull(world);
checkNotNull(position);
@ -157,19 +191,26 @@ public enum BukkitAdapter {
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.
*
* @param location The Bukkit location
* @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) {
checkNotNull(location);
return getAdapter().asBlockVector(location);
return BlockVector3.at(location.getX(), location.getY(), location.getZ());
}
/**
@ -329,12 +370,4 @@ public enum BukkitAdapter {
checkNotNull(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);
return bukkitBiome == null ? null : bukkitBiome::name;
}
}

View File

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

View File

@ -23,7 +23,6 @@ import com.boydti.fawe.Fawe;
import com.boydti.fawe.bukkit.FaweBukkit;
import com.boydti.fawe.object.RunnableVal;
import com.boydti.fawe.util.TaskManager;
import com.sk89q.util.StringUtil;
import com.sk89q.worldedit.WorldEdit;
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.session.SessionKey;
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.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.gamemode.GameMode;
import com.sk89q.worldedit.world.gamemode.GameModes;
import 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.Location;
import org.bukkit.Material;
@ -53,11 +59,6 @@ import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class BukkitPlayer extends AbstractPlayerActor {
private Player player;
@ -162,6 +163,11 @@ public class BukkitPlayer extends AbstractPlayerActor {
}
}
@Override
public void print(Component component) {
TextAdapter.sendComponent(player, component);
}
@Override
public void setPosition(Vector3 pos, float pitch, float yaw) {
if (pos instanceof com.sk89q.worldedit.util.Location) {
@ -187,12 +193,12 @@ public class BukkitPlayer extends AbstractPlayerActor {
@Override
public GameMode getGameMode() {
return GameModes.get(player.getGameMode().name().toLowerCase());
return GameModes.get(player.getGameMode().name().toLowerCase(Locale.ROOT));
}
@Override
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

View File

@ -19,29 +19,32 @@
package com.sk89q.worldedit.bukkit;
import static com.sk89q.worldedit.bukkit.BukkitTextAdapter.reduceToText;
import com.sk89q.bukkit.util.CommandInfo;
import com.sk89q.bukkit.util.CommandRegistration;
import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.command.util.PermissionCondition;
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.MultiUserPlatform;
import com.sk89q.worldedit.extension.platform.Preference;
import com.sk89q.worldedit.util.command.CommandMapping;
import com.sk89q.worldedit.util.command.Description;
import com.sk89q.worldedit.util.command.Dispatcher;
import com.sk89q.worldedit.world.DataFixer;
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.Collection;
import java.util.EnumMap;
import java.util.List;
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 Server server;
@ -64,6 +67,22 @@ public class BukkitServerInterface implements MultiUserPlatform {
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
public boolean isValidMobType(String type) {
final EntityType entityType = EntityType.fromName(type);
@ -115,20 +134,25 @@ public class BukkitServerInterface implements MultiUserPlatform {
}
@Override
public void registerCommands(Dispatcher dispatcher) {
List<CommandInfo> toRegister = new ArrayList<>();
public void registerCommands(CommandManager dispatcher) {
BukkitCommandInspector inspector = new BukkitCommandInspector(plugin, dispatcher);
for (CommandMapping command : dispatcher.getCommands()) {
Description description = command.getDescription();
List<String> permissions = description.getPermissions();
String[] permissionsArray = new String[permissions.size()];
permissions.toArray(permissionsArray);
dynamicCommands.register(dispatcher.getAllCommands()
.map(command -> {
String[] permissionsArray = command.getCondition()
.as(PermissionCondition.class)
.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));
}
dynamicCommands.register(toRegister);
String[] aliases = Stream.concat(
Stream.of(command.getName()),
command.getAliases().stream()
).toArray(String[]::new);
return new CommandInfo(reduceToText(command.getUsage()),
reduceToText(command.getDescription()), aliases,
inspector, permissionsArray);
}).collect(Collectors.toList()));
}
@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;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEdit;
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.weather.WeatherType;
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.TreeType;
import org.bukkit.World;
@ -47,16 +56,9 @@ import org.bukkit.block.Chest;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.DoubleChestInventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
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 {
private static final Logger logger = WorldEdit.logger;
@ -154,6 +156,11 @@ public class BukkitWorld extends AbstractWorld {
return getWorld().getName();
}
@Override
public Path getStoragePath() {
return getWorld().getWorldFolder().toPath();
}
@Override
public int getBlockLightLevel(BlockVector3 pt) {
return getWorld().getBlockAt(pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()).getLightLevel();
@ -239,11 +246,11 @@ public class BukkitWorld extends AbstractWorld {
return false;
}
BlockState state = block.getState();
if (!(state instanceof org.bukkit.inventory.InventoryHolder)) {
if (!(state instanceof InventoryHolder)) {
return false;
}
org.bukkit.inventory.InventoryHolder chest = (org.bukkit.inventory.InventoryHolder) state;
InventoryHolder chest = (InventoryHolder) state;
Inventory inven = chest.getInventory();
if (chest instanceof Chest) {
inven = getBlockInventory((Chest) chest);
@ -311,10 +318,13 @@ public class BukkitWorld extends AbstractWorld {
@Override
public boolean equals(Object other) {
if (other == null) {
if (worldRef.get() == null) {
return false;
} else if (other == null) {
return false;
} 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) {
return ((com.sk89q.worldedit.world.World) other).getName().equals(getName());
} else {

View File

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

View File

@ -21,14 +21,10 @@
package com.sk89q.worldedit.bukkit;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.util.StringUtil;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.command.CommandMapping;
import com.sk89q.worldedit.util.command.Dispatcher;
import com.sk89q.worldedit.world.World;
import org.bukkit.block.Block;
import org.bukkit.event.Event.Result;
@ -36,14 +32,16 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerCommandSendEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import 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.stream.Collectors;
import java.util.Optional;
/**
* Handles all events thrown in relation to a Player
@ -52,12 +50,6 @@ public class WorldEditListener implements Listener {
private WorldEditPlugin plugin;
/**
* Called when a player plays an animation, such as an arm swing
*
* @param event Relevant event details
*/
/**
* Construct the object;
*
@ -77,48 +69,18 @@ public class WorldEditListener implements Listener {
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)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
String[] split = event.getMessage().split(" ");
if (split.length > 0) {
split[0] = split[0].substring(1);
split = plugin.getWorldEdit().getPlatformManager().getCommandManager().commandDetection(split);
}
final String newMessage = "/" + StringUtil.joinString(split, " ");
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);
}
public void onPlayerCommandSend(PlayerCommandSendEvent event) {
InjectedValueStore store = MapBackedValueStore.create();
store.injectValue(Key.of(Actor.class), context ->
Optional.of(plugin.wrapCommandSender(event.getPlayer())));
CommandManager commandManager = plugin.getWorldEdit().getPlatformManager().getPlatformCommandManager().getCommandManager();
event.getCommands().removeIf(name ->
// remove if in the manager and not satisfied
commandManager.getCommand(name)
.filter(command -> !command.getCondition().satisfied(store))
.isPresent()
);
}
/**
@ -136,12 +98,8 @@ public class WorldEditListener implements Listener {
return;
}
try {
if (event.getHand() == EquipmentSlot.OFF_HAND) {
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) {
return;
}
final Player player = plugin.wrapPlayer(event.getPlayer());
@ -167,7 +125,6 @@ public class WorldEditListener implements Listener {
event.setCancelled(true);
}
} else if (action == Action.RIGHT_CLICK_BLOCK) {
final Block clickedBlock = event.getClickedBlock();
final Location pos = new Location(world, clickedBlock.getX(), clickedBlock.getY(), clickedBlock.getZ());

View File

@ -19,8 +19,6 @@
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.bukkit.FaweBukkit;
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.BukkitImplLoader;
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.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.Platform;
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.block.BlockCategory;
import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.item.ItemCategory;
import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.registry.LegacyMapper;
import io.papermc.lib.PaperLib;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Tag;
@ -55,6 +56,8 @@ import org.bukkit.block.Biome;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
@ -75,6 +78,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.jar.JarFile;
import java.util.logging.Level;
@ -192,10 +196,11 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
// Now we can register events
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());
// 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());
}
}
PaperLib.suggestPaper(this);
}
public void setupRegistries() {
@ -228,11 +235,12 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
).toImmutableState();
BlockState defaultState = blockState.getBlockType().getAllStates().get(0);
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;
} catch (InputParseException e) {
e.printStackTrace();
getLogger().log(Level.WARNING, "Error loading block state for " + material.getKey(), e);
return blockState;
}
}));
@ -260,7 +268,7 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
for (Tag<Material> itemTag : Bukkit.getTags(Tag.REGISTRY_ITEMS, Material.class)) {
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.");
}
}
@ -554,4 +562,32 @@ public class WorldEditPlugin extends JavaPlugin { //implements TabCompleter
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.math.BlockVector3;
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.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
@ -44,6 +45,21 @@ import javax.annotation.Nullable;
*/
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.
*

View File

@ -52,7 +52,7 @@ public class BukkitImplLoader {
"**\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" +
"** and biome-related functions.\n" +
"** and block property-related functions.\n" +
"**\n" +
"** Please see http://wiki.sk89q.com/wiki/WorldEdit/Bukkit_adapters\n" +
"**********************************************\n";
@ -160,9 +160,6 @@ public class BukkitImplLoader {
if (cls.isSynthetic()) continue;
if (BukkitImplAdapter.class.isAssignableFrom(cls)) {
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) {
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 +
"' that is not supposed to be raising this error", e);
} catch (Throwable e) {
e.printStackTrace();
if (className.equals(customCandidate)) {
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) {
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.pattern.DefaultPatternParser;
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.extent.Extent;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
@ -152,7 +152,7 @@ public class FaweAPI {
* @param aliases The aliases to give the command (or none)
*/
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;
import com.boydti.fawe.Fawe;
import static com.google.common.base.Preconditions.checkNotNull;
import com.boydti.fawe.FaweAPI;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.config.BBC;
import com.boydti.fawe.jnbt.anvil.*;
import com.boydti.fawe.jnbt.anvil.filters.*;
import com.boydti.fawe.jnbt.anvil.MCAClipboard;
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.NullAnvilHistory;
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.changeset.AnvilHistory;
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.SetQueue;
import com.boydti.fawe.util.StringMan;
import com.sk89q.minecraft.util.commands.Command;
import org.enginehub.piston.annotation.Command;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.pattern.RandomPattern;
import com.sk89q.worldedit.internal.annotation.Selection;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
@ -33,15 +45,10 @@ import com.sk89q.worldedit.util.command.binding.Switch;
import com.sk89q.worldedit.util.command.parametric.Optional;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;
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)")
public class AnvilCommands {
@ -139,9 +146,7 @@ public class AnvilCommands {
desc = "Replace all blocks in the selection with another",
help = "Replace all blocks in the selection with another\n" +
"The -d flag disabled wildcard data matching\n",
flags = "df",
min = 2,
max = 4
flags = "df"
)
@CommandPermissions("worldedit.anvil.replaceall")
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"},
usage = "<folder>",
help = "Remap the world between MCPE/PC values",
desc = "Remap the world between MCPE/PC values",
min = 1,
max = 1
desc = "Remap the world between MCPE/PC values"
)
@CommandPermissions("worldedit.anvil.remapall")
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" +
"Have not been accessed since `file-duration` (ms) after creation and\n" +
"Have not been used in the past `chunk-inactivity` (ms)" +
"The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`",
min = 2,
max = 3
"The auto-save interval is the recommended value for `file-duration` and `chunk-inactivity`"
)
@CommandPermissions("worldedit.anvil.deleteallunvisited")
public void deleteAllUnvisited(Player player, String folder, int inhabitedTicks, @Optional("60000") int fileDurationMillis) throws WorldEditException {
@ -220,7 +221,7 @@ public class AnvilCommands {
}
@Command(
aliases = {"deleteunclaimed"},
name = "deleteunclaimed",
usage = "<age-ticks> [file-age=60000]",
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" +
@ -245,9 +246,7 @@ public class AnvilCommands {
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" +
"(months are not a unit of time)\n" +
"E.g. 8h5m12s\n",
min = 2,
max = 3
"E.g. 8h5m12s\n"
)
@CommandPermissions("worldedit.anvil.deletealloldregions")
public void deleteAllOldRegions(Player player, String folder, String time) throws WorldEditException {
@ -258,7 +257,7 @@ public class AnvilCommands {
}
@Command(
aliases = {"trimallplots", },
name = "trimallplots",
desc = "Trim chunks in a Plot World",
help = "Trim chunks in a Plot World\n" +
"Unclaimed chunks will be deleted\n" +
@ -278,7 +277,7 @@ public class AnvilCommands {
}
@Command(
aliases = {"deletebiomechunks", },
name = "deletebiomechunks",
desc = "Delete chunks matching a specific biome"
)
@CommandPermissions("worldedit.anvil.trimallair")
@ -289,7 +288,7 @@ public class AnvilCommands {
}
@Command(
aliases = {"trimallair", },
name = "trimallair",
desc = "Trim all air in the world"
)
@CommandPermissions("worldedit.anvil.trimallair")
@ -300,7 +299,7 @@ public class AnvilCommands {
}
@Command(
aliases = {"debugfixroads", },
name = "debugfixroads",
desc = "debug - do not use"
)
@CommandPermissions("worldedit.anvil.debugfixroads")
@ -314,9 +313,7 @@ public class AnvilCommands {
aliases = {"replaceallpattern", "reap", "repallpat"},
usage = "<folder> [from-block] <to-pattern>",
desc = "Replace all blocks in the selection with another",
flags = "dm",
min = 2,
max = 4
flags = "dm"
)
@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 {
@ -346,9 +343,7 @@ public class AnvilCommands {
aliases = {"countall"},
usage = "<folder> [hasSky] <id>",
desc = "Count all blocks in a world",
flags = "d",
min = 2,
max = 3
flags = "d"
)
@CommandPermissions("worldedit.anvil.countall")
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.object.FawePlayer;
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.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
@ -28,11 +28,8 @@ public class CFICommand extends MethodCommands {
}
@Command(
name = "cfi",
aliases = {"cfi", "createfromimage"},
usage = "",
min = 0,
max = -1,
anyFlags = true,
desc = "Start CreateFromImage"
)
@CommandPermissions("worldedit.anvil.cfi")
@ -51,32 +48,36 @@ public class CFICommand extends MethodCommands {
private void dispatch(FawePlayer fp, CFICommands.CFISettings settings, CommandContext context) throws CommandException {
if (!settings.hasGenerator()) {
switch (context.argsLength()) {
case 0: {
if (context.argsLength() == 0) {
String hmCmd = child.alias() + " ";
if (settings.image == null) {
hmCmd += "image";
} else {
hmCmd = Commands.getAlias(CFICommands.class, "heightmap") + " " + settings.imageArg;
hmCmd =
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")
.text("[HeightMap]").cmdTip(hmCmd).text(" - A heightmap like ")
.text("[this]").linkTip("http://i.imgur.com/qCd30MR.jpg")
.newline()
.text("&7[&aEmpty&7]").cmdTip(child.alias() + " empty").text("- An empty map of a specific size")
.text("[Empty]").cmdTip(child.alias() + " empty")
.text("- An empty map of a specific size")
.send(fp);
break;
}
default: {
} else {
String remaining = context.getJoinedStrings(0);
if (!dispatcher.contains(context.getString(0))) {
switch (context.argsLength()) {
case 1: {
String cmd = Commands.getAlias(CFICommands.class, "heightmap") + " " + context.getJoinedStrings(0);
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);
String cmd =
Commands.getAlias(CFICommands.class, "empty") + " " + context
.getJoinedStrings(0);
dispatcher.call(cmd, context.getLocals(), new String[0]);
return;
}
@ -84,16 +85,12 @@ public class CFICommand extends MethodCommands {
}
dispatcher.call(remaining, context.getLocals(), new String[0]);
}
}
} else {
switch (context.argsLength()) {
case 0:
if (context.argsLength() == 0) {
settings.setCategory("");
child.mainMenu(fp);
break;
default:
} else {
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.chat.Message;
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.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissions;
@ -72,10 +74,11 @@ import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import org.enginehub.piston.annotation.CommandContainer;
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 {
private final Dispatcher dispathcer;
@ -99,17 +102,14 @@ public class CFICommands extends MethodCommands {
@Command(
aliases = {"heightmap"},
usage = "<url>",
desc = "Start CFI with a height map as a base"
)
@CommandPermissions("worldedit.anvil.cfi")
public void heightmap(FawePlayer fp, FawePrimitiveBinding.ImageUri image, @Optional("1") double yscale) throws ParameterException {
if (yscale != 0) {
int[] raw = ((DataBufferInt) image.load().getRaster().getDataBuffer()).getData();
int[] table = new int[256];
for (int i = 0; i < table.length; i++) {
table[i] = Math.min(255, (int) (i * yscale));
}
int[] table = IntStream.range(0, 256).map(i -> Math.min(255, (int) (i * yscale)))
.toArray();
for (int i = 0; i < raw.length; i++) {
int color = raw[i];
int red = table[(color >> 16) & 0xFF];
@ -123,8 +123,7 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"empty"},
usage = "<width> <length>",
name = "empty",
desc = "Start CFI with an empty map as a base"
)
@CommandPermissions("worldedit.anvil.cfi")
@ -135,8 +134,7 @@ public class CFICommands extends MethodCommands {
private String generateName() {
DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH.mm.ss");
String data = df.format(new Date());
return data;
return df.format(new Date());
}
private void setup(HeightMapMCAGenerator generator, FawePlayer fp) {
@ -149,8 +147,7 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"brush"},
usage = "",
name = "brush",
desc = "Info about using brushes with CFI"
)
@CommandPermissions("worldedit.anvil.cfi")
@ -166,23 +163,23 @@ public class CFICommands extends MethodCommands {
} else {
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(
aliases = {"cancel", "exit"},
usage = "",
name = "cancel",
aliases = {"exit"},
desc = "Cancel creation"
)
@CommandPermissions("worldedit.anvil.cfi")
public void cancel(FawePlayer fp) throws ParameterException, IOException {
public void cancel(FawePlayer fp) {
getSettings(fp).remove();
fp.sendMessage("Cancelled!");
}
@Command(
aliases = {"done", "create"},
usage = "",
name = "done",
aliases = "create",
desc = "Create the world"
)
@CommandPermissions("worldedit.anvil.cfi")
@ -240,8 +237,7 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"column", "setcolumn"},
usage = "<pattern> [url|mask]",
name = "column",
desc = "Set the floor and main block"
)
@CommandPermissions("worldedit.anvil.cfi")
@ -256,8 +252,7 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"floor", "setfloor"},
usage = "<pattern> [url|mask]",
name = "floor",
desc = "Set the floor (default: grass)"
)
@CommandPermissions("worldedit.anvil.cfi")
@ -276,8 +271,7 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"main", "setmain"},
usage = "<pattern> [url|mask]",
name = "main",
desc = "Set the main block (default: stone)"
)
@CommandPermissions("worldedit.anvil.cfi")
@ -296,10 +290,10 @@ public class CFICommands extends MethodCommands {
}
@Command(
name = "overlay",
aliases = {"overlay", "setoverlay"},
usage = "<pattern> [url|mask]",
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"
)
@CommandPermissions("worldedit.anvil.cfi")
@ -314,9 +308,8 @@ public class CFICommands extends MethodCommands {
@Command(
aliases = {"smooth"},
usage = "<radius> <iterations> [image|mask]",
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" +
" - This supports smoothing snow layers (set the floor to 78:7)\n" +
" - A good value for radius and iterations would be 1 8."
@ -335,8 +328,7 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"snow"},
usage = "[image|mask]",
name = "snow",
desc = "Create some snow"
)
@CommandPermissions("worldedit.anvil.cfi")
@ -351,10 +343,9 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"biomepriority", "palettebiomepriority", "setpalettebiomepriority"},
usage = "[percent=50]",
name = "biomepriority",
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" +
"Above 50 will prefer to color with biomes\n" +
"Below 50 will prefer to color with blocks"
@ -366,10 +357,9 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"paletteblocks", "colorpaletterblocks", "setcolorpaletteblocks"},
usage = "<blocks|#clipboard|*>",
name = "paletteblocks",
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" +
"`#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 {
if (arg == null) {
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()
.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()
.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()
.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()
.text("&8< &7[&aBack&7]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "coloring"))
.text("< [Back]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "coloring"))
.send(fp);
return;
}
@ -444,10 +434,9 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"randomization", "paletterandomization"},
usage = "<true|false>",
name = "randomization",
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" +
"Randomization will allow mixing biomes when coloring with biomes"
)
@ -458,10 +447,9 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"complexity", "palettecomplexity"},
usage = "<minPercent> <maxPercent>",
name = "complexity",
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" +
"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."
@ -475,10 +463,9 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"schem", "schematic", "schems", "schematics", "addschems"},
usage = "[url] <mask> <file|folder|url> <rarity> <distance> <rotate=true>",
name = "schem",
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" +
" - The rarity is a value between 0 and 100.\n" +
" - The distance is the spacing between each schematic"
@ -502,10 +489,9 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"biome", "setbiome"},
usage = "<biome> [image|mask]",
name = "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)" +
" - 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"
@ -522,7 +508,7 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"caves", "addcaves"},
name = "caves",
desc = "Generate vanilla caves"
)
@CommandPermissions("worldedit.anvil.cfi")
@ -533,10 +519,9 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"ore", "addore"},
usage = "<mask=stone> <pattern> <size> <frequency> <rarity> <minY> <maxY>",
name = "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")
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(
aliases = {"ores", "addores"},
usage = "<mask=stone>",
name = "ores",
desc = "Generate the vanilla ores"
)
@CommandPermissions("worldedit.anvil.cfi")
@ -558,10 +542,9 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"height", "setheight"},
usage = "<height|image>",
name = "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")
public void height(FawePlayer fp, String arg) throws ParameterException, WorldEditException {
@ -576,10 +559,8 @@ public class CFICommands extends MethodCommands {
}
@Command(
aliases = {"water", "waterid"},
usage = "<block>",
desc = "Change the block used for water\n" +
"e.g. Lava"
name = "water",
desc = "Change the block used for water\ne.g. Lava"
)
@CommandPermissions("worldedit.anvil.cfi")
public void waterId(FawePlayer fp, BlockStateHolder block) throws ParameterException, WorldEditException {
@ -592,9 +573,7 @@ public class CFICommands extends MethodCommands {
@Command(
aliases = {"baseid", "bedrockid"},
usage = "<block>",
desc = "Change the block used for the base\n" +
"e.g. Bedrock"
desc = "Change the block used for the base\ne.g. Bedrock"
)
@CommandPermissions("worldedit.anvil.cfi")
public void baseId(FawePlayer fp, BlockStateHolder block) throws ParameterException, WorldEditException {
@ -607,7 +586,6 @@ public class CFICommands extends MethodCommands {
@Command(
aliases = {"worldthickness", "width", "thickness"},
usage = "<height>",
desc = "Set the thickness of the generated world\n" +
" - A value of 0 is the default and will not modify the height"
)
@ -620,7 +598,6 @@ public class CFICommands extends MethodCommands {
@Command(
aliases = {"floorthickness", "floorheight", "floorwidth"},
usage = "<height>",
desc = "Set the thickness of the top layer\n" +
" - A value of 0 is the default and will only set the top block"
)
@ -659,7 +636,6 @@ public class CFICommands extends MethodCommands {
@Command(
aliases = {"waterheight", "sealevel", "setwaterheight"},
usage = "<height>",
desc = "Set the level water is generated at\n" +
"Set the level water is generated at\n" +
" - By default water is disabled (with a value of 0)"
@ -785,14 +761,14 @@ public class CFICommands extends MethodCommands {
int biomePriority = gen.getBiomePriority();
Message msg = msg("&8>>&7 Current Settings &8<<&7").newline()
.text("&7Randomization ").text("&7[&a" + (Boolean.toString(rand).toUpperCase()) + "&7]").cmdTip(alias() + " randomization " + (!rand))
Message msg = msg(">> Current Settings <<").newline()
.text("Randomization ").text("[" + (Boolean.toString(rand).toUpperCase()) + "]").cmdTip(alias() + " randomization " + (!rand))
.newline()
.text("&7Mask ").text("&7[&a" + mask + "&7]").cmdTip(alias() + " mask")
.text("Mask ").text("[" + mask + "]").cmdTip(alias() + " mask")
.newline()
.text("&7Blocks ").text("&7[&a" + blocks + "&7]").tooltip(blockList).command(alias() + " paletteBlocks")
.text("Blocks ").text("[" + blocks + "]").tooltip(blockList).command(alias() + " paletteBlocks")
.newline()
.text("&7BiomePriority ").text("&7[&a" + biomePriority + "&7]").cmdTip(alias() + " biomepriority")
.text("BiomePriority ").text("[" + biomePriority + "]").cmdTip(alias() + " biomepriority")
.newline();
if (settings.image != null) {
@ -802,19 +778,19 @@ public class CFICommands extends MethodCommands {
if (settings.mask != null) colorArgs.append(" " + settings.maskArg);
if (!settings.whiteOnly) colorArgs.append(" -w");
msg.text("&7Image: ")
.text("&7[&a" + settings.imageArg + "&7]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "image"))
msg.text("Image: ")
.text("[" + settings.imageArg + "]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "image"))
.newline().newline()
.text("&cLet's Color&7: ")
.text("&cLet's Color: ")
.cmdOptions(alias() + " ", colorArgs.toString(), "Biomes", "Blocks", "BlockAndBiome", "Glass")
.newline();
} else {
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("&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(
@ -835,12 +811,12 @@ public class CFICommands extends MethodCommands {
StringBuilder cmd = new StringBuilder(alias() + " mask ");
msg("&8>>&7 Current Settings &8<<&7").newline()
.text("&7Image Mask ").text("&7[&a" + settings.imageMaskArg + "&7]").suggestTip(cmd + "http://")
msg(">> Current Settings <<").newline()
.text("Image Mask ").text("[" + settings.imageMaskArg + "]").suggestTip(cmd + "http://")
.newline()
.text("&7WorldEdit Mask ").text("&7[&a" + settings.maskArg + "&7]").suggestTip(cmd + "<mask>")
.text("WorldEdit Mask ").text("[" + settings.maskArg + "]").suggestTip(cmd + "<mask>")
.newline()
.text("&8< &7[&aBack&7]").cmdTip(alias() + " " + settings.getCategory()).send(fp);
.text("< [Back]").cmdTip(alias() + " " + settings.getCategory()).send(fp);
}
@Command(
@ -861,10 +837,10 @@ public class CFICommands extends MethodCommands {
if (pattern != null) {
dispathcer.call(settings.getCategory(), context.getLocals(), new String[0]);
} else {
msg("&8>>&7 Current Settings &8<<&7").newline()
.text("&7Pattern ").text("&7[&aClick Here&7]").suggestTip(cmd + " stone")
msg(">> Current Settings <<").newline()
.text("Pattern ").text("[Click Here]").suggestTip(cmd + " stone")
.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 ");
if (image == null) {
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()
.text("From a file: ").text("&7[&aClick Here&7]").suggestTip(cmd + "file://")
.text("From a file: ").text("[Click Here]").suggestTip(cmd + "file://")
.send(fp);
} else {
if (settings.hasGenerator()) {
@ -931,7 +907,7 @@ public class CFICommands extends MethodCommands {
msg("What would you like to populate?").newline()
.text("(You will need to type these commands)").newline()
.cmdOptions(alias() + " ", "", "Ores", "Ore", "Caves", "Schematics", "Smooth")
.newline().text("&8< &7[&aBack&7]").cmdTip(alias())
.newline().text("< [Back]").cmdTip(alias())
.send(fp);
}
@ -966,49 +942,49 @@ public class CFICommands extends MethodCommands {
String waterHeight = Commands.getAlias(CFICommands.class, "waterheight");
String snow = Commands.getAlias(CFICommands.class, "snow");
Message msg = msg("&8>>&7 Current Settings &8<<&7").newline()
.text("&7Mask ").text("&7[&a" + mask + "&7]").cmdTip(alias() + " mask")
Message msg = msg(">> Current Settings <<").newline()
.text("Mask ").text("[" + mask + "]").cmdTip(alias() + " mask")
.newline()
.text("&7Pattern ").text("&7[&a" + pattern + "&7]").cmdTip(alias() + " pattern")
.text("Pattern ").text("[" + pattern + "]").cmdTip(alias() + " pattern")
.newline()
.newline()
.text("&8>>&7 Components &8<<&7")
.text(">> Components <<")
.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()
.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()
.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()
.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()
.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();
if (pattern != null) {
String disabled = "You must specify a pattern";
msg
.text("&7[&cWaterId&7]").tooltip(disabled).newline()
.text("&7[&cBedrockId&7]").tooltip(disabled).newline()
.text("&7[&cFloor&7]").tooltip(disabled).newline()
.text("&7[&cMain&7]").tooltip(disabled).newline()
.text("&7[&cColumn&7]").tooltip(disabled).newline()
.text("&7[&cOverlay&7]").tooltip(disabled).newline();
.text("[&cWaterId]").tooltip(disabled).newline()
.text("[&cBedrockId]").tooltip(disabled).newline()
.text("[&cFloor]").tooltip(disabled).newline()
.text("[&cMain]").tooltip(disabled).newline()
.text("[&cColumn]").tooltip(disabled).newline()
.text("[&cOverlay]").tooltip(disabled).newline();
} else {
StringBuilder compArgs = new StringBuilder();
compArgs.append(" " + settings.patternArg + maskArgs);
msg
.text("&7[&aWaterId&7]").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("&7[&aFloor&7]").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("&7[&aColumn&7]").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("[WaterId]").cmdTip(alias() + " waterId " + pattern).text(" - Water id for whole map").newline()
.text("[BedrockId]").cmdTip(alias() + " baseId " + pattern).text(" - Bedrock id for whole map").newline()
.text("[Floor]").cmdTip(alias() + " floor" + compArgs).text(" - Set the floor in the masked areas").newline()
.text("[Main]").cmdTip(alias() + " main" + compArgs).text(" - Set the main block in the masked areas").newline()
.text("[Column]").cmdTip(alias() + " column" + compArgs).text(" - Set the columns in the masked areas").newline()
.text("[Overlay]").cmdTip(alias() + " overlay" + compArgs).text(" - Set the overlay in the masked areas").newline();
}
msg.newline()
.text("&8< &7[&aBack&7]").cmdTip(alias())
.text("< [Back]").cmdTip(alias())
.send(fp);
}
@ -1160,9 +1136,9 @@ public class CFICommands extends MethodCommands {
protected void mainMenu(FawePlayer fp) {
msg("What do you want to do now?").newline()
.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("&4>< &7[&aCancel&7]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "cancel"))
.newline().text("&2>> &7[&aDone&7]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "done"))
.newline().text("<> [View]").command(alias() + " " + Commands.getAlias(CFICommands.class, "download")).tooltip("View full resolution image")
.newline().text(">< [Cancel]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "cancel"))
.newline().text("&2>> [Done]").cmdTip(alias() + " " + Commands.getAlias(CFICommands.class, "done"))
.send(fp);
}
}

View File

@ -3,7 +3,7 @@ package com.boydti.fawe.config;
import com.boydti.fawe.configuration.ConfigurationSection;
import com.boydti.fawe.configuration.file.YamlConfiguration;
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.IOException;
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) {
if (cmdConfig == null || command instanceof TranslatedCommand) {
return command;

View File

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

View File

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

View File

@ -122,7 +122,7 @@ public class SchematicStreamer extends NBTStreamer {
ByteReader biomeReader = new ByteReader() {
@Override
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>() {

View File

@ -1,11 +1,7 @@
package com.boydti.fawe.jnbt.anvil;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweCache;
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.brush.visualization.VirtualWorld;
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 {
int index = z * getWidth() + x;
if (index < 0 || index >= getArea()) index = Math.floorMod(index, getArea());
return BiomeTypes.get(biomes.getByte(index));
return BiomeTypes.register(biomes.getByte(index));
}
@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.MathMan;
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.BiomeTypes;
import java.io.DataOutput;
import java.io.DataOutputStream;
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;
public class MCAChunk extends FaweChunk<Void> {
@ -105,12 +116,9 @@ public class MCAChunk extends FaweChunk<Void> {
}
out.writeNamedTag("HeightMap", heightMap);
out.writeNamedTagName("Sections", NBTConstants.TYPE_LIST);
nbtOut.getOutputStream().writeByte(NBTConstants.TYPE_COMPOUND);
int len = 0;
for (int[] id : ids) {
if (id != null) len++;
}
nbtOut.getOutputStream().writeInt(len);
nbtOut.writeByte(NBTConstants.TYPE_COMPOUND);
int len = (int) Arrays.stream(ids).filter(Objects::nonNull).count();
nbtOut.writeInt(len);
for (int layer = 0; layer < ids.length; layer++) {
int[] idLayer = ids[layer];
if (idLayer == null) {
@ -131,8 +139,7 @@ public class MCAChunk extends FaweChunk<Void> {
buffer = new byte[8192];
}
FastByteArrayOutputStream buffered = new FastByteArrayOutputStream(buffer);
DataOutputStream dataOut = new DataOutputStream(buffered);
try (NBTOutputStream nbtOut = new NBTOutputStream((DataOutput) dataOut)) {
try (NBTOutputStream nbtOut = new NBTOutputStream(buffered)) {
write(nbtOut);
}
return buffered.toByteArray();
@ -603,14 +610,14 @@ public class MCAChunk extends FaweChunk<Void> {
public BiomeType[] getBiomeArray() {
BiomeType[] arr = new BiomeType[256];
for (int i = 0; i < arr.length; i++) {
arr[i] = BiomeTypes.get(biomes[i]);
arr[i] = BiomeTypes.register(biomes[i]);
}
return arr;
}
@Override
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

View File

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

View File

@ -24,10 +24,9 @@ import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extension.platform.CommandManager;
import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
import com.sk89q.worldedit.extension.platform.PlatformManager;
import com.sk89q.worldedit.extension.platform.PlayerProxy;
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.util.Location;
import com.sk89q.worldedit.world.World;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
@ -59,6 +56,7 @@ import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.jetbrains.annotations.NotNull;
public abstract class FawePlayer<T> extends Metadatable {
@ -152,74 +150,70 @@ public abstract class FawePlayer<T> extends Metadatable {
return cancelled;
}
private void setConfirmTask(@Nullable Runnable task, CommandContext context, String command) {
if (task != null) {
Runnable newTask = () -> CommandManager.getInstance().handleCommandTask(() -> {
private void setConfirmTask(@NotNull Runnable task, CommandContext context) {
Runnable newTask = () -> PlatformCommandManager.getInstance().handleCommandTask(() -> {
task.run();
return null;
}, context.getLocals());
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 (times > limit) {
setConfirmTask(task, context, command);
setConfirmTask(task, context);
String volume = "<unspecified>";
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 (radius > 0) {
if (radius > 448) {
setConfirmTask(task, context, command);
setConfirmTask(task, context);
long volume = (long) (Math.PI * ((double) radius * radius));
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 (region != null) {
BlockVector3 min = region.getMinimumPoint();
BlockVector3 max = region.getMaximumPoint();
long area = (long) ((max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1)) * times;
if (area > 2 << 18) {
setConfirmTask(task, context, command);
setConfirmTask(task, context);
BlockVector3 base = max.subtract(min).add(BlockVector3.ONE);
long volume = (long) base.getX() * base.getZ() * base.getY() * times;
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(min, max, command, NumberFormat.getNumberInstance().format(volume)));
}
}
}
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 (region != null) {
BlockVector3 min = region.getMinimumPoint();
BlockVector3 max = region.getMaximumPoint();
long area = (max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1);
if (area > 2 << 18) {
setConfirmTask(task, context, command);
setConfirmTask(task, context);
BlockVector3 base = max.subtract(min).add(BlockVector3.ONE);
long volume = (long) base.getX() * base.getZ() * base.getY();
throw new RegionOperationException(BBC.WORLDEDIT_CANCEL_REASON_CONFIRM.f(min, max, command, NumberFormat.getNumberInstance().format(volume)));
}
}
}
if (task != null) task.run();
task.run();
}
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.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[]>() {
@Override
public void run(int[] value) {
@ -228,6 +222,7 @@ public interface FaweQueue extends HasFaweQueue, Extent {
File getSaveFolder();
@Override
default int getMaxY() {
World weWorld = getWEWorld();
return weWorld == null ? 255 : weWorld.getMaxY();
@ -452,7 +447,7 @@ public interface FaweQueue extends HasFaweQueue, Extent {
try {
return getCombinedId4Data(x, y, z);
} 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;
} catch (Throwable e) {
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;
}
@Override
public boolean isGlobal() {
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.ParserContext;
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.pattern.Pattern;
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 {
Dispatcher dispatcher = CommandManager.getInstance().getDispatcher();
Dispatcher dispatcher = PlatformCommandManager.getInstance().getCommandManager();
Dispatcher brushDispatcher = (Dispatcher) (dispatcher.get("brush").getCallable());
if (brushDispatcher == 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.entity.Player;
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.math.BlockVector3;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
@ -48,7 +48,7 @@ public class CommandBrush implements Brush {
List<String> cmds = StringMan.split(replaced, ';');
for (String cmd : cmds) {
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.entity.Player;
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.math.BlockVector3;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
@ -42,7 +42,7 @@ public class ScatterCommand extends ScatterBrush {
List<String> cmds = StringMan.split(replaced, ';');
for (String cmd : cmds) {
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 {
BlockVector3 top = session.getMaximumPoint();
int maxY = top.getBlockY();
int diameter = 2 * size + 1;
Location min = new Location(session.getWorld(), pos.subtract(size, maxY, size).toVector3());
BlockVector3 max = pos.add(size, maxY, size);
Region region = new CuboidRegion(session.getWorld(), min.toBlockPoint(), max);
@ -34,6 +33,7 @@ public interface HeightMap {
if (smooth) {
try {
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);
} catch (Throwable e) {
e.printStackTrace();

View File

@ -1,6 +1,5 @@
package com.boydti.fawe.object.brush.visualization;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.example.SimpleIntFaweChunk;
import com.boydti.fawe.object.FaweChunk;
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.util.SetQueue;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.function.operation.Operation;
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.world.World;
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.weather.WeatherType;
import com.sk89q.worldedit.world.weather.WeatherTypes;
import java.io.File;
import java.util.Collection;
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.change.Change;
import com.sk89q.worldedit.math.MutableBlockVector2;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
public class MutableBiomeChange implements Change {
@ -26,11 +25,11 @@ public class MutableBiomeChange implements Change {
@Override
public void undo(UndoContext context) throws WorldEditException {
context.getExtent().setBiome(mutable, BiomeTypes.get(from));
context.getExtent().setBiome(mutable, BiomeTypes.register(from));
}
@Override
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.database.DBHandler;
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.sk89q.jnbt.NBTInputStream;
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.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.io.DataOutput;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@ -291,7 +294,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
}
enttFile.getParentFile().mkdirs();
enttFile.createNewFile();
osENTCT = new NBTOutputStream((DataOutput) getCompressedOS(new FileOutputStream(enttFile)));
osENTCT = new NBTOutputStream(getCompressedOS(new FileOutputStream(enttFile)));
return osENTCT;
}
@ -302,7 +305,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
}
entfFile.getParentFile().mkdirs();
entfFile.createNewFile();
osENTCF = new NBTOutputStream((DataOutput) getCompressedOS(new FileOutputStream(entfFile)));
osENTCF = new NBTOutputStream(getCompressedOS(new FileOutputStream(entfFile)));
return osENTCF;
}
@ -313,7 +316,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
}
nbttFile.getParentFile().mkdirs();
nbttFile.createNewFile();
osNBTT = new NBTOutputStream((DataOutput) getCompressedOS(new FileOutputStream(nbttFile)));
osNBTT = new NBTOutputStream(getCompressedOS(new FileOutputStream(nbttFile)));
return osNBTT;
}
@ -324,7 +327,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
}
nbtfFile.getParentFile().mkdirs();
nbtfFile.createNewFile();
osNBTF = new NBTOutputStream((DataOutput) getCompressedOS(new FileOutputStream(nbtfFile)));
osNBTF = new NBTOutputStream(getCompressedOS(new FileOutputStream(nbtfFile)));
return osNBTF;
}
@ -343,8 +346,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
if (!bioFile.exists()) {
return null;
}
FaweInputStream is = MainUtil.getCompressedIS(new FileInputStream(bioFile));
return is;
return MainUtil.getCompressedIS(new FileInputStream(bioFile));
}
@Override
@ -391,8 +393,8 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
// skip mode
gis.skipFully(1);
// origin
ox = ((gis.read() << 24) + (gis.read() << 16) + (gis.read() << 8) + (gis.read() << 0));
oz = ((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());
setOrigin(ox, oz);
DiskStorageSummary summary = new DiskStorageSummary(ox, oz);
if (!requiredRegion.isIn(ox, oz)) {
@ -432,8 +434,8 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
// skip mode
gis.skipFully(1);
// origin
ox = ((gis.read() << 24) + (gis.read() << 16) + (gis.read() << 8) + (gis.read() << 0));
oz = ((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());
setOrigin(ox, oz);
fis.close();
gis.close();
@ -446,8 +448,6 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
public static class DiskStorageSummary {
private final int z;
private final int x;
public int[] blocks;
public int minX;
@ -458,8 +458,6 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
public DiskStorageSummary(int x, int z) {
blocks = new int[BlockTypes.states.length];
this.x = x;
this.z = z;
minX = x;
maxX = x;
minZ = z;
@ -485,7 +483,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
for (int i = 0; i < blocks.length; i++) {
if (blocks[i] != 0) {
BlockState state = BlockTypes.states[i];
map.put(state, (Integer) blocks[i]);
map.put(state, blocks[i]);
}
}
return map;
@ -498,18 +496,14 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
for (Map.Entry<BlockState, Integer> entry : map.entrySet()) {
BlockState id = entry.getKey();
int changes = entry.getValue();
double percent = ((changes * 1000l) / count) / 10d;
newMap.put(id, (Double) percent);
double percent = (changes * 1000L / count) / 10d;
newMap.put(id, percent);
}
return newMap;
}
public int getSize() {
int count = 0;
for (int block : blocks) {
count += block;
}
return count;
return Arrays.stream(blocks).sum();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,7 @@
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.ReflectionUtils;
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.world.World;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import static com.google.common.base.Preconditions.checkNotNull;
public class ResettableExtent extends AbstractDelegateExtent implements Serializable {
public ResettableExtent(Extent parent) {
super(parent);
@ -41,7 +41,7 @@ public class ResettableExtent extends AbstractDelegateExtent implements Serializ
return this;
}
private void writeObject(java.io.ObjectOutputStream stream) throws IOException {
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
Extent extent = getExtent();
boolean next = extent instanceof ResettableExtent;

View File

@ -34,13 +34,13 @@ public class SolidPlaneMask extends SolidBlockMask implements ResettableMask {
originZ = vector.getBlockZ();
mode = 0;
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;
}
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;
}
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;
}
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.TextureUtil;
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.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.BlockTypes;
import java.awt.Color;
import java.io.IOException;
import java.io.ObjectInputStream;
public class AverageColorPattern extends AbstractExtentPattern {
private transient TextureHolder holder;
@ -36,7 +33,7 @@ public class AverageColorPattern extends AbstractExtentPattern {
@Override
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();
int currentColor = util.getColor(blockType);
if (currentColor == 0) return false;
@ -46,7 +43,7 @@ public class AverageColorPattern extends AbstractExtentPattern {
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();
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.TextureUtil;
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.function.pattern.AbstractPattern;
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 java.io.IOException;
import java.io.ObjectInputStream;
public class DesaturatePattern extends AbstractPattern {
private transient TextureHolder holder;
@ -27,7 +25,7 @@ public class DesaturatePattern extends AbstractPattern {
@Override
public BaseBlock apply(BlockVector3 position) {
BlockType block = extent.getBlockType(position);
BlockType block = extent.getBlock(position).getBlockType();
TextureUtil util = holder.getTextureUtil();
int color = util.getColor(block);
int r = (color >> 16) & 0xFF;
@ -44,7 +42,7 @@ public class DesaturatePattern extends AbstractPattern {
@Override
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();
int color = util.getColor(block);
int r = (color >> 16) & 0xFF;
@ -66,7 +64,7 @@ public class DesaturatePattern extends AbstractPattern {
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();
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.TextureUtil;
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.function.pattern.AbstractPattern;
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 java.awt.Color;
import java.io.IOException;
import java.io.ObjectInputStream;
public class SaturatePattern extends AbstractPattern {
private transient TextureHolder holder;
@ -29,7 +27,7 @@ public class SaturatePattern extends AbstractPattern {
@Override
public BaseBlock apply(BlockVector3 position) {
BlockType block = extent.getBlockType(position);
BlockType block = extent.getBlock(position).getBlockType();
TextureUtil util = holder.getTextureUtil();
int currentColor = util.getColor(block);
int newColor = util.multiplyColor(currentColor, color);
@ -38,7 +36,7 @@ public class SaturatePattern extends AbstractPattern {
@Override
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();
int currentColor = util.getColor(block);
if (currentColor == 0) return false;
@ -48,7 +46,7 @@ public class SaturatePattern extends AbstractPattern {
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();
holder = Fawe.get().getCachedTextureUtil(true, 0, 100);
}

View File

@ -1,20 +1,16 @@
package com.boydti.fawe.object.pattern;
import static com.google.common.base.Preconditions.checkNotNull;
import com.boydti.fawe.Fawe;
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.function.pattern.AbstractPattern;
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 java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull;
public class ShadePattern extends AbstractPattern {
private transient TextureUtil util;
private final Extent extent;
@ -29,7 +25,7 @@ public class ShadePattern extends AbstractPattern {
@Override
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();
}

View File

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

View File

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

View File

@ -154,8 +154,4 @@ public class FuzzyRegionSelector extends AbstractDelegateExtent implements Regio
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) {
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) {
EditSession editSession = (EditSession) extent;
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) {
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) {
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() {

View File

@ -8,7 +8,6 @@ import com.boydti.fawe.util.EditSessionBuilder;
import com.boydti.fawe.util.IOUtil;
import com.boydti.fawe.util.SetQueue;
import com.boydti.fawe.util.TaskManager;
import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.object.Location;
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.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
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.util.SetupUtils;
import com.sk89q.worldedit.event.platform.CommandEvent;
import com.sk89q.worldedit.extension.platform.CommandManager;
import com.sk89q.worldedit.extension.platform.PlatformCommandManager;
@CommandDeclaration(
command = "replaceall",
@ -57,7 +57,7 @@ public class ReplaceAll extends Command {
FakePlayer actor = FakePlayer.getConsole();
String cmd = "/replaceallpattern " + worldName + " " + StringMan.join(args, " ");
CommandEvent event = new CommandEvent(actor, cmd);
CommandManager.getInstance().handleCommandOnCurrentThread(event);
PlatformCommandManager.getInstance().handleCommandOnCurrentThread(event);
TaskManager.IMP.sync(new RunnableVal<Object>() {
@Override
public void run(Object value) {

View File

@ -25,7 +25,7 @@ public final class BrushCache {
return item.hasNbtData() ? item.getNbtData() : null;
}
private static final Object getKey(BaseItem item) {
private static Object getKey(BaseItem item) {
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.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.NestedCommand;
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.config.Settings;
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.FaweChangeSet;
import com.boydti.fawe.object.changeset.MemoryOptimizedHistory;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.event.extent.EditSessionEvent;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.eventbus.EventBus;
import com.sk89q.worldedit.world.World;
import java.util.UUID;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.UUID;
public class EditSessionBuilder {
private World world;
@ -180,17 +186,15 @@ public class EditSessionBuilder {
return this;
}
public EditSessionBuilder eventBus(@Nullable EventBus eventBus) {
this.eventBus = eventBus;
return this;
}
public EditSessionBuilder event(@Nullable EditSessionEvent event) {
this.event = event;
return this;
}
public EditSession build() {
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;
import static java.lang.System.arraycopy;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.config.BBC;
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.FaweStreamChangeSet;
import com.boydti.fawe.object.io.AbstractDelegateOutputStream;
import com.github.luben.zstd.ZstdInputStream;
import com.github.luben.zstd.ZstdOutputStream;
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.history.changeset.ChangeSet;
import com.sk89q.worldedit.util.Location;
import static java.lang.System.arraycopy;
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.Graphics2D;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
@ -77,6 +77,15 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.ZipEntry;
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 {
/*
@ -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,17 +171,8 @@ public class SetQueue {
e.printStackTrace();
}
if (pool.getQueuedSubmissionCount() != 0 || pool.getRunningThreadCount() != 0 || pool.getQueuedTaskCount() != 0) {
// if (Fawe.get().isJava8())
{
pool.awaitQuiescence(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
// else {
// pool.shutdown();
// pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// pool = new ForkJoinPool();
// completer = new ExecutorCompletionService(pool);
// }
}
queue.endSet(parallel);
} catch (Throwable e) {
e.printStackTrace();

View File

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

View File

@ -6,7 +6,7 @@ import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.StringMan;
import com.sk89q.minecraft.util.commands.CommandLocals;
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.CommandMapping;
import com.sk89q.worldedit.util.command.Description;
@ -57,7 +57,7 @@ public class UsageMessage extends Message {
String prefix = !commandString.isEmpty() ? commandString + " " : "";
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) {
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>() {
@Override
public void accept(File file) {
String path = dir.toURI().relativize(file.toURI()).getPath();
try {
String path = dir.toURI()
.relativize(file.toURI()).getPath();
out.writeUTF(path);
} catch (IOException e) {
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.Location;
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.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockTypes;
@ -120,6 +121,10 @@ public class PlayerWrapper extends AbstractPlayerActor {
parent.printError(msg);
}
@Override public void print(Component component) {
parent.print(component);
}
@Override
public String[] getGroups() {
return parent.getGroups();

View File

@ -181,6 +181,18 @@ public class CompoundTagBuilder {
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.
*

View File

@ -1,10 +1,9 @@
package com.sk89q.jnbt;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import net.jpountz.lz4.LZ4BlockInputStream;
public abstract class CompressedCompoundTag<T> extends CompoundTag {
private T in;
@ -20,7 +19,7 @@ public abstract class CompressedCompoundTag<T> extends CompoundTag {
return super.getValue();
}
public abstract DataInputStream adapt(T src) throws IOException;
public abstract LZ4BlockInputStream adapt(T src) throws IOException;
public T getSource() {
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.FastByteArraysInputStream;
import com.boydti.fawe.object.io.PGZIPOutputStream;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.SpongeSchematicWriter;
import net.jpountz.lz4.LZ4BlockInputStream;
import net.jpountz.lz4.LZ4BlockOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
public class CompressedSchematicTag extends CompressedCompoundTag<Clipboard> {
public CompressedSchematicTag(Clipboard holder) {
@ -18,7 +15,7 @@ public class CompressedSchematicTag extends CompressedCompoundTag<Clipboard> {
}
@Override
public DataInputStream adapt(Clipboard src) throws IOException {
public LZ4BlockInputStream adapt(Clipboard src) throws IOException {
FastByteArrayOutputStream blocksOut = new FastByteArrayOutputStream();
try (LZ4BlockOutputStream lz4out = new LZ4BlockOutputStream(blocksOut)) {
NBTOutputStream nbtOut = new NBTOutputStream(lz4out);
@ -27,6 +24,6 @@ public class CompressedSchematicTag extends CompressedCompoundTag<Clipboard> {
throw new RuntimeException(e);
}
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 java.util.Locale;
/**
* The {@code TAG_Int_Array} tag.
*/
@ -48,7 +50,7 @@ public final class IntArrayTag extends Tag {
public String toString() {
StringBuilder hex = new StringBuilder();
for (int b : value) {
String hexDigits = Integer.toHexString(b).toUpperCase();
String hexDigits = Integer.toHexString(b).toUpperCase(Locale.ROOT);
if (hexDigits.length() == 1) {
hex.append("0");
}

View File

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

View File

@ -152,7 +152,6 @@ public final class NBTInputStream implements Closeable {
if (reader instanceof NBTStreamer.ByteReader) {
NBTStreamer.ByteReader byteReader = (NBTStreamer.ByteReader) reader;
int i = 0;
if (is instanceof InputStream) {
DataInputStream dis = is;
if (length > 1024) {
if (buf == null) {
@ -169,23 +168,6 @@ public final class NBTInputStream implements Closeable {
for (; i < length; i++) {
byteReader.run(i, dis.read());
}
} else {
if (length > 1024) {
if (buf == null) {
buf = new byte[1024];
}
int left = length;
for (; left > 1024; left -= 1024) {
is.readFully(buf);
for (byte b : buf) {
byteReader.run(i++, b & 0xFF);
}
}
}
for (; i < length; i++) {
byteReader.run(i, is.readByte() & 0xFF);
}
}
} else if (reader instanceof NBTStreamer.LazyReader) {
reader.accept(length, is);
} else {
@ -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.
*
@ -560,22 +460,20 @@ public final class NBTInputStream implements Closeable {
}
return new CompoundTag(tagMap);
case NBTConstants.TYPE_INT_ARRAY: {
case NBTConstants.TYPE_INT_ARRAY:
length = is.readInt();
int[] data = new int[length];
for (int i = 0; i < length; i++) {
data[i] = is.readInt();
}
return new IntArrayTag(data);
}
case NBTConstants.TYPE_LONG_ARRAY: {
case NBTConstants.TYPE_LONG_ARRAY:
length = is.readInt();
long[] longData = new long[length];
for (int i = 0; i < length; i++) {
longData[i] = is.readLong();
}
return new LongArrayTag(longData);
}
default:
throw new IOException("Invalid tag type: " + type + ".");
}
@ -583,13 +481,7 @@ public final class NBTInputStream implements Closeable {
@Override
public void close() throws IOException {
if (is instanceof AutoCloseable) {
try {
((AutoCloseable) is).close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
is.close();
}
}

View File

@ -19,8 +19,6 @@
package com.sk89q.jnbt;
import com.boydti.fawe.object.io.LittleEndianOutputStream;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.Closeable;
@ -45,7 +43,7 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
/**
* The output stream.
*/
private DataOutput os;
private final DataOutputStream os;
/**
* 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);
}
public NBTOutputStream(DataOutput os) throws IOException {
this.os = os;
}
public DataOutput getOutputStream() {
return os;
}
/**
* Use a little endian output stream
*/
public void setLittleEndian() {
if (!(os instanceof LittleEndianOutputStream)) {
this.os = new LittleEndianOutputStream((OutputStream) os);
}
}
/**
* Writes a tag.
*
@ -159,7 +144,7 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
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);
os.writeByte(type);
os.writeInt(0);
@ -420,7 +405,7 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
@Override
public void close() throws IOException {
if (os instanceof Closeable) ((Closeable) os).close();
os.close();
}
@Override
@ -500,6 +485,6 @@ public final class NBTOutputStream extends OutputStream implements Closeable, Da
*/
@Override
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.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
@ -60,6 +61,7 @@ import java.util.Set;
* @param <T> command sender class
*/
@SuppressWarnings("ProtectedField")
@Deprecated
public abstract class CommandsManager<T> {
protected static final Logger logger =
@ -253,7 +255,7 @@ public abstract class CommandsManager<T> {
* @return true if the command exists
*/
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];
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 (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

@ -19,6 +19,12 @@
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.FaweAPI;
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.jnbt.anvil.MCAQueue;
import com.boydti.fawe.jnbt.anvil.MCAWorld;
import com.boydti.fawe.logging.LoggingChangeSet;
import com.boydti.fawe.logging.rollback.RollbackOptimizedHistory;
import com.boydti.fawe.object.FaweLimit;
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.collection.LocalBlockVectorSet;
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.mask.ResettableMask;
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.TaskManager;
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.sk89q.jnbt.CompoundTag;
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.generator.ForestGenerator;
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.ForwardExtentCopy;
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.Region;
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.ArbitraryShape;
import com.sk89q.worldedit.regions.shape.RegionShape;
import com.sk89q.worldedit.regions.shape.WorldEditExpressionEnvironment;
import com.sk89q.worldedit.util.Countable;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.util.eventbus.EventBus;
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.BlockTypes;
import com.sk89q.worldedit.world.weather.WeatherType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -156,6 +171,11 @@ import java.util.Map;
import java.util.Set;
import java.util.UUID;
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,
@ -229,20 +249,17 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
public static final UUID CONSOLE = UUID.fromString("1-1-3-3-7");
@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);
}
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);
this.worldName = worldName == null ? world == null ? queue == null ? "" : queue.getWorldName() : world.getName() : worldName;
if (world == null && this.worldName != null) world = FaweAPI.getWorld(this.worldName);
this.world = world;
if (bus == null) {
bus = WorldEdit.getInstance().getEventBus();
}
if (event == 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) {
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 LoggingChangeSet) && player != null && Fawe.imp().getBlocksHubApi() != null) {
changeSet = LoggingChangeSet.wrap(player, changeSet);
}
if (this.blockBag != null) {
changeSet = new BlockBagChangeSet(changeSet, blockBag, limit.INVENTORY_MODE == 1);
}
@ -416,7 +427,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
public void resetLimit() {
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) {
find.get().setLimit(this.limit);
}
@ -455,7 +466,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return FaweRegionExtent (may be null)
*/
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();
}
@ -467,6 +478,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return bypassHistory;
}
@Override
public Extent getExtent() {
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>
* - Note: All implementation queues for FAWE are instances of NMSMappedFaweQueue
*
* @return
*/
@Override
public FaweQueue getQueue() {
return queue;
}
@Deprecated
private AbstractDelegateExtent wrapExtent(Extent extent, EventBus eventBus, EditSessionEvent event, Stage stage) {
event = event.clone(stage);
event.setExtent(extent);
@ -739,7 +741,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return mask, may be null
*/
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;
}
@ -749,18 +751,18 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return mask, may be null
*/
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;
}
public void addTransform(ResettableExtent transform) {
wrapped = true;
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;
while (traverser != null && traverser.get() instanceof ResettableExtent) {
traverser = traverser.next();
next = traverser.get();
next = (AbstractDelegateExtent) traverser.get();
}
this.extent = next;
return;
@ -770,7 +772,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
}
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) {
return (ResettableExtent) traverser.get();
}
@ -788,7 +790,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
} else {
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) {
Mask oldMask = maskingExtent.get().getMask();
if (oldMask instanceof ResettableMask) {
@ -845,7 +847,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return the survival simulation extent
*/
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) {
return survivalExtent.get();
} else {
@ -878,7 +880,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
if (history == null) {
return;
}
ExtentTraverser traverseHistory = new ExtentTraverser(this.extent).find(HistoryExtent.class);
ExtentTraverser<HistoryExtent> traverseHistory = new ExtentTraverser<>(this.extent).find(HistoryExtent.class);
if (disableHistory) {
if (traverseHistory != null && traverseHistory.exists()) {
ExtentTraverser beforeHistory = traverseHistory.previous();
@ -890,7 +892,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
}
}
} 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) {
ExtentTraverser beforeHistory = traverseBypass.previous();
beforeHistory.setNext(history);
@ -939,19 +941,19 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
*
* @return a map of missing blocks
*/
public Map<com.sk89q.worldedit.world.block.BlockType, Integer> popMissingBlocks() {
public Map<BlockType, Integer> popMissingBlocks() {
BlockBag bag = getBlockBag();
if (bag != null) {
bag.flushChanges();
Map<com.sk89q.worldedit.world.block.BlockType, Integer> missingBlocks;
Map<BlockType, Integer> missingBlocks;
ChangeSet changeSet = getChangeSet();
if (changeSet instanceof BlockBagChangeSet) {
missingBlocks = ((BlockBagChangeSet) changeSet).popMissing();
} 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) {
missingBlocks = find.get().popMissing();
} else {
@ -1065,6 +1067,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return getLazyBlock(position.getBlockX(), position.getBlockY(), position.getBlockZ());
}
@Override
public BlockState getLazyBlock(int x, int y, int z) {
return extent.getLazyBlock(x, y, z);
}
@ -1083,18 +1086,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
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.
*
@ -1104,6 +1095,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @param maxY maximal height
* @return height of highest block found or 'minY'
*/
@Override
public int getHighestTerrainBlock(int x, int z, int minY, int maxY) {
for (int y = maxY; y >= minY; --y) {
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
* @return height of highest block found or 'minY'
*/
@Override
public int getHighestTerrainBlock(int x, int z, int minY, int maxY, Mask filter) {
for (int y = maxY; y >= minY; --y) {
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) {
this.changes++;
try {
@ -1301,7 +1295,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
@Override
@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);
}
@ -1472,12 +1466,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
}
if (searchIDs.size() == 1) {
final BlockType id = searchIDs.iterator().next();
RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() {
@Override
public boolean apply(BlockVector3 position) throws WorldEditException {
return getBlockType(position) == id;
}
}, this);
RegionVisitor visitor = new RegionVisitor(region, position -> getBlock(position).getBlockType() == id, this);
Operations.completeBlindly(visitor);
return visitor.getAffected();
}
@ -1489,23 +1478,14 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
}
public int countBlock(final Region region, final boolean[] ids) {
RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() {
@Override
public boolean apply(BlockVector3 position) throws WorldEditException {
return ids[getBlockType(position).getInternalId()];
}
}, this);
RegionVisitor visitor = new RegionVisitor(region,
position -> ids[getBlock(position).getInternalId()], this);
Operations.completeBlindly(visitor);
return visitor.getAffected();
}
public int countBlock(final Region region, final Mask mask) {
RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() {
@Override
public boolean apply(BlockVector3 position) throws WorldEditException {
return mask.test(position);
}
}, this);
RegionVisitor visitor = new RegionVisitor(region, mask::test, this);
Operations.completeBlindly(visitor);
return visitor.getAffected();
}
@ -1519,12 +1499,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
*/
public int countBlocks(Region region, Set<BaseBlock> searchBlocks) {
Mask mask = new BlockMaskBuilder().addBlocks(searchBlocks).build(extent);
RegionVisitor visitor = new RegionVisitor(region, new RegionFunction() {
@Override
public boolean apply(BlockVector3 position) throws WorldEditException {
return mask.test(position);
}
}, this);
RegionVisitor visitor = new RegionVisitor(region, mask::test, this);
Operations.completeBlindly(visitor);
return visitor.getAffected();
}
@ -1534,9 +1509,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
final int startPerformY = region.getMinimumPoint().getBlockY();
final int startCheckY = fullHeight ? 0 : startPerformY;
final int endY = region.getMaximumPoint().getBlockY();
RegionVisitor visitor = new RegionVisitor(flat, new RegionFunction() {
@Override
public boolean apply(BlockVector3 pos) throws WorldEditException {
RegionVisitor visitor = new RegionVisitor(flat, pos -> {
int x = pos.getBlockX();
int z = pos.getBlockZ();
int freeSpot = startCheckY;
@ -1557,7 +1530,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
}
}
return true;
}
}, this);
Operations.completeBlindly(visitor);
return this.changes;
@ -1574,7 +1546,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return number of blocks affected
* @throws MaxChangedBlocksException thrown if too many blocks are changed
*/
public int fillDirection(final 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(pattern);
checkArgument(radius >= 0, "radius >= 0");
@ -1727,12 +1699,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
FaweRegionExtent regionExtent = getRegionExtent();
if (!(region instanceof CuboidRegion)) return false;
if (regionExtent != null) {
if (!(region instanceof CuboidRegion)) return false;
BlockVector3 pos1 = region.getMinimumPoint();
BlockVector3 pos2 = region.getMaximumPoint();
boolean contains = false;
for (Region current : regionExtent.getRegions()) {
if (current.contains((int) pos1.getX(), pos1.getBlockY(), pos1.getBlockZ()) && current.contains(pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ())) {
if (current.contains(pos1.getX(), pos1.getBlockY(), pos1.getBlockZ()) && current.contains(pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ())) {
contains = true;
break;
}
@ -1745,8 +1716,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return false;
if (getChangeTask() != getChangeSet()) return false;
if (!Masks.isNull(getMask()) || !Masks.isNull(getSourceMask())) return false;
if (getBlockBag() != null) return false;
return true;
return getBlockBag() == null;
}
public boolean hasExtraExtents() {
@ -1772,7 +1742,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
getWorld(), // Causes clamping of Y range
position.add(adjustment.multiply(-1)),
position.add(adjustment));
Pattern pattern = (BlockTypes.AIR.getDefaultState());
Pattern pattern = BlockTypes.AIR.getDefaultState();
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 {
checkNotNull(region);
checkNotNull(block);
boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData();
boolean hasNbt = block instanceof BaseBlock && block.hasNbtData();
if (canBypassAll(region, false, true) && !hasNbt) {
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
*/
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
*/
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
*/
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();
ForwardExtentCopy copy = new ForwardExtentCopy(this, region, this, to);
copy.setCopyingEntities(copyEntities);
copy.setCopyBiomes(copyBiomes);
copy.setCopyingBiomes(copyBiomes);
copy.setRepetitions(count);
copy.setTransform(new AffineTransform().translate(dir.multiply(size)));
Mask sourceMask = getSourceMask();
@ -2140,8 +2110,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
ForwardExtentCopy copy = new ForwardExtentCopy(this, region, this, to);
if (replacement == null) replacement = BlockTypes.AIR.getDefaultState();
final BlockReplace remove = replacement instanceof ExistingPattern ? null : new BlockReplace(this, replacement);
copy.setCopyBiomes(copyBiomes);
BlockReplace remove = replacement instanceof ExistingPattern ? null : new BlockReplace(this, replacement);
copy.setCopyingBiomes(copyBiomes);
copy.setCopyingEntities(copyEntities);
copy.setSourceFunction(remove); // Remove
copy.setRemovingEntities(true);
@ -2170,7 +2140,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return number of blocks moved
* @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);
}
@ -2214,7 +2184,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
if (waterlogged) {
replace = new BlockReplace(this, new WaterloggedRemover(this));
} 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);
@ -2256,7 +2226,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
blockMask
);
BlockReplace replace = new BlockReplace(this, (fluid.getDefaultState()));
BlockReplace replace = new BlockReplace(this, fluid.getDefaultState());
NonRisingVisitor visitor = new NonRisingVisitor(mask, replace);
// Around the origin in a 3x3 block
@ -2298,15 +2268,15 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return number of blocks changed
* @throws MaxChangedBlocksException thrown if too many blocks are changed
*/
public int makeCylinder(BlockVector3 pos, 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);
}
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);
}
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;
radiusX += 0.5;
@ -2322,12 +2292,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
if (posv.getBlockY() < 0) {
posv.mutY(0);
} else if (((posv.getBlockY() + height) - 1) > maxY) {
height = (maxY - posv.getBlockY()) + 1;
} else if (posv.getBlockY() + height - 1 > maxY) {
height = maxY - posv.getBlockY() + 1;
}
final double invRadiusX = 1 / (radiusX);
final double invRadiusZ = 1 / (radiusZ);
final double invRadiusX = 1 / radiusX;
final double invRadiusZ = 1 / radiusZ;
int px = posv.getBlockX();
int py = posv.getBlockY();
@ -2336,7 +2306,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
final int ceilRadiusX = (int) Math.ceil(radiusX);
final int ceilRadiusZ = (int) Math.ceil(radiusZ);
double dx, dxz, dz;
double distanceSq;
double nextXn = 0;
if (thickness != 0) {
@ -2350,15 +2320,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
nextMinXn = (x + 1) * minInvRadiusX;
double nextZn = 0;
double nextMinZn = 0;
dx = xn * xn;
forZ: for (int z = 0; z <= ceilRadiusZ; ++z) {
final double zn = nextZn;
double dz2 = nextMinZn * nextMinZn;
nextZn = (z + 1) * invRadiusZ;
nextMinZn = (z + 1) * minInvRadiusZ;
dz = zn * zn;
dxz = dx + dz;
if (dxz > 1) {
distanceSq = lengthSq(xn, zn);
if (distanceSq > 1) {
if (z == 0) {
break forX;
}
@ -2381,14 +2349,14 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
forX: for (int x = 0; x <= ceilRadiusX; ++x) {
final double xn = nextXn;
nextXn = (x + 1) * invRadiusX;
double dx = xn * xn;
double nextZn = 0;
dx = xn * xn;
forZ: for (int z = 0; z <= ceilRadiusZ; ++z) {
final double zn = nextZn;
nextZn = (z + 1) * invRadiusZ;
dz = zn * zn;
dxz = dx + dz;
if (dxz > 1) {
double dz = zn * zn;
distanceSq = lengthSq(xn,zn);
if (distanceSq > 1) {
if (z == 0) {
break forX;
}
@ -2414,7 +2382,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
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;
radiusY += 0.5;
radiusZ += 0.5;
@ -2549,20 +2517,18 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
double nextXn = invRadiusX;
forX: for (int x = 0; x <= ceilRadiusX; ++x) {
final double xn = nextXn;
double dx = xn * xn;
nextXn = (x + 1) * invRadiusX;
double nextZn = invRadiusZ;
double dx = xn * xn;
forZ: for (int z = 0; z <= ceilRadiusZ; ++z) {
final double zn = nextZn;
double dz = zn * zn;
double dxz = dx + dz;
nextZn = (z + 1) * invRadiusZ;
double nextYn = invRadiusY;
forY: for (int y = 0; y <= ceilRadiusY; ++y) {
final double yn = nextYn;
double dy = yn * yn;
double dxyz = dxz + dy;
double dxyz = lengthSq(zn, yn, zn);
nextYn = (y + 1) * invRadiusY;
if (dxyz > 1) {
@ -2576,7 +2542,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
}
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;
}
}
@ -2763,11 +2730,13 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return number of blocks affected
* @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 {
int affected = 0;
final double radiusSq = radius * radius;
final int ox = position.getBlockX();
final int oy = position.getBlockY();
final int oz = position.getBlockZ();
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) {
int dx = x - ox;
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 dz2 = dz * dz;
if (dx2 + dz2 > radiusSq) {
continue;
}
loop:
for (int y = maxY; y >= 1; --y) {
BlockType block = getBlockType(x, y, z);
switch (block.getInternalId()) {
case BlockID.COARSE_DIRT:
if (onlyNormalDirt) break loop;
case BlockID.DIRT:
this.setBlock(x, y, z, BlockTypes.GRASS_BLOCK.getDefaultState());
break loop;
case BlockID.WATER:
case BlockID.LAVA:
default:
if (block.getMaterial().isMovementBlocker()) {
break loop;
}
final BlockState block = getBlock(x, y, z);
if (block.getBlockType() == BlockTypes.DIRT ||
(!onlyNormalDirt && block.getBlockType() == BlockTypes.COARSE_DIRT)) {
this.setBlock(x, y, z, grass);
break;
} else if (block.getBlockType() == BlockTypes.WATER || block.getBlockType() == BlockTypes.LAVA) {
break;
} else if (block.getBlockType().getMaterial().isMovementBlocker()) {
break;
}
}
}
@ -2813,11 +2780,11 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @return number of patches created
* @throws MaxChangedBlocksException thrown if too many blocks are changed
*/
public int makePumpkinPatches(final BlockVector3 position, final int apothem) {
public int makePumpkinPatches(BlockVector3 position, int apothem) throws MaxChangedBlocksException {
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
GardenPatchGenerator generator = new GardenPatchGenerator(this);
generator.setPlant(GardenPatchGenerator.getPumpkinPattern());
@ -2846,7 +2813,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
* @throws MaxChangedBlocksException thrown if too many blocks are changed
*/
public int makeForest(BlockVector3 basePosition, int size, double density, TreeGenerator.TreeType treeType) throws MaxChangedBlocksException {
try {
for (int x = basePosition.getBlockX() - size; x <= (basePosition.getBlockX() + size); ++x) {
for (int z = basePosition.getBlockZ() - size; z <= (basePosition.getBlockZ() + size); ++z) {
// 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;
}
@ -2928,7 +2893,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
}
} else {
for (final BlockVector3 pt : region) {
BlockType type = getBlockType(pt);
BlockType type = getBlock(pt).getBlockType();
counter[type.getInternalId()]++;
}
}
@ -3100,6 +3065,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
final RValue x = expression.getVariable("x", false).optimize();
final RValue y = expression.getVariable("y", false).optimize();
final RValue z = expression.getVariable("z", false).optimize();
final WorldEditExpressionEnvironment environment = new WorldEditExpressionEnvironment(this, unit, zero);
expression.setEnvironment(environment);
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
*/
public int hollowOutRegion(Region region, int thickness, Pattern pattern) throws MaxChangedBlocksException {
try {
final Set<BlockVector3> outside = new LocalBlockVectorSet();
final BlockVector3 min = region.getMinimumPoint();
@ -3201,12 +3166,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
}
}
this.changes++;
try {
pattern.apply(this.extent, position, position);
}
} catch (WorldEditException e) {
throw new RuntimeException(e);
e.printStackTrace();
}
}
return changes;
}
@ -3276,12 +3241,12 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
}
Set<BlockVector3> newVset;
if (flat) {
newVset = this.getStretched(vset, radius);
newVset = getStretched(vset, radius);
if (!filled) {
newVset = this.getOutline(newVset);
}
} else {
newVset = this.getBallooned(vset, radius);
newVset = getBallooned(vset, radius);
if (!filled) {
newVset = this.getHollowed(newVset);
}
@ -3324,16 +3289,20 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
interpol.setNodes(nodes);
double splinelength = interpol.arcLength(0, 1);
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) {
try {
pattern.apply(this, tipv, tipv);
} catch (WorldEditException e) {
e.printStackTrace();
}
} else {
vset.add(tipv);
}
}
Set<BlockVector3> newVset;
if (radius != 0) {
newVset = this.getBallooned(vset, radius);
newVset = getBallooned(vset, radius);
if (!filled) {
newVset = this.getHollowed(newVset);
}
@ -3342,7 +3311,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return changes;
}
private Set<BlockVector3> getBallooned(Set<BlockVector3> vset, double radius) {
private static Set<BlockVector3> getBallooned(Set<BlockVector3> vset, double radius) {
if (radius < 1) {
return vset;
}
@ -3352,9 +3321,9 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
for (BlockVector3 v : vset) {
int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ();
for (int loopx = tipx - ceilrad; loopx <= (tipx + ceilrad); loopx++) {
for (int loopy = tipy - ceilrad; loopy <= (tipy + ceilrad); loopy++) {
for (int loopz = tipz - ceilrad; loopz <= (tipz + ceilrad); loopz++) {
for (int loopx = tipx - ceilrad; loopx <= tipx + ceilrad; loopx++) {
for (int loopy = tipy - ceilrad; loopy <= tipy + ceilrad; loopy++) {
for (int loopz = tipz - ceilrad; loopz <= tipz + ceilrad; loopz++) {
if (MathMan.hypot(loopx - tipx, loopy - tipy, loopz - tipz) <= radius) {
returnset.add(loopx, loopy, loopz);
}
@ -3365,7 +3334,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
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) {
return vset;
}
@ -3373,8 +3342,8 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
final int ceilrad = (int) Math.ceil(radius);
for (final BlockVector3 v : vset) {
final int tipx = v.getBlockX(), tipy = v.getBlockY(), tipz = v.getBlockZ();
for (int loopx = tipx - ceilrad; loopx <= (tipx + ceilrad); loopx++) {
for (int loopz = tipz - ceilrad; loopz <= (tipz + ceilrad); loopz++) {
for (int loopx = tipx - ceilrad; loopx <= tipx + ceilrad; loopx++) {
for (int loopz = tipz - ceilrad; loopz <= tipz + ceilrad; loopz++) {
if (MathMan.hypot(loopx - tipx, 0, loopz - tipz) <= radius) {
returnset.add(loopx, v.getBlockY(), loopz);
}
@ -3384,7 +3353,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return returnset;
}
public Set<BlockVector3> getOutline(final Set<BlockVector3> vset) {
public Set<BlockVector3> getOutline(Set<BlockVector3> vset) {
final LocalBlockVectorSet returnset = new LocalBlockVectorSet();
final LocalBlockVectorSet newset = new LocalBlockVectorSet();
newset.addAll(vset);
@ -3400,7 +3369,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return returnset;
}
public Set<BlockVector3> getHollowed(final Set<BlockVector3> vset) {
public Set<BlockVector3> getHollowed(Set<BlockVector3> vset) {
final Set<BlockVector3> returnset = new LocalBlockVectorSet();
final LocalBlockVectorSet newset = new LocalBlockVectorSet();
newset.addAll(vset);
@ -3421,6 +3390,7 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
private void recurseHollow(Region region, BlockVector3 origin, Set<BlockVector3> outside) {
final LocalBlockVectorSet queue = new LocalBlockVectorSet();
queue.add(origin);
while (!queue.isEmpty()) {
final BlockVector3 current = queue.getIndex(0);
queue.remove(current);
@ -3518,6 +3488,10 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return worldName;
}
@Override public @org.jetbrains.annotations.Nullable Path getStoragePath() {
return null;
}
@Override
public int getBlockLightLevel(BlockVector3 position) {
return queue.getEmmittedLight(position.getBlockX(), position.getBlockY(), position.getBlockZ());
@ -3666,12 +3640,6 @@ public class EditSession extends AbstractDelegateExtent implements HasFaweQueue,
return false;
}
// public void dropItem(BlockVector3 position, BaseItemStack item) {
// if (getWorld() != null) {
// getWorld().dropItem(position, item);
// }
// }
@Override
public void simulateBlockMine(BlockVector3 position) {
TaskManager.IMP.sync((Supplier<Object>) () -> {

View File

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

View File

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

View File

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

View File

@ -19,9 +19,13 @@
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.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.entity.Player;
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.util.Direction;
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.io.file.FileSelectionAbortedException;
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.BundledItemData;
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.File;
import java.io.FileInputStream;
@ -76,10 +76,12 @@ import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.sk89q.worldedit.event.platform.Interaction.HIT;
import static com.sk89q.worldedit.event.platform.Interaction.OPEN;
import javax.annotation.Nullable;
import javax.script.ScriptException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 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 EditSessionFactory editSessionFactory = new EditSessionFactory.EditSessionFactoryImpl(eventBus);
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 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
*/
@ -163,6 +166,15 @@ public final class WorldEdit {
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
* constructed.
@ -307,6 +319,17 @@ public final class WorldEdit {
if (exts.size() != 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;
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) {
if (extension != null) {
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;
}
}
@ -396,16 +419,15 @@ public final class WorldEdit {
}
/**
* Get the direction vector for a player's direction. May return
* null if a direction could not be found.
* Get the direction vector for a player's direction.
*
* @param player the player
* @param dirStr the direction string
* @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 {
dirStr = dirStr.toLowerCase();
public BlockVector3 getDirection(@Nullable Player player, String dirStr) throws UnknownDirectionException {
dirStr = dirStr.toLowerCase(Locale.ROOT);
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
* null if a direction could not be found.
* Get the direction vector for a player's direction.
*
* @param player the player
* @param dirStr the direction string
* @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 {
dirStr = dirStr.toLowerCase();
public BlockVector3 getDiagonalDirection(@Nullable Player player, String dirStr) throws UnknownDirectionException {
dirStr = dirStr.toLowerCase(Locale.ROOT);
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
* null if a direction could not be found.
* Get the direction vector for a player's direction.
*
* @param player the player
* @param dirStr the direction string
* @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;
switch (dirStr.charAt(0)) {
@ -490,19 +510,19 @@ public final class WorldEdit {
case 'm': // me
case 'f': // forward
dir = player.getCardinalDirection(0);
dir = getDirectionRelative(player, 0);
break;
case 'b': // back
dir = player.getCardinalDirection(180);
dir = getDirectionRelative(player, 180);
break;
case 'l': // left
dir = player.getCardinalDirection(-90);
dir = getDirectionRelative(player, -90);
break;
case 'r': // right
dir = player.getCardinalDirection(90);
dir = getDirectionRelative(player, 90);
break;
default:
@ -511,6 +531,13 @@ public final class WorldEdit {
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.
*
@ -650,9 +677,9 @@ public final class WorldEdit {
try {
engine = new RhinoCraftScriptEngine();
} catch (NoClassDefFoundError e) {
} catch (NoClassDefFoundError ignored) {
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;
}

View File

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

View File

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

View File

@ -1,77 +0,0 @@
package com.sk89q.worldedit.command;
import com.boydti.fawe.config.BBC;
import com.boydti.fawe.object.brush.BrushSettings;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandLocals;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.tool.BrushTool;
import com.sk89q.worldedit.command.tool.InvalidToolBindException;
import com.sk89q.worldedit.command.tool.brush.Brush;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.util.command.CallableProcessor;
import com.sk89q.worldedit.util.command.CommandCallable;
import com.sk89q.worldedit.util.command.parametric.AParametricCallable;
public class BrushProcessor extends MethodCommands implements CallableProcessor<BrushSettings> {
private final WorldEdit worldEdit;
public BrushProcessor(WorldEdit worldEdit) {
this.worldEdit = worldEdit;
}
public WorldEdit getWorldEdit() {
return worldEdit;
}
@Override
public BrushSettings process(CommandLocals locals, BrushSettings settings) throws WorldEditException {
Actor actor = locals.get(Actor.class);
LocalSession session = worldEdit.getSessionManager().get(actor);
session.setTool(null, (Player) actor);
BrushTool tool = session.getBrushTool((Player) actor);
if (tool != null) {
tool.setPrimary(settings);
tool.setSecondary(settings);
BBC.BRUSH_EQUIPPED.send(actor, ((String) locals.get("arguments")).split(" ")[1]);
}
return null;
}
public BrushSettings set(LocalSession session, CommandContext context, Brush brush) throws InvalidToolBindException {
CommandLocals locals = context.getLocals();
Actor actor = locals.get(Actor.class);
BrushSettings bs = new BrushSettings();
BrushTool tool = session.getBrushTool((Player) actor, false);
if (tool != null) {
BrushSettings currentContext = tool.getContext();
if (currentContext != null) {
Brush currentBrush = currentContext.getBrush();
if (currentBrush != null && currentBrush.getClass() == brush.getClass()) {
bs = currentContext;
}
}
}
CommandCallable callable = locals.get(CommandCallable.class);
String[] perms;
if (callable != null && callable instanceof AParametricCallable) {
perms = ((AParametricCallable) callable).getPermissions();
} else {
perms = getPermissions();
}
bs.addPermissions(perms);
if (locals != null) {
String args = (String) locals.get("arguments");
if (args != null) {
bs.addSetting(BrushSettings.SettingType.BRUSH, args.substring(args.indexOf(' ') + 1));
}
}
return bs.setBrush(brush);
}
}

View File

@ -19,36 +19,47 @@
package com.sk89q.worldedit.command;
import com.boydti.fawe.config.BBC;
import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.minecraft.util.commands.Logging;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.LocalConfiguration;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.worldedit.command.util.Logging.LogMode.REGION;
import static com.sk89q.worldedit.internal.anvil.ChunkDeleter.DELCHUNKS_FILE_NAME;
import com.google.gson.JsonIOException;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.command.util.Logging;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.internal.anvil.ChunkDeleter;
import com.sk89q.worldedit.internal.anvil.ChunkDeletionInfo;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.MathUtils;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.formatting.component.PaginationBox;
import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.event.ClickEvent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldedit.world.storage.LegacyChunkStore;
import com.sk89q.worldedit.world.storage.McRegionChunkStore;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;
import java.util.stream.Collectors;
import org.enginehub.piston.annotation.Command;
import org.enginehub.piston.annotation.CommandContainer;
import org.enginehub.piston.annotation.param.ArgFlag;
import org.enginehub.piston.exception.StopExecutionException;
/**
* Commands for working with chunks.
*/
@Command(aliases = {}, desc = "[legacy] Inspect chunks: [More Info](http://wiki.sk89q.com/wiki/WorldEdit/Chunk_tools)")
@CommandContainer(superTypes = CommandPermissionsConditionGenerator.Registration.class)
public class ChunkCommands {
private final WorldEdit worldEdit;
@ -59,131 +70,101 @@ public class ChunkCommands {
}
@Command(
aliases = {"chunkinfo"},
usage = "",
desc = "Get information about the chunk that you are inside",
min = 0,
max = 0
name = "chunkinfo",
desc = "Get information about the chunk you're inside"
)
@CommandPermissions("worldedit.chunkinfo")
public void chunkInfo(Player player, LocalSession session, CommandContext args) throws WorldEditException {
public void chunkInfo(Player player) {
Location pos = player.getBlockIn();
int chunkX = (int) Math.floor(pos.getBlockX() / 16.0);
int chunkZ = (int) Math.floor(pos.getBlockZ() / 16.0);
String folder1 = Integer.toString(MathUtils.divisorMod(chunkX, 64), 36);
String folder2 = Integer.toString(MathUtils.divisorMod(chunkZ, 64), 36);
String filename = "c." + Integer.toString(chunkX, 36)
+ "." + Integer.toString(chunkZ, 36) + ".dat";
final BlockVector2 chunkPos = BlockVector2.at(chunkX, chunkZ);
player.print("Chunk: " + chunkX + ", " + chunkZ);
player.print("Old format: " + folder1 + "/" + folder2 + "/" + filename);
player.print("McRegion: region/" + McRegionChunkStore.getFilename(
BlockVector2.at(chunkX, chunkZ)));
player.print("Old format: " + LegacyChunkStore.getFilename(chunkPos));
player.print("McRegion: region/" + McRegionChunkStore.getFilename(chunkPos));
}
@Command(
aliases = {"listchunks"},
usage = "",
desc = "List chunks that your selection includes",
min = 0,
max = 0
name = "listchunks",
desc = "List chunks that your selection includes"
)
@CommandPermissions("worldedit.listchunks")
public void listChunks(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
public void listChunks(Player player, LocalSession session,
@ArgFlag(name = 'p', desc = "Page number.", def = "1") int page) throws WorldEditException {
Set<BlockVector2> chunks = session.getSelection(player.getWorld()).getChunks();
for (BlockVector2 chunk : chunks) {
player.print(LegacyChunkStore.getFilename(chunk));
}
PaginationBox paginationBox = PaginationBox.fromStrings("Selected Chunks", "/listchunks -p %page%",
chunks.stream().map(LegacyChunkStore::getFilename).collect(Collectors.toList()));
player.print(paginationBox.create(page));
}
@Command(
aliases = {"delchunks"},
usage = "",
desc = "Deprecated, use anvil commands",
min = 0,
max = 0
name = "delchunks",
desc = "Delete chunks that your selection includes"
)
@CommandPermissions("worldedit.delchunks")
@Logging(REGION)
public void deleteChunks(Player player, LocalSession session) throws WorldEditException {
player.print("Note that this command does not yet support the mcregion format.");
LocalConfiguration config = worldEdit.getConfiguration();
Set<BlockVector2> chunks = session.getSelection(player.getWorld()).getChunks();
FileOutputStream out = null;
if (config.shellSaveType == null) {
player.printError("Shell script type must be configured: 'bat' or 'bash' expected.");
} else if (config.shellSaveType.equalsIgnoreCase("bat")) {
try {
out = new FileOutputStream("worldedit-delchunks.bat");
OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
writer.write("@ECHO off\r\n");
writer.write("ECHO This batch file was generated by FAWE.\r\n");
writer.write("ECHO It contains a list of chunks that were in the selected region\r\n");
writer.write("ECHO at the time that the /delchunks command was used. Run this file\r\n");
writer.write("ECHO in order to delete the chunk files listed in this file.\r\n");
writer.write("ECHO.\r\n");
writer.write("PAUSE\r\n");
for (BlockVector2 chunk : chunks) {
String filename = LegacyChunkStore.getFilename(chunk);
writer.write("ECHO " + filename + "\r\n");
writer.write("DEL \"world/" + filename + "\"\r\n");
public void deleteChunks(Player player, LocalSession session,
@ArgFlag(name = 'o', desc = "Only delete chunks older than the specified time.", def = "")
ZonedDateTime beforeTime) throws WorldEditException {
Path worldDir = player.getWorld().getStoragePath();
if (worldDir == null) {
throw new StopExecutionException(TextComponent.of("Couldn't find world folder for this world."));
}
writer.write("ECHO Complete.\r\n");
writer.write("PAUSE\r\n");
writer.close();
player.print("worldedit-delchunks.bat written. Run it when no one is near the region.");
File chunkFile = worldEdit.getWorkingDirectoryFile(DELCHUNKS_FILE_NAME);
Path chunkPath = chunkFile.toPath();
ChunkDeletionInfo currentInfo = null;
if (Files.exists(chunkPath)) {
try {
currentInfo = ChunkDeleter.readInfo(chunkFile.toPath());
} catch (IOException e) {
player.printError("Error occurred: " + e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ignored) {
throw new StopExecutionException(TextComponent.of("Error reading existing chunk file."));
}
}
}
} else if (config.shellSaveType.equalsIgnoreCase("bash")) {
try {
out = new FileOutputStream("worldedit-delchunks.sh");
OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
writer.write("#!/bin/bash\n");
writer.write("echo This shell file was generated by FAWE.\n");
writer.write("echo It contains a list of chunks that were in the selected region\n");
writer.write("echo at the time that the /delchunks command was used. Run this file\n");
writer.write("echo in order to delete the chunk files listed in this file.\n");
writer.write("echo\n");
writer.write("read -p \"Press any key to continue...\"\n");
for (BlockVector2 chunk : chunks) {
String filename = LegacyChunkStore.getFilename(chunk);
writer.write("echo " + filename + "\n");
writer.write("rm \"world/" + filename + "\"\n");
if (currentInfo == null) {
currentInfo = new ChunkDeletionInfo();
currentInfo.batches = new ArrayList<>();
}
writer.write("echo Complete.\n");
writer.write("read -p \"Press any key to continue...\"\n");
writer.close();
player.print("worldedit-delchunks.sh written. Run it when no one is near the region.");
player.print("You will have to chmod it to be executable.");
} catch (IOException e) {
player.printError("Error occurred: " + e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ignored) {
}
}
}
ChunkDeletionInfo.ChunkBatch newBatch = new ChunkDeletionInfo.ChunkBatch();
newBatch.worldPath = worldDir.toAbsolutePath().normalize().toString();
newBatch.backup = true;
final Region selection = session.getSelection(player.getWorld());
if (selection instanceof CuboidRegion) {
newBatch.minChunk = BlockVector2.at(selection.getMinimumPoint().getBlockX() >> 4, selection.getMinimumPoint().getBlockZ() >> 4);
newBatch.maxChunk = BlockVector2.at(selection.getMaximumPoint().getBlockX() >> 4, selection.getMaximumPoint().getBlockZ() >> 4);
} else {
player.printError("Shell script type must be configured: 'bat' or 'bash' expected.");
// this has a possibility to OOM for very large selections still
Set<BlockVector2> chunks = selection.getChunks();
newBatch.chunks = new ArrayList<>(chunks);
}
if (beforeTime != null) {
newBatch.deletionPredicates = new ArrayList<>();
ChunkDeletionInfo.DeletionPredicate timePred = new ChunkDeletionInfo.DeletionPredicate();
timePred.property = "modification";
timePred.comparison = "<";
timePred.value = String.valueOf((int) beforeTime.toOffsetDateTime().toEpochSecond());
newBatch.deletionPredicates.add(timePred);
}
currentInfo.batches.add(newBatch);
try {
ChunkDeleter.writeInfo(currentInfo, chunkPath);
} catch (IOException | JsonIOException e) {
throw new StopExecutionException(TextComponent.of("Failed to write chunk list: " + e.getMessage()));
}
player.print(String.format("%d chunk(s) have been marked for deletion the next time the server starts.",
newBatch.getChunkCount()));
if (currentInfo.batches.size() > 1) {
player.printDebug(String.format("%d chunks total marked for deletion. (May have overlaps).",
currentInfo.batches.stream().mapToInt(ChunkDeletionInfo.ChunkBatch::getChunkCount).sum()));
}
player.print(TextComponent.of("You can mark more chunks for deletion, or to stop now, run: ", TextColor.LIGHT_PURPLE)
.append(TextComponent.of("/stop", TextColor.AQUA)
.clickEvent(ClickEvent.of(ClickEvent.Action.SUGGEST_COMMAND, "/stop"))));
}
}

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