Compare commits

...
4 Commits
Author SHA1 Message Date
Andrew Wong 8ec6a43dc8 Update the fawe hook 2020-11-04 17:38:24 +01:00
Andrew Wong 2d81614f5f Update the fawe hook 2020-11-04 17:34:43 +01:00
Andrew Wong 8fb035015d Cache rent and buy regions in a seperate map in FileManager 2020-11-04 17:19:14 +01:00
Andrew Wong 77088a3a72 Performance improvements 2020-11-04 16:38:13 +01:00
15 changed files with 197 additions and 181 deletions

No files matched your search

+1 -1
View File
@@ -11,7 +11,7 @@
<artifactId>areashop</artifactId>
<packaging>jar</packaging>
<name>AreaShop</name>
<version>2.7-SNAPSHOT</version> <!-- Main plugin version -->
<version>2.6.2</version> <!-- Main plugin version -->
<repositories>
<repository>
@@ -681,22 +681,6 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
return true;
}
final String packageName = "me.wiefferink.areashop.handlers.";
final Plugin fawe = getServer().getPluginManager().getPlugin("FastAsyncWorldEdit");
if (fawe != null && fawe.isEnabled()) {
final String version = fawe.getDescription().getVersion();
if (version.startsWith("1.15") || version.startsWith("1.16")) {
try {
this.worldEditInterface = (WorldEditInterface) Class.forName(packageName + "fawe.v1_15.FastAsyncWorldEditHandler")
.getDeclaredConstructor(AreaShopInterface.class).newInstance(this);
} catch (ReflectiveOperationException ex) {
getLogger().log(Level.SEVERE, "Failed to hook into FAWE!");
ex.printStackTrace();
}
}
if (this.worldEditInterface == null) {
info("FAWE Version: " + version + " detected, no compatible handler found. Using the WorldEdit handler instead.");
}
}
if (this.worldEditInterface == null) {
final String version = worldEdit.getDescription().getVersion();
Matcher matcher = VERSION_MATCHER_3.matcher(version);
@@ -718,6 +702,23 @@ public final class AreaShop extends JavaPlugin implements AreaShopInterface {
return false;
}
}
this.worldEdit = (WorldEditPlugin) worldEdit;
final Plugin fawe = getServer().getPluginManager().getPlugin("FastAsyncWorldEdit");
if (fawe != null && fawe.isEnabled()) {
final String version = fawe.getDescription().getVersion();
if (version.startsWith("1.15") || version.startsWith("1.16")) {
try {
this.worldEditInterface = (WorldEditInterface) Class.forName(packageName + "fawe.v1_15.FastAsyncWorldEditHandler")
.getDeclaredConstructor(AreaShopInterface.class).newInstance(this);
} catch (ReflectiveOperationException ex) {
getLogger().log(Level.SEVERE, "Failed to hook into FAWE!");
ex.printStackTrace();
}
}
if (this.worldEditInterface == null) {
info("FAWE Version: " + version + " detected, no compatible handler found. Using the WorldEdit handler instead.");
}
}
final String wgVersion = worldGuard.getDescription().getVersion();
Matcher matcher = VERSION_MATCHER_3.matcher(wgVersion);
if (!matcher.find()) {
@@ -125,7 +125,7 @@ public class AddCommand extends CommandAreaShop {
TreeSet<String> namesNoPermission = new TreeSet<>();
TreeSet<String> namesAddCancelled = new TreeSet<>(); // Denied by an event listener
Utils.runAsBatches(regions.entrySet(),
plugin.getConfig().getInt("adding.regionsPerTick"),
Math.min(plugin.getConfig().getInt("adding.regionsPerTick"), 1),
(regionEntry) -> {
String regionName = regionEntry.getKey();
ProtectedRegion region = regionEntry.getValue();
@@ -51,7 +51,7 @@ public class DelCommand extends CommandAreaShop {
return;
}
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions == null || regions.isEmpty()) {
if(regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound");
return;
}
@@ -92,7 +92,7 @@ public class FriendsFeature extends RegionFeature {
HashSet<String> result = new HashSet<>();
for(UUID friend : getFriends()) {
OfflinePlayer player = Bukkit.getOfflinePlayer(friend);
if(player != null && player.getName() != null) {
if(player.hasPlayedBefore() && player.getName() != null) {
result.add(player.getName());
}
}
@@ -1,5 +1,6 @@
package me.wiefferink.areashop.features;
import co.aikar.taskchain.TaskChain;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import io.papermc.lib.PaperLib;
@@ -8,12 +9,12 @@ import me.wiefferink.areashop.features.signs.RegionSign;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.areashop.tools.Value;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
@@ -40,18 +41,18 @@ public class TeleportFeature extends RegionFeature {
*/
private static boolean isSafe(Location location) {
Block feet = location.getBlock();
Block head = feet.getRelative(BlockFace.UP);
Block below = feet.getRelative(BlockFace.DOWN);
Block above = head.getRelative(BlockFace.UP);
BlockState head = PaperLib.getBlockState(feet.getRelative(BlockFace.UP), true).getState();
BlockState below = PaperLib.getBlockState(feet.getRelative(BlockFace.DOWN), true).getState();
BlockState above = PaperLib.getBlockState(head.getBlock().getRelative(BlockFace.UP), true).getState();
// Check the block at the feet and head of the player
if ((feet.getType().isSolid() && !canSpawnIn(feet.getType())) || feet.isLiquid()) {
return false;
} else if ((head.getType().isSolid() && !canSpawnIn(head.getType())) || head.isLiquid()) {
} else if ((head.getType().isSolid() && !canSpawnIn(head.getType())) || head.getBlock().isLiquid()) {
return false;
} else if (!below.getType().isSolid() || cannotSpawnOn(below.getType()) || below.isLiquid()) {
} else if (!below.getType().isSolid() || cannotSpawnOn(below.getType()) || below.getBlock().isLiquid()) {
return false;
} else if (above.isLiquid() || cannotSpawnBeside(above.getType())) {
} else if (above.getBlock().isLiquid() || cannotSpawnBeside(above.getType())) {
return false;
}
@@ -65,7 +66,7 @@ public class TeleportFeature extends RegionFeature {
continue;
}
around.add(below.getRelative(x, y, z).getType());
around.add(PaperLib.getBlockState(below.getBlock().getRelative(x, y, z), true).getState().getType());
}
}
}
@@ -259,9 +260,11 @@ public class TeleportFeature extends RegionFeature {
final CompletableFuture<Boolean> future = new CompletableFuture<>();
final boolean finalToSign = toSign;
Utils.newChain().future(Utils.runAsBatches(collection, 10, (arr) -> PaperLib.getChunkAtAsync(world, arr[0], arr[1]), false))
.delay(3)
.syncLast((unused) -> {
TaskChain<?> chain = Utils.newChain();
if (collection.size() < 64) {
chain = chain.future(Utils.runAsBatches(collection, 16, (arr) -> PaperLib.getChunkAtAsync(world, arr[0], arr[1]), false));
}
chain.delay(3).syncLast((unused) -> {
boolean blocksInRegionCopy = blocksInRegion;
Location safeLocation = startLocation;
// Tries limit tracking
@@ -493,7 +496,7 @@ public class TeleportFeature extends RegionFeature {
AreaShop.debug("No location found, checked " + checked + " spots of max " + maxTries);
future.complete(false);
}
});
}).execute();
return future;
}
@@ -255,7 +255,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
result = result.replace("&1", "&B");
result = result.replace("&d", "&p");
result = result.replace("&5", "&P");
result = result.replace("&0", "&0");
//result = result.replace("&0", "&0");
result = result.replace("&8", "&1");
result = result.replace("&7", "&2");
result = result.replace("&f", "&w");
@@ -1,6 +1,8 @@
package me.wiefferink.areashop.features.signs;
import com.google.common.base.Objects;
import io.papermc.lib.PaperLib;
import io.papermc.lib.features.blockstatesnapshot.BlockStateSnapshotResult;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Materials;
@@ -11,6 +13,7 @@ import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.WallSign;
@@ -141,7 +144,7 @@ public class RegionSign {
}
ConfigurationSection stateConfig = signConfig.getConfigurationSection(getRegion().getState().getValue());
assert stateConfig != null;
// Get the lines
String[] signLines = new String[4];
boolean signEmpty = true;
@@ -153,21 +156,22 @@ public class RegionSign {
block.setType(Material.AIR);
return true;
}
final BlockStateSnapshotResult snapshotResult = PaperLib.getBlockState(block, true);
final BlockState blockState = snapshotResult.getState();
// Place the sign back (with proper rotation and type) after it has been hidden or (indirectly) destroyed
if (!Materials.isSign(block.getType())) {
Material signType = getMaterial();
if (signType.name().contains("SIGN")) {
final BlockData data = blockState.getBlockData();
// Don't do physics here, we first need to update the direction
block.setType(signType, false);
BlockData data = block.getBlockData();
blockState.setType(signType);
if (data instanceof WallSign) {
((WallSign) data).setFacing(getFacing());
} else if (data instanceof Sign) {
((org.bukkit.block.data.type.Sign) data).setRotation(getFacing());
}
block.setBlockData(data, true);
blockState.setBlockData(data);
blockState.update(false, false);
// Check if the sign has popped
if (!Materials.isSign(block.getType())) {
AreaShop.warn("Setting sign", key, "of region", getRegion().getName(), "failed, could not set sign block back");
@@ -185,7 +189,7 @@ public class RegionSign {
if (!regionConfig.isString("general.signs." + key + ".facing")) {
final BlockFace rotation;
if (Materials.isSign(block.getType())) {
BlockData data = block.getBlockData();
BlockData data = blockState.getBlockData();
if (data instanceof org.bukkit.block.data.type.Sign) {
rotation = ((org.bukkit.block.data.type.Sign) block.getBlockData()).getRotation();
} else if (data instanceof WallSign) {
@@ -200,7 +204,7 @@ public class RegionSign {
}
// Apply replacements and color and then set it on the sign
Sign signState = (Sign) block.getState();
Sign signState = (Sign) blockState;
for (int i = 0; i < signLines.length; i++) {
if (signLines[i] == null) {
signState.setLine(i, "");
@@ -210,8 +214,7 @@ public class RegionSign {
signLines[i] = Utils.applyColors(signLines[i]);
signState.setLine(i, signLines[i]);
}
signState.update(false, false);
return true;
return signState.update(false, false);
}
/**
@@ -22,6 +22,7 @@ import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Sign;
import org.bukkit.block.data.type.WallSign;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -579,7 +580,7 @@ public class SignsFeature extends RegionFeature {
* @return List of signs
*/
public List<RegionSign> getSigns() {
return Collections.unmodifiableList(new ArrayList<>(signs.values()));
return new ArrayList<>(signs.values());
}
/**
@@ -597,7 +598,7 @@ public class SignsFeature extends RegionFeature {
* @return A List with all sign locations
*/
public List<Location> getSignLocations() {
List<Location> result = new ArrayList<>();
List<Location> result = new ArrayList<>(signs.size());
for (RegionSign sign : signs.values()) {
result.add(sign.getLocation());
}
@@ -614,7 +615,8 @@ public class SignsFeature extends RegionFeature {
*/
public void addSign(Location location, Material signType, BlockFace facing, String profile) {
int i = 0;
while (getRegion().getConfig().isSet("general.signs." + i)) {
final YamlConfiguration configuration = getRegion().getConfig();
while (configuration.isSet("general.signs." + i)) {
i++;
}
String signPath = "general.signs." + i + ".";
@@ -1,6 +1,5 @@
package me.wiefferink.areashop.managers;
import co.aikar.taskchain.TaskChain;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.sk89q.worldguard.protection.managers.RegionManager;
@@ -31,31 +30,32 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class FileManager extends Manager {
private final Set<String> worldRegionsRequireSaving;
private HashMap<String, GeneralRegion> regions = null;
private String regionsPath = null;
private HashMap<String, RegionGroup> groups = null;
private String configPath = null;
private final Map<String, BuyRegion> buyRegions = new HashMap<>();
private final Map<String, RentRegion> rentRegions = new HashMap<>();
private final Map<String, GeneralRegion> allRegions = new HashMap<>();
private final String regionsPath;
private final HashMap<String, RegionGroup> groups;
private final String configPath;
private YamlConfiguration config = null;
private String groupsPath = null;
private final String groupsPath;
private YamlConfiguration groupsConfig = null;
private String defaultPath = null;
private final String defaultPath;
private YamlConfiguration defaultConfig = null;
private YamlConfiguration defaultConfigFallback = null;
private boolean saveGroupsRequired = false;
private HashMap<String, Integer> versions = null;
private String versionPath = null;
private String schemFolder = null;
private final String versionPath;
private final String schemFolder;
/**
* Constructor, initialize variabeles.
*/
public FileManager() {
regions = new HashMap<>();
regionsPath = plugin.getDataFolder() + File.separator + AreaShop.regionsFolder;
configPath = plugin.getDataFolder() + File.separator + "config.yml";
groups = new HashMap<>();
@@ -151,7 +151,7 @@ public class FileManager extends Manager {
* @return The region if found, otherwise null
*/
public GeneralRegion getRegion(String name) {
return regions.get(name.toLowerCase());
return allRegions.get(name.toLowerCase());
}
/**
@@ -161,11 +161,7 @@ public class FileManager extends Manager {
* @return RentRegion if it could be found, otherwise null
*/
public RentRegion getRent(String name) {
GeneralRegion region = regions.get(name.toLowerCase());
if (region instanceof RentRegion) {
return (RentRegion) region;
}
return null;
return rentRegions.get(name.toLowerCase());
}
/**
@@ -175,11 +171,7 @@ public class FileManager extends Manager {
* @return BuyRegion if it could be found, otherwise null
*/
public BuyRegion getBuy(String name) {
GeneralRegion region = regions.get(name.toLowerCase());
if (region instanceof BuyRegion) {
return (BuyRegion) region;
}
return null;
return buyRegions.get(name.toLowerCase());
}
/**
@@ -188,13 +180,7 @@ public class FileManager extends Manager {
* @return List of all rental regions
*/
public List<RentRegion> getRents() {
List<RentRegion> result = new LinkedList<>();
for (GeneralRegion region : regions.values()) {
if (region instanceof RentRegion) {
result.add((RentRegion) region);
}
}
return result;
return new ArrayList<>(rentRegions.values());
}
/**
@@ -203,13 +189,7 @@ public class FileManager extends Manager {
* @return List of all buy regions
*/
public List<BuyRegion> getBuys() {
List<BuyRegion> result = new LinkedList<>();
for (GeneralRegion region : regions.values()) {
if (region instanceof BuyRegion) {
result.add((BuyRegion) region);
}
}
return result;
return new ArrayList<>(buyRegions.values());
}
/**
@@ -218,7 +198,9 @@ public class FileManager extends Manager {
* @return List of all regions (it is safe to modify the list)
*/
public List<GeneralRegion> getRegions() {
return new ArrayList<>(regions.values());
final List<GeneralRegion> list = new ArrayList<>(allRegions.size());
list.addAll(allRegions.values());
return list;
}
/**
@@ -227,7 +209,11 @@ public class FileManager extends Manager {
* @return A String list with all the names
*/
public List<String> getBuyNames() {
return getBuys().stream().map(GeneralRegion::getName).collect(Collectors.toList());
final List<String> list = new ArrayList<>(buyRegions.size());
for (GeneralRegion region : buyRegions.values()) {
list.add(region.getName());
}
return list;
}
/**
@@ -236,7 +222,11 @@ public class FileManager extends Manager {
* @return A String list with all the names
*/
public List<String> getRentNames() {
return getRents().stream().map(GeneralRegion::getName).collect(Collectors.toList());
final List<String> list = new ArrayList<>(rentRegions.size());
for (GeneralRegion region : rentRegions.values()) {
list.add(region.getName());
}
return list;
}
/**
@@ -245,7 +235,11 @@ public class FileManager extends Manager {
* @return A String list with all the names
*/
public List<String> getRegionNames() {
return getRegions().stream().map(GeneralRegion::getName).collect(Collectors.toList());
final List<String> list = new ArrayList<>(allRegions.size());
for (GeneralRegion region : rentRegions.values()) {
list.add(region.getName());
}
return list;
}
/**
@@ -254,7 +248,11 @@ public class FileManager extends Manager {
* @return A String list with all the names
*/
public List<String> getGroupNames() {
return getGroups().stream().map(RegionGroup::getName).collect(Collectors.toList());
final List<String> names = new ArrayList<>(groups.size());
for (RegionGroup group : groups.values()) {
names.add(group.getName());
}
return names;
}
/**
@@ -290,7 +288,16 @@ public class FileManager extends Manager {
if (event.isCancelled()) {
return event;
}
regions.put(region.getName().toLowerCase(), region);
final String name = region.getName().toLowerCase();
// Forcefully remove regions from cache.
buyRegions.remove(name);
rentRegions.remove(name);
if (region instanceof BuyRegion) {
buyRegions.put(region.getName().toLowerCase(), (BuyRegion) region);
} else if (region instanceof RentRegion) {
rentRegions.put(region.getName().toLowerCase(), (RentRegion) region);
}
allRegions.put(region.getName().toLowerCase(), region);
Bukkit.getPluginManager().callEvent(new AddedRegionEvent(region));
return event;
}
@@ -404,8 +411,9 @@ public class FileManager extends Manager {
}
region.resetRegionFlags();
regions.remove(region.getLowerCaseName());
rentRegions.remove(region.getLowerCaseName());
buyRegions.remove(region.getLowerCaseName());
allRegions.remove(region.getLowerCaseName());
// Remove file
File file = new File(plugin.getDataFolder() + File.separator + AreaShop.regionsFolder + File.separator + region.getLowerCaseName() + ".yml");
if (file.exists()) {
@@ -553,12 +561,12 @@ public class FileManager extends Manager {
this.saveWorldGuardRegions();
final AtomicInteger processed = new AtomicInteger();
for (GeneralRegion region : getRegions()) {
for (GeneralRegion region : allRegions.values()) {
if (region.isSaveRequired()) {
region.saveNowAsync().thenAccept((unused) -> processed.getAndIncrement());
}
}
final int finalCount = getRegions().size();
final int finalCount = allRegions.size();
final CompletableFuture<Boolean> future = new CompletableFuture<>();
new BukkitRunnable() {
@Override
@@ -580,7 +588,7 @@ public class FileManager extends Manager {
if (isSaveGroupsRequired()) {
saveGroupsNow();
}
for (GeneralRegion region : getRegions()) {
for (GeneralRegion region : allRegions.values()) {
if (region.isSaveRequired()) {
region.saveNow();
}
@@ -833,7 +841,6 @@ public class FileManager extends Manager {
* @return true if succeeded, otherwise false
*/
public boolean loadGroupsFile() {
boolean result = true;
File groupFile = new File(groupsPath);
if (groupFile.exists() && groupFile.isFile()) {
try (
@@ -851,14 +858,16 @@ public class FileManager extends Manager {
RegionGroup group = new RegionGroup(plugin, groupName);
groups.put(groupName, group);
}
return result;
return true;
}
/**
* Load all region files.
*/
public void loadRegionFiles() {
regions.clear();
rentRegions.clear();
buyRegions.clear();
allRegions.clear();
final File file = new File(regionsPath);
if (!file.exists()) {
if (!file.mkdirs()) {
@@ -953,7 +962,7 @@ public class FileManager extends Manager {
boolean noWorldRegions = !noWorld.isEmpty();
while (!noWorld.isEmpty()) {
List<GeneralRegion> toDisplay = new ArrayList<>();
List<GeneralRegion> toDisplay = new ArrayList<>(noWorld.size());
String missingWorld = noWorld.get(0).getWorldName();
toDisplay.add(noWorld.get(0));
for (int i = 1; i < noWorld.size(); i++) {
@@ -973,7 +982,7 @@ public class FileManager extends Manager {
}
if (!incorrectDuration.isEmpty()) {
List<String> incorrectDurationNames = new ArrayList<>();
List<String> incorrectDurationNames = new ArrayList<>(incorrectDuration.size());
for (GeneralRegion region : incorrectDuration) {
incorrectDurationNames.add(region.getName());
}
@@ -1281,7 +1290,7 @@ public class FileManager extends Manager {
// Add 'general.lastActive' to rented/bought regions (initialize at current time)
if (fileStatus == null || fileStatus < 3) {
for (GeneralRegion region : getRegions()) {
for (GeneralRegion region : allRegions.values()) {
region.updateLastActiveTime();
}
// Update versions file to 3
@@ -867,20 +867,19 @@ public class Utils {
if (batchSize < 1) {
throw new IllegalArgumentException("Invalid batch size!");
}
final List<E> cloned = new ArrayList<>(objects);
final Queue<E> cloned = new LinkedList<>(objects);
final CompletableFuture<Object> future = new CompletableFuture<>();
BukkitRunnable runnable = new BukkitRunnable() {
int lastIndex;
@Override
public void run() {
if (lastIndex >= cloned.size() - 1) {
if (cloned.isEmpty()) {
future.complete(true);
cancel();
return;
}
int index = Math.min(batchSize, objects.size() - 1);
cloned.subList(lastIndex, index).forEach(task);
for (int i = 0; i < batchSize && !cloned.isEmpty(); i++) {
task.accept(cloned.remove());
}
}
};
if (async) {
+1 -1
View File
@@ -1,6 +1,6 @@
name: AreaShop
main: me.wiefferink.areashop.AreaShop
version: "${project.version}${build.number}"
version: "${project.version}"
description: "Selling and renting WorldGuard regions to your players, highly configurable."
depend: [Vault, WorldGuard, WorldEdit]
softdepend: [Multiverse-Core, FastAsyncWorldEdit]
+3 -3
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>areashop-fawe-1-15</artifactId>
<packaging>jar</packaging>
<name>AreaShop FastAsyncWorldEdit 1.14+</name>
<name>AreaShop FastAsyncWorldEdit 1.15+</name>
<version>latest</version>
<parent>
@@ -24,7 +24,7 @@
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.14.4-R0.1-SNAPSHOT</version>
<version>1.15.2-R0.1-SNAPSHOT</version>
<type>jar</type>
<scope>provided</scope>
<optional>true</optional>
@@ -32,7 +32,7 @@
<dependency>
<groupId>com.intellectualsites.fawe</groupId>
<artifactId>FAWE-Bukkit</artifactId>
<version>1.16-343</version> <!-- Equivalent to WE 7.0.2? -->
<version>1.16-380</version> <!-- Equivalent to WE 7.0.2? -->
<scope>provided</scope>
</dependency>
<dependency>
@@ -1,11 +1,8 @@
package me.wiefferink.areashop.handlers.fawe.v1_15;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweAPI;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.bukkit.FaweBukkit;
import com.boydti.fawe.object.FaweLimit;
import com.boydti.fawe.object.FaweOutputStream;
import com.boydti.fawe.object.RelightMode;
import com.sk89q.jnbt.NBTInputStream;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.IncompleteRegionException;
@@ -14,27 +11,17 @@ import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter;
import com.sk89q.worldedit.extent.clipboard.io.FastSchematicReader;
import com.sk89q.worldedit.extent.clipboard.io.FastSchematicWriter;
import com.sk89q.worldedit.extent.clipboard.io.*;
import com.sk89q.worldedit.extent.transform.BlockTransformExtent;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.mask.Mask2D;
import com.sk89q.worldedit.function.mask.RegionMask;
import com.sk89q.worldedit.function.operation.ForwardExtentCopy;
import com.sk89q.worldedit.function.operation.Operation;
import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Polygonal2DRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.util.io.Closer;
import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionType;
import me.wiefferink.areashop.interfaces.AreaShopInterface;
@@ -44,12 +31,7 @@ import me.wiefferink.areashop.interfaces.WorldEditSelection;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.bukkit.entity.Player;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.*;
import java.util.zip.GZIPInputStream;
// Future: this class could use the schematic save/paste api of FAWE: https://github.com/boy0001/FastAsyncWorldedit/wiki/Pasting-a-schematic
@@ -60,6 +42,25 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
super(pluginInterface);
}
private Mask newMask(final ProtectedRegion region) {
return new Mask() {
@Override
public boolean test(BlockVector3 vector) {
return region.contains(vector);
}
@Override
public Mask2D toMask2D() {
return null;
}
@Override
public Mask copy() {
return this;
}
};
}
@Override
public boolean restoreRegionBlocks(File rawFile, GeneralRegionInterface regionInterface) {
// TODO implement using the FastAsyncWorldEdit api to paste async
@@ -67,9 +68,9 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
ClipboardFormat format = null;
for (ClipboardFormat formatOption : BuiltInClipboardFormat.values()) {
if (new File(rawFile.getAbsolutePath() + "." + formatOption.getPrimaryFileExtension())
.exists()) {
.exists()) {
file = new File(
rawFile.getAbsolutePath() + "." + formatOption.getPrimaryFileExtension());
rawFile.getAbsolutePath() + "." + formatOption.getPrimaryFileExtension());
format = formatOption;
break;
}
@@ -99,31 +100,30 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
ProtectedRegion region = regionInterface.getRegion();
// Get the origin and size of the region
BlockVector3 origin = BlockVector3
.at(region.getMinimumPoint().getBlockX(), region.getMinimumPoint().getBlockY(),
region.getMinimumPoint().getBlockZ());
.at(region.getMinimumPoint().getBlockX(), region.getMinimumPoint().getBlockY(),
region.getMinimumPoint().getBlockZ());
// Read the schematic and paste it into the world
try (Closer closer = Closer.create()) {
FileInputStream fis = closer.register(new FileInputStream(file));
BufferedInputStream bis = closer.register(new BufferedInputStream(fis));
NBTInputStream nbtStream = new NBTInputStream(new GZIPInputStream(bis));
ClipboardReader reader = new FastSchematicReader(nbtStream);
try (Closer closer = Closer.create(); FileInputStream fis = closer.register(new FileInputStream(file));
BufferedInputStream bis = closer.register(new BufferedInputStream(fis));
NBTInputStream nbtStream = new NBTInputStream(new GZIPInputStream(bis));
ClipboardReader reader = new FastSchematicReader(nbtStream)) {
LocalSession session =
new LocalSession(pluginInterface.getWorldEdit().getLocalConfiguration());
new LocalSession(pluginInterface.getWorldEdit().getLocalConfiguration());
Clipboard clipboard = reader.read();
if (clipboard.getDimensions().getY() != regionInterface.getHeight()
|| clipboard.getDimensions().getX() != regionInterface.getWidth()
|| clipboard.getDimensions().getZ() != regionInterface.getDepth()) {
|| clipboard.getDimensions().getX() != regionInterface.getWidth()
|| clipboard.getDimensions().getZ() != regionInterface.getDepth()) {
pluginInterface.getLogger().warning(
"Size of the region " + regionInterface.getName()
+ " is not the same as the schematic to restore!");
"Size of the region " + regionInterface.getName()
+ " is not the same as the schematic to restore!");
pluginInterface.debugI(
"schematic|region, x:" + clipboard.getDimensions().getX() + "|"
+ regionInterface.getWidth() + ", y:" + clipboard.getDimensions().getY()
+ "|" + regionInterface.getHeight() + ", z:" + clipboard.getDimensions()
.getZ() + "|" + regionInterface.getDepth());
"schematic|region, x:" + clipboard.getDimensions().getX() + "|"
+ regionInterface.getWidth() + ", y:" + clipboard.getDimensions().getY()
+ "|" + regionInterface.getHeight() + ", z:" + clipboard.getDimensions()
.getZ() + "|" + regionInterface.getDepth());
}
clipboard.setOrigin(clipboard.getMinimumPoint());
ClipboardHolder clipboardHolder = new ClipboardHolder(clipboard);
@@ -140,15 +140,7 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
// Mask to region (for polygon and other weird shaped regions)
// TODO make this more efficient (especially for polygon regions)
if (region.getType() != RegionType.CUBOID) {
copy.setSourceMask(new Mask() {
@Override public boolean test(BlockVector3 vector) {
return region.contains(vector);
}
@Override public Mask2D toMask2D() {
return null;
}
});
copy.setSourceMask(newMask(region));
}
Operations.completeLegacy(copy);
} catch (MaxChangedBlocksException e) {
@@ -187,43 +179,44 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
}
if (world == null) {
pluginInterface.getLogger().warning(
"Did not save region " + regionInterface.getName() + ", world not found: "
+ regionInterface.getWorldName());
"Did not save region " + regionInterface.getName() + ", world not found: "
+ regionInterface.getWorldName());
return false;
}
EditSession editSession =
pluginInterface.getWorldEdit().getWorldEdit().getEditSessionFactory()
.getEditSession(world, pluginInterface.getConfig().getInt("maximumBlocks"));
final FaweLimit limit = new FaweLimit();
limit.MAX_CHANGES = pluginInterface.getConfig().getInt("maximumBlocks");
EditSession editSession = FaweAPI.getEditSessionBuilder(world).limit(limit).relightMode(RelightMode.OPTIMAL).build();
// Create a clipboard
CuboidRegion selection =
new CuboidRegion(world, regionInterface.getRegion().getMinimumPoint(),
regionInterface.getRegion().getMaximumPoint());
new CuboidRegion(world, regionInterface.getRegion().getMinimumPoint(),
regionInterface.getRegion().getMaximumPoint());
BlockArrayClipboard clipboard = new BlockArrayClipboard(selection);
clipboard.setOrigin(regionInterface.getRegion().getMinimumPoint());
ForwardExtentCopy copy = new ForwardExtentCopy(editSession,
new CuboidRegion(world, regionInterface.getRegion().getMinimumPoint(),
regionInterface.getRegion().getMaximumPoint()), clipboard,
regionInterface.getRegion().getMinimumPoint());
new CuboidRegion(world, regionInterface.getRegion().getMinimumPoint(),
regionInterface.getRegion().getMaximumPoint()), clipboard,
regionInterface.getRegion().getMinimumPoint());
try {
Operations.completeLegacy(copy);
} catch (MaxChangedBlocksException e) {
pluginInterface.getLogger().warning(
"Exceeded the block limit while saving schematic of " + regionInterface.getName()
+ ", limit in exception: " + e.getBlockLimit() + ", limit passed by AreaShop: "
+ pluginInterface.getConfig().getInt("maximumBlocks"));
"Exceeded the block limit while saving schematic of " + regionInterface.getName()
+ ", limit in exception: " + e.getBlockLimit() + ", limit passed by AreaShop: "
+ pluginInterface.getConfig().getInt("maximumBlocks"));
return false;
}
try (Closer closer = Closer.create()) {
FileOutputStream fos = closer.register(new FileOutputStream(file));
BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos));
try (Closer closer = Closer.create();
FileOutputStream fos = closer.register(new FileOutputStream(file));
BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos))) {
ClipboardWriter writer = closer.register(format.getWriter(bos));
writer.write(clipboard);
} catch (IOException e) {
pluginInterface.getLogger().warning(
"An error occured while saving schematic of " + regionInterface.getName()
+ ", enable debug to see the complete stacktrace");
"An error occured while saving schematic of " + regionInterface.getName()
+ ", enable debug to see the complete stacktrace");
pluginInterface.debugI(ExceptionUtils.getStackTrace(e));
return false;
} catch (Exception e) {
@@ -46,7 +46,14 @@ public class WorldEditHandler extends WorldEditInterface {
@Override
public WorldEditSelection getPlayerSelection(Player player) {
try {
Region region = pluginInterface.getWorldEdit().getSession(player).getSelection(BukkitAdapter.adapt(player.getWorld()));
final LocalSession session = pluginInterface.getWorldEdit().getSession(player);
if (session == null) {
return null;
}
Region region = session.getSelection(BukkitAdapter.adapt(player.getWorld()));
if (region == null) {
return null;
}
return new WorldEditSelection(
player.getWorld(),
BukkitAdapter.adapt(player.getWorld(), region.getMinimumPoint()),
@@ -92,10 +99,10 @@ public class WorldEditHandler extends WorldEditInterface {
BlockVector3 origin = BlockVector3.at(region.getMinimumPoint().getBlockX(), region.getMinimumPoint().getBlockY(), region.getMinimumPoint().getBlockZ());
// Read the schematic and paste it into the world
try(Closer closer = Closer.create()) {
try(Closer closer = Closer.create();
FileInputStream fis = closer.register(new FileInputStream(file));
BufferedInputStream bis = closer.register(new BufferedInputStream(fis));
ClipboardReader reader = format.getReader(bis);
ClipboardReader reader = format.getReader(bis)) {
//WorldData worldData = world.getWorldData();
LocalSession session = new LocalSession(pluginInterface.getWorldEdit().getLocalConfiguration());
@@ -188,10 +195,9 @@ public class WorldEditHandler extends WorldEditInterface {
return false;
}
try(Closer closer = Closer.create()) {
FileOutputStream fos = closer.register(new FileOutputStream(file));
try(Closer closer = Closer.create(); FileOutputStream fos = closer.register(new FileOutputStream(file));
BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos));
ClipboardWriter writer = closer.register(format.getWriter(bos));
ClipboardWriter writer = closer.register(format.getWriter(bos));) {
writer.write(clipboard);
} catch(IOException e) {
pluginInterface.getLogger().warning("An error occured while saving schematic of " + regionInterface.getName() + ", enable debug to see the complete stacktrace");