Merge from upstream

This commit is contained in:
Jesse Boyd
2019-06-29 16:01:32 +10:00
589 changed files with 7156 additions and 15969 deletions

View File

@ -1,32 +1,51 @@
apply plugin: 'java-library'
apply plugin: 'eclipse'
apply plugin: 'idea'
repositories {
maven {url "http://ci.athion.net/job/PlotSquared-Breaking/ws/mvn/"}
}
configurations.all { Configuration it ->
it.resolutionStrategy { ResolutionStrategy rs ->
rs.force("com.google.guava:guava:21.0")
}
}
dependencies {
compile project(':worldedit-libs:core')
compile 'de.schlichtherle:truezip:6.8.3'
compile 'rhino:js:1.7R2'
compile 'org.yaml:snakeyaml:1.23'
compile 'com.google.guava:guava:21.0'
compile 'com.sk89q:jchronic:0.2.4a'
compile 'com.google.code.findbugs:jsr305:1.3.9'
compile 'com.thoughtworks.paranamer:paranamer:2.6'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.sk89q.lib:jlibnoise:1.0.0'
compile 'com.googlecode.json-simple:json-simple:1.1.1'
compile 'org.slf4j:slf4j-api:1.7.26'
compileOnly project(':worldedit-libs:core:ap')
annotationProcessor project(':worldedit-libs:core:ap')
annotationProcessor "com.google.guava:guava:21.0"
def avVersion = "1.6.5"
compileOnly "com.google.auto.value:auto-value-annotations:$avVersion"
annotationProcessor "com.google.auto.value:auto-value:$avVersion"
//compile 'net.sf.trove4j:trove4j:3.0.3'
testCompile 'org.mockito:mockito-core:1.9.0-rc1'
// Fawe depends
compile 'org.yaml:snakeyaml:1.19'
compile 'net.fabiozumbi12:redprotect:1.9.6'
compile ("com.github.intellectualsites.plotsquared:PlotSquared-API:latest") {
transitive = false
}
compile 'com.mojang:datafixerupper:1.0.20'
compile 'com.github.luben:zstd-jni:1.1.1'
compile 'co.aikar:fastutil-lite:1.0'
}
tasks.withType(JavaCompile).configureEach {
it.options.compilerArgs.add("-Aarg.name.key.prefix=")
}
sourceSets {
main {
java {

View File

@ -166,21 +166,6 @@ public class Fawe {
this.timer = new FaweTimer();
Fawe.this.IMP.setupVault();
File jar = MainUtil.getJarFile();
// TODO FIXME remove extrablocks.json
// File extraBlocks = MainUtil.copyFile(jar, "extrablocks.json", null);
// if (extraBlocks != null && extraBlocks.exists()) {
// TaskManager.IMP.task(() -> {
// try {
// BundledBlockData.getInstance().loadFromResource();
// BundledBlockData.getInstance().add(extraBlocks.toURI().toURL(), true);
// } catch (Throwable ignore) {
// ignore.printStackTrace();
// Fawe.debug("Invalid format: extrablocks.json");
// }
// });
// }
// Delayed worldedit setup
TaskManager.IMP.later(() -> {
try {
@ -207,11 +192,6 @@ public class Fawe {
this.chatManager = chatManager;
}
// @Deprecated
// public boolean isJava8() {
// return isJava8;
// }
public DefaultTransformParser getTransformParser() {
return transformParser;
}
@ -295,11 +275,10 @@ public class Fawe {
Settings.IMP.PLATFORM = IMP.getPlatform().replace("\"", "");
try (InputStream stream = getClass().getResourceAsStream("/fawe.properties");
BufferedReader br = new BufferedReader(new InputStreamReader(stream))) {
// java.util.Scanner scanner = new java.util.Scanner(stream).useDelimiter("\\A");
String versionString = br.readLine();
String commitString = br.readLine();
String dateString = br.readLine();
// scanner.close();
br.close();
this.version = FaweVersion.tryParse(versionString, commitString, dateString);
Settings.IMP.DATE = new Date(100 + version.year, version.month, version.day).toGMTString();
Settings.IMP.BUILD = "https://ci.athion.net/job/FastAsyncWorldEdit-Breaking/" + version.build;
@ -361,7 +340,7 @@ public class Fawe {
try {
String arch = System.getenv("PROCESSOR_ARCHITECTURE");
String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432");
boolean x86OS = arch.endsWith("64") || wow64Arch != null && wow64Arch.endsWith("64") ? false : true;
boolean x86OS = !(arch.endsWith("64") || wow64Arch != null && wow64Arch.endsWith("64"));
boolean x86JVM = System.getProperty("sun.arch.data.model").equals("32");
if (x86OS != x86JVM) {
debug("====== UPGRADE TO 64-BIT JAVA ======");
@ -403,7 +382,7 @@ public class Fawe {
}
} catch (Throwable e) {
debug("====== MEMORY LISTENER ERROR ======");
MainUtil.handleError(e, false);
e.printStackTrace();
debug("===================================");
debug("FAWE needs access to the JVM memory system:");
debug(" - Change your Java security settings");
@ -422,7 +401,7 @@ public class Fawe {
}
public static boolean isMainThread() {
return INSTANCE != null ? INSTANCE.thread == Thread.currentThread() : true;
return INSTANCE == null || INSTANCE.thread == Thread.currentThread();
}
/**

View File

@ -4,10 +4,8 @@ import com.boydti.fawe.config.BBC;
import com.boydti.fawe.config.Settings;
import com.boydti.fawe.example.NMSMappedFaweQueue;
import com.boydti.fawe.example.NMSRelighter;
import com.boydti.fawe.object.FaweLocation;
import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.object.FaweQueue;
import com.boydti.fawe.object.PseudoRandom;
import com.boydti.fawe.object.RegionWrapper;
import com.boydti.fawe.object.changeset.DiskStorageHistory;
import com.boydti.fawe.object.schematic.Schematic;
@ -37,8 +35,11 @@ import com.sk89q.worldedit.internal.registry.AbstractFactory;
import com.sk89q.worldedit.internal.registry.InputParser;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.AbstractWorld;
import com.sk89q.worldedit.world.World;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
@ -67,7 +68,7 @@ public class FaweAPI {
*
* @param world
* @return A new EditSessionBuilder
* @see com.boydti.fawe.util.EditSessionBuilder
* @see EditSessionBuilder
*/
public static EditSessionBuilder getEditSessionBuilder(World world) {
return new EditSessionBuilder(world);
@ -182,7 +183,7 @@ public class FaweAPI {
* @param world The name of the world
* @param autoqueue If it should start dispatching before you enqueue it.
* @return
* @see com.boydti.fawe.object.FaweQueue#enqueue()
* @see FaweQueue#enqueue()
*/
public static FaweQueue createQueue(World world, boolean autoqueue) {
return SetQueue.IMP.getNewQueue(world, true, autoqueue);
@ -191,11 +192,6 @@ public class FaweAPI {
public static World getWorld(String worldName) {
Platform platform = WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.WORLD_EDITING);
List<? extends World> worlds = platform.getWorlds();
for (World current : worlds) {
if (Fawe.imp().getWorldName(current).equals(worldName)) {
return WorldWrapper.wrap(current);
}
}
for (World current : worlds) {
if (current.getName().equals(worldName)) {
return WorldWrapper.wrap(current);
@ -220,8 +216,8 @@ public class FaweAPI {
*
* @param file
* @return
* @see com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat
* @see com.boydti.fawe.object.schematic.Schematic
* @see ClipboardFormat
* @see Schematic
*/
public static Schematic load(File file) throws IOException {
return ClipboardFormats.findByFile(file).load(file);
@ -245,15 +241,6 @@ public class FaweAPI {
return MemUtil.isMemoryLimited();
}
/**
* Use ThreadLocalRandom instead
*
*/
@Deprecated
public static PseudoRandom getFastRandom() {
throw new UnsupportedOperationException("Please Use ThreadLocalRandom instead.");
}
/**
* Get a player's allowed WorldEdit region
*
@ -271,7 +258,7 @@ public class FaweAPI {
*
* @param extent
* @param reason
* @see com.sk89q.worldedit.EditSession#getRegionExtent() To get the FaweExtent for an EditSession
* @see EditSession#getRegionExtent() To get the FaweExtent for an EditSession
*/
public static void cancelEdit(Extent extent, BBC reason) {
try {
@ -332,8 +319,13 @@ public class FaweAPI {
* Reading only part of the file will result in unreliable bounds info for large edits
* @return
*/
public static List<DiskStorageHistory> getBDFiles(FaweLocation origin, UUID user, int radius, long timediff, boolean shallow) {
File history = MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.HISTORY + File.separator + origin.world);
public static List<DiskStorageHistory> getBDFiles(Location origin, UUID user, int radius, long timediff, boolean shallow) {
Extent extent = origin.getExtent();
if (!(extent instanceof World)) {
throw new IllegalArgumentException("Origin is not a valid world");
}
World world = (World) extent;
File history = MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.HISTORY + File.separator + Fawe.imp().getWorldName(world));
if (!history.exists()) {
return new ArrayList<>();
}
@ -364,7 +356,6 @@ public class FaweAPI {
}
}
}
World world = origin.getWorld();
files.sort((a, b) -> {
String aName = a.getName();
String bName = b.getName();
@ -373,7 +364,7 @@ public class FaweAPI {
long value = aI - bI;
return value == 0 ? 0 : value < 0 ? -1 : 1;
});
RegionWrapper bounds = new RegionWrapper(origin.x - radius, origin.x + radius, origin.z - radius, origin.z + radius);
RegionWrapper bounds = new RegionWrapper(origin.getBlockX() - radius, origin.getBlockX() + radius, origin.getBlockZ() - radius, origin.getBlockZ() + radius);
RegionWrapper boundsPlus = new RegionWrapper(bounds.minX - 64, bounds.maxX + 512, bounds.minZ - 64, bounds.maxZ + 512);
HashSet<RegionWrapper> regionSet = Sets.<RegionWrapper>newHashSet(bounds);
ArrayList<DiskStorageHistory> result = new ArrayList<>();
@ -410,7 +401,7 @@ public class FaweAPI {
* @param uuid
* @param index
* @return
* @see com.boydti.fawe.object.changeset.DiskStorageHistory#toEditSession(com.boydti.fawe.object.FawePlayer)
* @see DiskStorageHistory#toEditSession(FawePlayer)
*/
public static DiskStorageHistory getChangeSetFromDisk(World world, UUID uuid, int index) {
return new DiskStorageHistory(world, uuid, index);
@ -527,25 +518,4 @@ public class FaweAPI {
return BBC.values();
}
/**
* @see #getEditSessionBuilder(com.sk89q.worldedit.world.World)
* @deprecated
*/
@Deprecated
public static EditSession getNewEditSession(@Nonnull FawePlayer player) {
if (player == null) {
throw new IllegalArgumentException("Player may not be null");
}
return player.getNewEditSession();
}
/**
* @see #getEditSessionBuilder(com.sk89q.worldedit.world.World)
* @deprecated
*/
@Deprecated
public static EditSession getNewEditSession(World world) {
return WorldEdit.getInstance().getEditSessionFactory().getEditSession(world, -1);
}
}

View File

@ -13,7 +13,7 @@ public class FaweVersion {
public FaweVersion(String version, String commit, String date) {
String[] split = version.substring(version.indexOf('=') + 1).split("\\.");
this.build = Integer.parseInt(split[1]);
this.build = Integer.parseInt(split[2]);
this.hash = Integer.parseInt(commit.substring(commit.indexOf('=') + 1), 16);
String[] split1 = date.substring(date.indexOf('=') + 1).split("\\.");
this.year = Integer.parseInt(split1[0]);
@ -30,9 +30,12 @@ public class FaweVersion {
}
}
@Override
public String toString() {
return "FastAsyncWorldEdit-" + year + "." + month + "." + day + "-" + Integer.toHexString(hash) + "-" + build;
@Override public String toString() {
if (hash == 0 && build == 0) {
return "FastAsyncWorldEdit-1.13-NoVer-SNAPSHOT";
} else {
return "FastAsyncWorldEdit-1.13" + build;
}
}
public boolean isNewer(FaweVersion other) {

View File

@ -37,8 +37,6 @@ public interface IFawe {
default ImageViewer getImageViewer(FawePlayer player) { return null; }
default void registerPacketListener() {}
default int getPlayerCount() {
return Fawe.get().getCachedPlayers().size();
}

View File

@ -111,7 +111,7 @@ public class AnvilCommands {
}
CuboidRegion cuboid = (CuboidRegion) selection;
RegionWrapper wrappedRegion = new RegionWrapper(cuboid.getMinimumPoint(), cuboid.getMaximumPoint());
String worldName = Fawe.imp().getWorldName(editSession.getWorld());
String worldName = editSession.getWorld().getName();
FaweQueue tmp = SetQueue.IMP.getNewQueue(worldName, true, false);
MCAQueue queue = new MCAQueue(tmp);
FawePlayer<Object> fp = FawePlayer.wrap(player);
@ -127,7 +127,7 @@ public class AnvilCommands {
if (session == null || session.hasFastMode()) {
run.accept(new NullAnvilHistory());
} else {
AnvilHistory history = new AnvilHistory(Fawe.imp().getWorldName(world), fp.getUUID());
AnvilHistory history = new AnvilHistory(world.getName(), fp.getUUID());
run.accept(history);
session.remember(fp.getPlayer(), world, history, fp.getLimit());
}
@ -157,7 +157,7 @@ public class AnvilCommands {
// final FaweBlockMatcher matchTo = FaweBlockMatcher.setBlocks(worldEdit.getBlocks(player, to, true));
// ReplaceSimpleFilter filter = new ReplaceSimpleFilter(matchFrom, matchTo);
// ReplaceSimpleFilter result = runWithWorld(player, folder, filter, true);
// if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
// if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
@Command(
@ -173,16 +173,11 @@ public class AnvilCommands {
ClipboardRemapper mapper;
ClipboardRemapper.RemapPlatform from;
ClipboardRemapper.RemapPlatform to;
if (Fawe.imp().getPlatform().equalsIgnoreCase("nukkit")) {
from = ClipboardRemapper.RemapPlatform.PC;
to = ClipboardRemapper.RemapPlatform.PE;
} else {
from = ClipboardRemapper.RemapPlatform.PE;
to = ClipboardRemapper.RemapPlatform.PC;
}
from = ClipboardRemapper.RemapPlatform.PE;
to = ClipboardRemapper.RemapPlatform.PC;
RemapFilter filter = new RemapFilter(from, to);
RemapFilter result = runWithWorld(player, folder, filter, true);
if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
@ -199,10 +194,9 @@ public class AnvilCommands {
)
@CommandPermissions("worldedit.anvil.deleteallunvisited")
public void deleteAllUnvisited(Player player, String folder, int inhabitedTicks, @Optional("60000") int fileDurationMillis) throws WorldEditException {
long chunkInactivityMillis = fileDurationMillis; // Use same value for now
DeleteUninhabitedFilter filter = new DeleteUninhabitedFilter(fileDurationMillis, inhabitedTicks, chunkInactivityMillis);
DeleteUninhabitedFilter filter = new DeleteUninhabitedFilter(fileDurationMillis, inhabitedTicks, fileDurationMillis);
DeleteUninhabitedFilter result = runWithWorld(player, folder, filter, true);
if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
@Command(
@ -218,12 +212,11 @@ public class AnvilCommands {
)
@CommandPermissions("worldedit.anvil.deleteallunclaimed")
public void deleteAllUnclaimed(Player player, int inhabitedTicks, @Optional("60000") int fileDurationMillis, @Switch('d') boolean debug) throws WorldEditException {
String folder = Fawe.imp().getWorldName(player.getWorld());
long chunkInactivityMillis = fileDurationMillis; // Use same value for now
DeleteUnclaimedFilter filter = new DeleteUnclaimedFilter(player.getWorld(), fileDurationMillis, inhabitedTicks, chunkInactivityMillis);
String folder = player.getWorld().getName();
DeleteUnclaimedFilter filter = new DeleteUnclaimedFilter(player.getWorld(), fileDurationMillis, inhabitedTicks, fileDurationMillis);
if (debug) filter.enableDebug();
DeleteUnclaimedFilter result = runWithWorld(player, folder, filter, true);
if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
@Command(
@ -239,12 +232,10 @@ public class AnvilCommands {
)
@CommandPermissions("worldedit.anvil.deleteunclaimed")
public void deleteUnclaimed(Player player, EditSession editSession, @Selection Region selection, int inhabitedTicks, @Optional("60000") int fileDurationMillis, @Switch('d') boolean debug) throws WorldEditException {
String folder = Fawe.imp().getWorldName(player.getWorld());
long chunkInactivityMillis = fileDurationMillis; // Use same value for now
DeleteUnclaimedFilter filter = new DeleteUnclaimedFilter(player.getWorld(), fileDurationMillis, inhabitedTicks, chunkInactivityMillis);
DeleteUnclaimedFilter filter = new DeleteUnclaimedFilter(player.getWorld(), fileDurationMillis, inhabitedTicks, fileDurationMillis);
if (debug) filter.enableDebug();
DeleteUnclaimedFilter result = runWithSelection(player, editSession, selection, filter);
if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
@Command(
@ -260,10 +251,10 @@ public class AnvilCommands {
)
@CommandPermissions("worldedit.anvil.deletealloldregions")
public void deleteAllOldRegions(Player player, String folder, String time) throws WorldEditException {
long duration = MainUtil.timeToSec(time) * 1000l;
long duration = MainUtil.timeToSec(time) * 1000L;
DeleteOldFilter filter = new DeleteOldFilter(duration);
DeleteOldFilter result = runWithWorld(player, folder, filter, true);
if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
@Command(
@ -276,14 +267,14 @@ public class AnvilCommands {
)
@CommandPermissions("worldedit.anvil.trimallplots")
public void trimAllPlots(Player player, @Switch('v') boolean deleteUnvisited) throws WorldEditException {
String folder = Fawe.imp().getWorldName(player.getWorld());
String folder = player.getWorld().getName();
int visitTime = deleteUnvisited ? 1 : -1;
PlotTrimFilter filter = new PlotTrimFilter(player.getWorld(), 0, visitTime, 600000);
// PlotTrimFilter result = runWithWorld(player, folder, filter, true);
FaweQueue defaultQueue = SetQueue.IMP.getNewQueue(folder, true, false);
MCAQueue queue = new MCAQueue(defaultQueue);
PlotTrimFilter result = queue.filterWorld(filter);
if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
@Command(
@ -294,7 +285,7 @@ public class AnvilCommands {
public void deleteBiome(Player player, String folder, BiomeType biome, @Switch('u') boolean unsafe) {
DeleteBiomeFilterSimple filter = new DeleteBiomeFilterSimple(biome);
DeleteBiomeFilterSimple result = runWithWorld(player, folder, filter, true, unsafe);
if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
@Command(
@ -305,7 +296,7 @@ public class AnvilCommands {
public void trimAllAir(Player player, String folder, @Switch('u') boolean unsafe) throws WorldEditException {
TrimAirFilter filter = new TrimAirFilter();
TrimAirFilter result = runWithWorld(player, folder, filter, true, unsafe);
if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
@Command(
@ -316,7 +307,7 @@ public class AnvilCommands {
public void debugfixroads(Player player, String folder) throws WorldEditException {
DebugFixP2Roads filter = new DebugFixP2Roads();
DebugFixP2Roads result = runWithWorld(player, folder, filter, true, true);
if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
@Command(
@ -335,7 +326,7 @@ public class AnvilCommands {
// List<String> split = StringMan.split(from, ',');
// filter = new MappedReplacePatternFilter(from, (RandomPattern) to, useData);
// } else {
// player.print(BBC.getPrefix() + "Must be a pattern list!");
// player.print("Must be a pattern list!");
// return;
// }
// } else {
@ -348,7 +339,7 @@ public class AnvilCommands {
// filter = new ReplacePatternFilter(matchFrom, to);
// }
// MCAFilterCounter result = runWithWorld(player, folder, filter, true);
// if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
// if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
//
@Command(
@ -373,7 +364,7 @@ public class AnvilCommands {
// filter = counter;
// }
// MCAFilterCounter result = runWithWorld(player, folder, filter, true);
// if (result != null) player.print(BBC.getPrefix() + BBC.SELECTION_COUNT.format(result.getTotal()));
// if (result != null) player.print(BBC.SELECTION_COUNT.format(result.getTotal()));
}
@Command(
@ -423,7 +414,7 @@ public class AnvilCommands {
}
};
MCAFilterCounter result = runWithSelection(player, editSession, selection, filter);
if (result != null) player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
if (result != null) player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
@Command(
@ -448,7 +439,7 @@ public class AnvilCommands {
// filter = counter;
// }
// MCAFilterCounter result = runWithSelection(player, editSession, selection, filter);
// if (result != null) player.print(BBC.getPrefix() + BBC.SELECTION_COUNT.format(result.getTotal()));
// if (result != null) player.print(BBC.SELECTION_COUNT.format(result.getTotal()));
}
//
@Command(
@ -514,7 +505,7 @@ public class AnvilCommands {
// ((c[1] * 10000) / total) / 100d,
// name == null ? "Unknown" : name,
// block.getType(), block.getData());
// player.print(BBC.getPrefix() + str);
// player.print(str);
// }
// } else {
// for (long[] c : map) {
@ -523,7 +514,7 @@ public class AnvilCommands {
// String.valueOf(c[1]),
// ((c[1] * 10000) / total) / 100d,
// block == null ? "Unknown" : block.getName(), c[0]);
// player.print(BBC.getPrefix() + str);
// player.print(str);
// }
// }
}
@ -545,7 +536,7 @@ public class AnvilCommands {
// ReplaceSimpleFilter filter = new ReplaceSimpleFilter(matchFrom, matchTo);
// MCAFilterCounter result = runWithSelection(player, editSession, selection, filter);
// if (result != null) {
// player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
// player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
// }
}
//
@ -563,7 +554,7 @@ public class AnvilCommands {
// List<String> split = StringMan.split(from, ',');
// filter = new MappedReplacePatternFilter(from, (RandomPattern) to, useData);
// } else {
// player.print(BBC.getPrefix() + "Must be a pattern list!");
// player.print("Must be a pattern list!");
// return;
// }
// } else {
@ -577,7 +568,7 @@ public class AnvilCommands {
// }
// MCAFilterCounter result = runWithSelection(player, editSession, selection, filter);
// if (result != null) {
// player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
// player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
// }
}
@ -592,7 +583,7 @@ public class AnvilCommands {
MCAFilterCounter filter = new SetPatternFilter(to);
MCAFilterCounter result = runWithSelection(player, editSession, selection, filter);
if (result != null) {
player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
}
@ -611,7 +602,7 @@ public class AnvilCommands {
RemoveLayerFilter filter = new RemoveLayerFilter(minY, maxY, id);
MCAFilterCounter result = runWithSelection(player, editSession, selection, filter);
if (result != null) {
player.print(BBC.getPrefix() + BBC.VISITOR_BLOCK.format(result.getTotal()));
player.print(BBC.VISITOR_BLOCK.format(result.getTotal()));
}
}
@ -627,7 +618,7 @@ public class AnvilCommands {
return;
}
CuboidRegion cuboid = (CuboidRegion) selection;
String worldName = Fawe.imp().getWorldName(editSession.getWorld());
String worldName = editSession.getWorld().getName();
FaweQueue tmp = SetQueue.IMP.getNewQueue(worldName, true, false);
MCAQueue queue = new MCAQueue(tmp);
BlockVector3 origin = session.getPlacementPosition(player);
@ -651,7 +642,7 @@ public class AnvilCommands {
// FawePlayer fp = FawePlayer.wrap(player);
// MCAClipboard clipboard = fp.getMeta(FawePlayer.METADATA_KEYS.ANVIL_CLIPBOARD);
// if (clipboard == null) {
// fp.sendMessage(BBC.getPrefix() + "You must first use `//anvil copy`");
// fp.sendMessage("You must first use `//anvil copy`");
// return;
// }
// CuboidRegion cuboid = clipboard.getRegion();
@ -676,4 +667,4 @@ public class AnvilCommands {
// });
// BBC.COMMAND_PASTE.send(player, player.getPosition().toBlockVector());
}
}
}

View File

@ -177,7 +177,7 @@ public class CFICommands extends MethodCommands {
@CommandPermissions("worldedit.anvil.cfi")
public void cancel(FawePlayer fp) throws ParameterException, IOException {
getSettings(fp).remove();
fp.sendMessage(BBC.getPrefix() + "Cancelled!");
fp.sendMessage("Cancelled!");
}
@Command(
@ -196,12 +196,12 @@ public class CFICommands extends MethodCommands {
if (folder != null) {
try {
generator.setFolder(folder);
fp.sendMessage(BBC.getPrefix() + "Generating " + folder);
fp.sendMessage("Generating " + folder);
generator.generate();
generator.setPacketViewer(null);
generator.setImageViewer(null);
settings.remove();
fp.sendMessage(BBC.getPrefix() + "Done!");
fp.sendMessage("Done!");
return true;
} catch (IOException e) {
throw new RuntimeException(e);
@ -215,8 +215,8 @@ public class CFICommands extends MethodCommands {
try {
new PlotLoader().load(fp, settings, function);
} catch (Throwable ignore) {
ignore.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
function.apply(generator.getFolder().getParentFile());
}
@ -879,7 +879,7 @@ public class CFICommands extends MethodCommands {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos );
byte[] data = baos.toByteArray();
fp.sendMessage(BBC.getPrefix() + "Please wait...");
fp.sendMessage("Please wait...");
URL url = ImgurUtility.uploadImage(data);
BBC.DOWNLOAD_LINK.send(fp, url);
}

View File

@ -75,7 +75,7 @@ public abstract class FaweParser<T> extends InputParser<T> {
}
}
}
inputs.add(toParse.substring(last, toParse.length()));
inputs.add(toParse.substring(last));
for (int i = 0; i < inputs.size(); i++) {
String full = inputs.get(i);
String command = full;

View File

@ -50,7 +50,7 @@ public class PlotLoader {
SinglePlotArea area = sManager.getArea();
PlotPlayer player = PlotPlayer.wrap(fp.parent);
fp.sendMessage(BBC.getPrefix() + "Claiming world");
fp.sendMessage("Claiming world");
Plot plot = TaskManager.IMP.sync(new RunnableVal<Plot>() {
@Override
public void run(Plot o) {
@ -65,12 +65,9 @@ public class PlotLoader {
area.setMeta("lastPlot", new PlotId(0, 0));
}
PlotId lastId = (PlotId) area.getMeta("lastPlot");
while (true) {
do {
lastId = Auto.getNextPlotId(lastId, 1);
if (area.canClaim(player, lastId, lastId)) {
break;
}
}
} while (!area.canClaim(player, lastId, lastId));
area.setMeta("lastPlot", lastId);
this.value = area.getPlot(lastId);
this.value.setOwner(player.getUUID());

View File

@ -4,18 +4,14 @@ import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweAPI;
import com.boydti.fawe.config.BBC;
import com.boydti.fawe.config.Settings;
import com.boydti.fawe.object.FaweCommand;
import com.boydti.fawe.object.FaweLocation;
import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.object.RegionWrapper;
import com.boydti.fawe.object.RunnableVal;
import com.boydti.fawe.object.*;
import com.boydti.fawe.object.changeset.DiskStorageHistory;
import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.MathMan;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import java.util.Arrays;
import java.util.List;
@ -65,16 +61,16 @@ public class Rollback extends FaweCommand {
return false;
}
player.deleteMeta(FawePlayer.METADATA_KEYS.ROLLBACK);
final FaweLocation origin = player.getLocation();
Location origin = player.getPlayer().getLocation();
rollback(player, !player.hasPermission("fawe.rollback.deep"), Arrays.copyOfRange(args, 1, args.length), new RunnableVal<List<DiskStorageHistory>>() {
@Override
public void run(List<DiskStorageHistory> edits) {
long total = 0;
player.sendMessage("&d=| Username | Bounds | Distance | Changes | Age |=");
for (DiskStorageHistory edit : edits) {
DiskStorageHistory.DiskStorageSummary summary = edit.summarize(new RegionWrapper(origin.x, origin.x, origin.z, origin.z), !player.hasPermission("fawe.rollback.deep"));
DiskStorageHistory.DiskStorageSummary summary = edit.summarize(new RegionWrapper(origin.getBlockX(), origin.getBlockX(), origin.getBlockZ(), origin.getBlockZ()), !player.hasPermission("fawe.rollback.deep"));
RegionWrapper region = new RegionWrapper(summary.minX, summary.maxX, summary.minZ, summary.maxZ);
int distance = region.distance(origin.x, origin.z);
int distance = region.distance(origin.getBlockX(), origin.getBlockZ());
String name = Fawe.imp().getName(edit.getUUID());
long seconds = (System.currentTimeMillis() - edit.getBDFile().lastModified()) / 1000;
total += edit.getBDFile().length();
@ -106,7 +102,7 @@ public class Rollback extends FaweCommand {
BBC.NO_PERM.send(player, "fawe.rollback.perform");
return false;
}
final List<DiskStorageHistory> edits = (List<DiskStorageHistory>) player.getMeta(FawePlayer.METADATA_KEYS.ROLLBACK);
final List<DiskStorageHistory> edits = player.getMeta(FawePlayer.METADATA_KEYS.ROLLBACK);
player.deleteMeta(FawePlayer.METADATA_KEYS.ROLLBACK);
if (edits == null) {
BBC.COMMAND_SYNTAX.send(player, "/frb info u:<uuid> r:<radius> t:<time>");
@ -137,8 +133,8 @@ public class Rollback extends FaweCommand {
UUID user = null;
int radius = Integer.MAX_VALUE;
long time = Long.MAX_VALUE;
for (int i = 0; i < args.length; i++) {
String[] split = args[i].split(":");
for (String arg : args) {
String[] split = arg.split(":");
if (split.length != 2) {
BBC.COMMAND_SYNTAX.send(player, "/frb <info|undo> u:<uuid> r:<radius> t:<time>");
return;
@ -153,7 +149,7 @@ public class Rollback extends FaweCommand {
} else {
user = Fawe.imp().getUUID(split[1]);
}
} catch (IllegalArgumentException e) {
} catch (IllegalArgumentException ignored) {
}
if (user == null) {
player.sendMessage("&dInvalid user: " + split[1]);
@ -181,7 +177,7 @@ public class Rollback extends FaweCommand {
}
}
}
FaweLocation origin = player.getLocation();
Location origin = player.getLocation();
List<DiskStorageHistory> edits = FaweAPI.getBDFiles(origin, user, radius, time, shallow);
if (edits == null) {
player.sendMessage("&cToo broad, try refining your search!");

View File

@ -4,13 +4,13 @@ import com.boydti.fawe.Fawe;
import com.boydti.fawe.configuration.MemorySection;
import com.boydti.fawe.configuration.file.YamlConfiguration;
import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.object.PseudoRandom;
import com.boydti.fawe.object.RunnableVal3;
import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.StringMan;
import com.boydti.fawe.util.chat.Message;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sk89q.worldedit.extension.platform.Actor;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@ -379,51 +379,25 @@ public enum BBC {
/**
* Translated
*/
private String s;
private String translatedMessage;
/**
* Default
*/
private String d;
private String defaultMessage;
/**
* What locale category should this translation fall under
*/
private String cat;
/**
* Should the string be prefixed?
*/
private boolean prefix;
/**
* Constructor for custom strings.
*/
BBC() {
/*
* use setCustomString();
*/
}
private String category;
/**
* Constructor
*
* @param d default
* @param prefix use prefix
* @param defaultMessage default
*/
BBC(final String d, final boolean prefix, final String cat) {
this.d = d;
if (this.s == null) {
this.s = d;
}
this.prefix = prefix;
this.cat = cat.toLowerCase();
}
/**
* Constructor
*
* @param d default
*/
BBC(final String d, final String cat) {
this(d, true, cat.toLowerCase());
BBC(final String defaultMessage, final String category) {
this.defaultMessage = defaultMessage;
this.translatedMessage = defaultMessage;
this.category = category.toLowerCase();
}
public String f(final Object... args) {
@ -431,7 +405,7 @@ public enum BBC {
}
public String format(final Object... args) {
String m = this.s;
String m = this.translatedMessage;
for (int i = args.length - 1; i >= 0; i--) {
if (args[i] == null) {
continue;
@ -458,7 +432,7 @@ public enum BBC {
final HashSet<String> toRemove = new HashSet<>();
for (final BBC c : all) {
allNames.add(c.name());
allCats.add(c.cat.toLowerCase());
allCats.add(c.category.toLowerCase());
}
final HashSet<BBC> captions = new HashSet<>();
boolean changed = false;
@ -471,13 +445,13 @@ public enum BBC {
final String node = split[split.length - 1].toUpperCase();
final BBC caption = allNames.contains(node) ? valueOf(node) : null;
if (caption != null) {
if (!split[0].equalsIgnoreCase(caption.cat)) {
if (!split[0].equalsIgnoreCase(caption.category)) {
changed = true;
yml.set(key, null);
yml.set(caption.cat + "." + caption.name().toLowerCase(), value);
yml.set(caption.category + "." + caption.name().toLowerCase(), value);
}
captions.add(caption);
caption.s = (String) value;
caption.translatedMessage = (String) value;
} else {
toRemove.add(key);
}
@ -489,15 +463,15 @@ public enum BBC {
for (final BBC caption : all) {
if (!captions.contains(caption)) {
changed = true;
yml.set(caption.cat + "." + caption.name().toLowerCase(), caption.d);
yml.set(caption.category + "." + caption.name().toLowerCase(), caption.defaultMessage);
}
caption.s = StringMan.replaceFromMap(caption.s, replacements);
caption.translatedMessage = StringMan.replaceFromMap(caption.translatedMessage, replacements);
}
if (changed) {
yml.save(file);
}
} catch (final Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -524,7 +498,7 @@ public enum BBC {
}
public String s() {
return this.s;
return this.translatedMessage;
}
public Message m(Object... args) {
@ -532,15 +506,11 @@ public enum BBC {
}
public String original() {
return d;
return defaultMessage;
}
public boolean usePrefix() {
return this.prefix;
}
public String getCat() {
return this.cat;
public String getCategory() {
return this.category;
}
public BBC or(BBC... others) {
@ -559,11 +529,7 @@ public enum BBC {
Method method = actor.getClass().getMethod("print", String.class);
method.setAccessible(true);
method.invoke(actor, (PREFIX.isEmpty() ? "" : PREFIX.s() + " ") + this.format(args));
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
@ -583,6 +549,16 @@ public enum BBC {
player.sendMessage((PREFIX.isEmpty() ? "" : PREFIX.s() + " ") + this.format(args));
}
}
public void send(final Actor player, final Object... args) {
if (isEmpty()) {
return;
}
if (player == null) {
Fawe.debug(this.format(args));
} else {
player.print(this.format(args));
}
}
public static char getCode(String name) {
switch (name) {
@ -700,7 +676,7 @@ public enum BBC {
}
for (Map.Entry<String, Object> entry2 : obj.entrySet()) {
if (StringMan.isEqualIgnoreCaseToAny(entry2.getKey(), "bold", "italic", "underlined", "strikethrough", "obfuscated")) {
boolean newValue = Boolean.valueOf((String) entry2.getValue());
boolean newValue = Boolean.parseBoolean((String) entry2.getValue());
if (properties.put(entry2.getKey(), newValue) != newValue) {
if (newValue) {
char code = BBC.getCode(entry2.getKey().toUpperCase());

View File

@ -441,7 +441,7 @@ public class Config {
}
/**
* Set some field to be accesible
* Set some field to be accessible
*
* @param field
* @throws NoSuchFieldException

View File

@ -339,11 +339,6 @@ public class Settings extends Config {
"Allows brushes to be persistent (default: true)",
})
public boolean PERSISTENT_BRUSHES = true;
@Comment({
"[SAFE] Enable CUI without needing the mod installed (Requires ProtocolLib)",
})
public boolean VANILLA_CUI = false;
@Comment({
"Disable using native libraries",
@ -502,4 +497,4 @@ public class Settings extends Config {
}
return limit;
}
}
}

View File

@ -11,7 +11,7 @@ public class DBHandler {
private Map<String, RollbackDatabase> databases = new ConcurrentHashMap<>(8, 0.9f, 1);
public RollbackDatabase getDatabase(World world) {
String worldName = Fawe.imp().getWorldName(world);
String worldName = world.getName();
RollbackDatabase database = databases.get(worldName);
if (database != null) {
return database;

View File

@ -52,9 +52,9 @@ public class RollbackDatabase extends AsyncNotifyQueue {
public RollbackDatabase(final World world) throws SQLException, ClassNotFoundException {
this.prefix = "";
this.worldName = Fawe.imp().getWorldName(world);
this.worldName = world.getName();
this.world = world;
this.dbLocation = MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.HISTORY + File.separator + Fawe.imp().getWorldName(world) + File.separator + "summary.db");
this.dbLocation = MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.HISTORY + File.separator + world.getName() + File.separator + "summary.db");
connection = openConnection();
CREATE_TABLE = "CREATE TABLE IF NOT EXISTS `" + prefix + "edits` (`player` BLOB(16) NOT NULL,`id` INT NOT NULL,`x1` INT NOT NULL,`y1` INT NOT NULL,`z1` INT NOT NULL,`x2` INT NOT NULL,`y2` INT NOT NULL,`z2` INT NOT NULL,`time` INT NOT NULL, PRIMARY KEY (player, id))";
INSERT_EDIT = "INSERT OR REPLACE INTO `" + prefix + "edits` (`player`,`id`,`x1`,`y1`,`z1`,`x2`,`y2`,`z2`,`time`) VALUES(?,?,?,?,?,?,?,?,?)";

View File

@ -45,7 +45,7 @@ public class DefaultFaweQueueMap implements IFaweQueueMap {
};
@Override
public Collection<FaweChunk> getFaweCunks() {
public Collection<FaweChunk> getFaweChunks() {
synchronized (blocks) {
return new HashSet<>(blocks.values());
}

View File

@ -6,7 +6,7 @@ import java.util.Collection;
public interface IFaweQueueMap {
Collection<FaweChunk> getFaweCunks();
Collection<FaweChunk> getFaweChunks();
void forEachChunk(RunnableVal<FaweChunk> onEach);

View File

@ -84,16 +84,16 @@ public abstract class IntFaweChunk<T, V extends FaweQueue> extends FaweChunk<T>
public int getTotalCount() {
int total = 0;
for (int i = 0; i < count.length; i++) {
total += Math.min(4096, this.count[i]);
for (short value : count) {
total += Math.min(4096, value);
}
return total;
}
public int getTotalAir() {
int total = 0;
for (int i = 0; i < air.length; i++) {
total += Math.min(4096, this.air[i]);
for (short value : air) {
total += Math.min(4096, value);
}
return total;
}

View File

@ -10,7 +10,6 @@ import com.boydti.fawe.object.RunnableVal;
import com.boydti.fawe.object.RunnableVal2;
import com.boydti.fawe.object.exception.FaweException;
import com.boydti.fawe.object.extent.LightingExtent;
import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.MathMan;
import com.boydti.fawe.util.SetQueue;
import com.boydti.fawe.util.TaskManager;
@ -84,7 +83,7 @@ public abstract class MappedFaweQueue<WORLD, CHUNK, CHUNKSECTIONS, SECTION> impl
public MappedFaweQueue(final World world, IFaweQueueMap map) {
this.weWorld = world;
if (world != null) this.world = Fawe.imp().getWorldName(world);
if (world != null) this.world = world.getName();
if (map == null) {
map = getSettings().PREVENT_CRASHES ? new WeakFaweQueueMap(this) : new DefaultFaweQueueMap(this);
}
@ -102,7 +101,7 @@ public abstract class MappedFaweQueue<WORLD, CHUNK, CHUNKSECTIONS, SECTION> impl
@Override
public Collection<FaweChunk> getFaweChunks() {
return map.getFaweCunks();
return map.getFaweChunks();
}
@Override
@ -229,7 +228,7 @@ public abstract class MappedFaweQueue<WORLD, CHUNK, CHUNKSECTIONS, SECTION> impl
try {
task.run();
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
}
@ -246,7 +245,7 @@ public abstract class MappedFaweQueue<WORLD, CHUNK, CHUNKSECTIONS, SECTION> impl
try {
run.run();
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
}

View File

@ -1,17 +1,10 @@
package com.boydti.fawe.example;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.object.FaweChunk;
import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.TaskManager;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public abstract class NMSMappedFaweQueue<WORLD, CHUNK, CHUNKSECTION, SECTION> extends MappedFaweQueue<WORLD, CHUNK, CHUNKSECTION, SECTION> {
private final int maxY;
@ -104,7 +97,7 @@ public abstract class NMSMappedFaweQueue<WORLD, CHUNK, CHUNKSECTION, SECTION> ex
try {
refreshChunk(fc);
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}

View File

@ -48,7 +48,7 @@ public class WeakFaweQueueMap implements IFaweQueueMap {
};
@Override
public Collection<FaweChunk> getFaweCunks() {
public Collection<FaweChunk> getFaweChunks() {
HashSet<FaweChunk> set = new HashSet<>();
synchronized (blocks) {
Iterator<Map.Entry<Long, Reference<FaweChunk>>> iter = blocks.entrySet().iterator();

View File

@ -1,44 +0,0 @@
package com.boydti.fawe.installer;
import com.boydti.fawe.Fawe;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.prefs.Preferences;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.DirectoryChooser;
public abstract class BrowseButton extends InteractiveButton {
private final String id;
public BrowseButton(String id) {
super("Browse");
this.id = id;
}
public abstract void onSelect(File folder);
@Override
public void actionPerformed(ActionEvent e) {
Preferences prefs = Preferences.userRoot().node(Fawe.class.getName());
String lastUsed = prefs.get("LAST_USED_FOLDER", null);
final File lastFile = lastUsed == null ? null : new File(lastUsed).getParentFile();
browse(lastFile);
}
public void browse(File from) {
DirectoryChooser folderChooser = new DirectoryChooser();
folderChooser.setInitialDirectory(from);
new JFXPanel(); // Init JFX Platform
Platform.runLater(() -> {
File file = folderChooser.showDialog(null);
if (file != null && file.exists()) {
File parent = file.getParentFile();
if (parent == null) parent = file;
Preferences.userRoot().node(Fawe.class.getName()).put("LAST_USED_FOLDER" + id, parent.getPath());
onSelect(file);
}
});
}
}

View File

@ -1,16 +0,0 @@
package com.boydti.fawe.installer;
import java.awt.Color;
import java.awt.event.ActionEvent;
public class CloseButton extends InteractiveButton {
public CloseButton() {
super("X");
setColor(new Color(0x66, 0x33, 0x33));
}
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}

View File

@ -1,30 +0,0 @@
package com.boydti.fawe.installer;
import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
private BufferedImage image;
public ImagePanel(BufferedImage image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.6f));
g.drawImage(image, 0, 0, getWidth(), getWidth(), this); // see javadoc for more info on the parameters
}
}

View File

@ -1,360 +0,0 @@
package com.boydti.fawe.installer;
import com.boydti.fawe.FaweVersion;
import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.StringMan;
import com.sk89q.worldedit.WorldEdit;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
public class InstallerFrame extends JFrame {
private final InvisiblePanel loggerPanel;
private Color LIGHT_GRAY = new Color(0x66, 0x66, 0x66);
private Color GRAY = new Color(0x44, 0x44, 0x46);
private Color DARK_GRAY = new Color(0x33, 0x33, 0x36);
private Color DARKER_GRAY = new Color(0x26, 0x26, 0x28);
private Color INVISIBLE = new Color(0, 0, 0, 0);
private Color OFF_WHITE = new Color(200, 200, 200);
private JTextArea loggerTextArea;
private BrowseButton browse;
public InstallerFrame() throws Exception {
final MovablePanel movable = new MovablePanel(this);
Container content = this.getContentPane();
content.add(movable);
this.setSize(480, 320);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setUndecorated(true);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - this.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - this.getHeight()) / 2);
this.setLocation(x, y);
this.setVisible(true);
this.setOpacity(0);
movable.setBackground(DARK_GRAY);
movable.setLayout(new BorderLayout());
fadeIn();
JPanel topBar = new InvisiblePanel(new BorderLayout());
{
JPanel topBarLeft = new InvisiblePanel();
JPanel topBarRight = new InvisiblePanel();
JLabel title = new JLabel("FastAsyncWorldEdit Installer");
title.setHorizontalAlignment(SwingConstants.CENTER);
title.setAlignmentX(Component.RIGHT_ALIGNMENT);
title.setForeground(LIGHT_GRAY);
MinimizeButton minimize = new MinimizeButton(this);
CloseButton exit = new CloseButton();
topBarLeft.add(title);
topBarRight.add(minimize);
topBarRight.add(exit);
topBar.add(topBarLeft, BorderLayout.CENTER);
topBar.add(topBarRight, BorderLayout.EAST);
}
final JPanel mainContent = new InvisiblePanel(new BorderLayout());
{
final JPanel browseContent = new InvisiblePanel(new BorderLayout());
File dir = MainUtil.getWorkingDirectory("minecraft");
JLabel folder = new JLabel("Folder: ");
folder.setForeground(OFF_WHITE);
final InteractiveButton text = new InteractiveButton(dir.getPath(), DARKER_GRAY) {
@Override
public void actionPerformed(ActionEvent e) {
browse.actionPerformed(e);
}
};
text.setForeground(OFF_WHITE);
text.setBackground(DARKER_GRAY);
text.setOpaque(true);
text.setBorder(new EmptyBorder(4, 4, 4, 4));
browse = new BrowseButton("") {
@Override
public void onSelect(File folder) {
text.setText(folder.getPath());
movable.repaint();
}
};
InteractiveButton install = new InteractiveButton(">> Create Profile <<", DARKER_GRAY) {
@Override
public void actionPerformed(ActionEvent e) {
try {
install(text.getText());
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
browseContent.add(folder, BorderLayout.WEST);
browseContent.add(text, BorderLayout.CENTER);
browseContent.add(browse, BorderLayout.EAST);
final JPanel installContent = new InvisiblePanel(new FlowLayout());
install.setPreferredSize(new Dimension(416, 32));
installContent.add(install);
installContent.setBorder(new EmptyBorder(10, 0, 10, 0));
this.loggerPanel = new InvisiblePanel(new BorderLayout());
this.loggerPanel.setBackground(Color.GREEN);
loggerPanel.setPreferredSize(new Dimension(416, 160));
loggerTextArea = new JTextArea(12, 52);
loggerTextArea.setBackground(GRAY);
loggerTextArea.setForeground(DARKER_GRAY);
loggerTextArea.setFont(new Font(loggerTextArea.getFont().getName(), Font.PLAIN, 9));
JScrollPane scroll = new JScrollPane(loggerTextArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setBackground(DARK_GRAY);
scroll.setBorder(new EmptyBorder(0, 0, 0, 0));
loggerPanel.add(scroll);
loggerPanel.setVisible(false);
mainContent.setBorder(new EmptyBorder(6, 32, 6, 32));
mainContent.add(browseContent, BorderLayout.NORTH);
mainContent.add(installContent, BorderLayout.CENTER);
mainContent.add(loggerPanel, BorderLayout.SOUTH);
}
JPanel bottomBar = new InvisiblePanel();
{
try {
InputStream stream = getClass().getResourceAsStream("/fawe.properties");
java.util.Scanner scanner = new java.util.Scanner(stream).useDelimiter("\\A");
String versionString = scanner.next().trim();
scanner.close();
FaweVersion version = null;
String date = new Date(100 + version.year, version.month, version.day).toGMTString();
String build = "https://ci.athion.net/job/FastAsyncWorldEdit/" + version.build;
String commit = "https://github.com/boy0001/FastAsyncWorldedit/commit/" + Integer.toHexString(version.hash);
String footerMessage = "FAWE v" + version.year + "." + version.month + "." + version.day + " by Empire92 (c) 2017 (GPL v3.0)";
URL licenseUrl = new URL("https://github.com/boy0001/FastAsyncWorldedit/blob/master/LICENSE");
URLButton licenseButton = new URLButton(licenseUrl, footerMessage);
bottomBar.add(licenseButton);
} catch (Throwable ignore) {
ignore.printStackTrace();
}
URL chat = new URL("https://discord.gg/ngZCzbU");
URLButton chatButton = new URLButton(chat, "Chat");
bottomBar.add(chatButton);
URL wiki = new URL("https://github.com/boy0001/FastAsyncWorldedit/wiki");
URLButton wikiButton = new URLButton(wiki, "Wiki");
bottomBar.add(wikiButton);
URL issue = new URL("https://github.com/boy0001/FastAsyncWorldedit/issues/new");
URLButton issueButton = new URLButton(issue, "Report Issue");
bottomBar.add(issueButton);
}
// We want to add these a bit later
movable.add(topBar, BorderLayout.NORTH);
this.setVisible(true);
this.repaint();
movable.add(mainContent, BorderLayout.CENTER);
this.setVisible(true);
this.repaint();
movable.add(bottomBar, BorderLayout.SOUTH);
this.setVisible(true);
this.repaint();
}
private boolean newLine = false;
public void prompt(String message) {
JOptionPane.showMessageDialog(null, message);
}
public void debug(String m) {
System.out.println(m);
}
public void install(String name) throws Exception {
if (!loggerPanel.isVisible()) {
loggerPanel.setVisible(true);
this.repaint();
System.setOut(new TextAreaOutputStream(loggerTextArea));
}
if (name == null || name.isEmpty()) {
prompt("No folder selection");
return;
}
final File dirMc = new File(name);
if (!dirMc.exists()) {
prompt("Folder does not exist");
return;
}
if (!dirMc.isDirectory()) {
prompt("You must select a folder, not a file");
return;
}
Thread installThread = new Thread(new Runnable() {
@Override
public void run() {
List<String> supported = Arrays.asList("v1710", "v189", "v194", "v110", "v111");
String supportedString = null;
for (String version : supported) {
try {
Class.forName("com.boydti.fawe.forge." + version + ".ForgeChunk_All");
supportedString = version;
break;
} catch (ClassNotFoundException ignore) {
}
}
if (supportedString == null) {
prompt("This version of FAWE cannot be installed this way.");
return;
}
debug("Selected version " + supportedString);
URL forgeUrl;
URL worldEditUrl;
URL worldEditCuiUrl;
try {
switch (supportedString) {
case "v111":
forgeUrl = new URL("https://files.minecraftforge.net/maven/net/minecraftforge/forge/1.11.2-13.20.0.2201/forge-1.11.2-13.20.0.2201-installer.jar");
worldEditUrl = new URL("http://builds.enginehub.org/job/worldedit/9593/download/worldedit-forge-mc1.11-6.1.6-SNAPSHOT-dist.jar");
worldEditCuiUrl = new URL("https://addons-origin.cursecdn.com/files/2361/241/worldeditcuife-v1.0.6-mf-1.11.2-13.20.0.2201.jar");
break;
case "v110":
forgeUrl = new URL("http://files.minecraftforge.net/maven/net/minecraftforge/forge/1.10.2-12.18.3.2185/forge-1.10.2-12.18.3.2185-installer.jar");
worldEditUrl = new URL("http://builds.enginehub.org/job/worldedit/9395/download/worldedit-forge-mc1.10.2-6.1.4-SNAPSHOT-dist.jar");
worldEditCuiUrl = new URL("https://addons-origin.cursecdn.com/files/2361/239/WorldEditCuiFe-v1.0.6-mf-1.10.2-12.18.2.2125.jar");
break;
case "v194":
forgeUrl = new URL("https://files.minecraftforge.net/maven/net/minecraftforge/forge/1.9.4-12.17.0.2051/forge-1.9.4-12.17.0.2051-installer.jar");
worldEditUrl = new URL("http://builds.enginehub.org/job/worldedit/9171/download/worldedit-forge-mc1.9.4-6.1.3-SNAPSHOT-dist.jar");
worldEditCuiUrl = new URL("https://addons-origin.cursecdn.com/files/2361/236/WorldEditCuiFe-v1.0.6-mf-1.9.4-12.17.0.1976.jar");
break;
case "v189":
forgeUrl = new URL("https://files.minecraftforge.net/maven/net/minecraftforge/forge/1.8.9-11.15.1.1902-1.8.9/forge-1.8.9-11.15.1.1902-1.8.9-installer.jar");
worldEditUrl = new URL("http://builds.enginehub.org/job/worldedit/8755/download/worldedit-forge-mc1.8.9-6.1.1-dist.jar");
worldEditCuiUrl = new URL("https://addons-origin.cursecdn.com/files/2361/235/WorldEditCuiFe-v1.0.6-mf-1.8.9-11.15.1.1855.jar");
break;
case "v1710":
forgeUrl = new URL("https://files.minecraftforge.net/maven/net/minecraftforge/forge/1.7.10-10.13.4.1614-1.7.10/forge-1.7.10-10.13.4.1614-1.7.10-installer.jar");
worldEditUrl = new URL("http://builds.enginehub.org/job/worldedit/9194/download/worldedit-forge-mc1.7.10-6.1.2-SNAPSHOT-dist.jar");
worldEditCuiUrl = new URL("https://addons-origin.cursecdn.com/files/2361/234/WorldEditCuiFe-v1.0.6-mf-1.7.10-10.13.4.1566.jar");
break;
default:
return;
}
} catch (MalformedURLException e) {
e.printStackTrace();
return;
}
try { // install forge
debug("Downloading forge installer from:\n - https://files.minecraftforge.net/");
URLClassLoader loader = new URLClassLoader(new URL[]{forgeUrl});
debug("Connected");
Class<?> forgeInstallClass = loader.loadClass("net.minecraftforge.installer.ClientInstall");
debug("Found ClientInstall class");
Object forgeInstallInstance = forgeInstallClass.newInstance();
debug(forgeInstallInstance + " | " + forgeInstallClass + " | " + StringMan.getString(forgeInstallClass.getMethods()));
debug("Created instance " + forgeInstallInstance);
Method methodRun = forgeInstallClass.getDeclaredMethods()[0];//("run", File.class, Predicate.class);
Object alwaysTrue = loader.loadClass("com.google.common.base.Predicates").getDeclaredMethod("alwaysTrue").invoke(null);
methodRun.invoke(forgeInstallInstance, dirMc, alwaysTrue);
debug("Forge profile created, now installing WorldEdit");
} catch (Throwable e) {
e.printStackTrace();
prompt("[ERROR] Forge install failed, download from:\nhttps://files.minecraftforge.net/");
}
File mods = new File(dirMc, "mods");
if (!mods.exists()) {
debug("Creating mods directory");
mods.mkdirs();
} else {
for (File file : mods.listFiles()) {
String name = file.getName().toLowerCase();
if ((name.contains("worldedit") || name.contains("fawe"))) {
debug("Delete existing: " + file.getName());
file.delete();
}
}
}
try { // install worldedit
debug("Downloading WE-CUI from:\n - https://minecraft.curseforge.com/projects/worldeditcui-forge-edition");
try (ReadableByteChannel rbc = Channels.newChannel(worldEditCuiUrl.openStream())) {
try (FileOutputStream fos = new FileOutputStream(new File(mods, "WorldEditCUI.jar"))) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
}
debug("Successfully downloaded WorldEdit-CUI");
} catch (Throwable e) {
prompt("[ERROR] WorldEdit install failed, download from:\nhttp://builds.enginehub.org/job/worldedit");
}
try { // install worldedit
debug("Downloading WorldEdit from:\n - http://builds.enginehub.org/job/worldedit");
try (ReadableByteChannel rbc = Channels.newChannel(worldEditUrl.openStream())) {
try (FileOutputStream fos = new FileOutputStream(new File(mods, "WorldEdit.jar"))) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
}
debug("Successfully downloaded WorldEdit");
} catch (Throwable e) {
prompt("[ERROR] WorldEdit install failed, download from:\nhttp://builds.enginehub.org/job/worldedit");
}
try { // install FAWE
debug("Copying FastAsyncWorldEdit to mods directory");
File file = new File(InstallerFrame.class.getProtectionDomain().getCodeSource().getLocation().getPath());
debug(" - " + file.getPath());
MainUtil.copyFile(file, new File(mods, "FastAsyncWorldEdit.jar"));
debug("Installation complete!");
} catch (Throwable e) {
prompt("[ERROR] Copy installer failed, please copy this installer jar manually");
}
prompt("Installation complete!\nLaunch the game using the forge profile.");
}
});
installThread.start();
}
public void fadeIn() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (float i = 0; i <= 1; i += 0.001) {
InstallerFrame.this.setOpacity(i);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
public static void main(String[] args) throws Exception {
InstallerFrame window = new InstallerFrame();
}
}

View File

@ -1,68 +0,0 @@
package com.boydti.fawe.installer;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
public class InteractiveButton extends JButton implements ActionListener, MouseListener {
private Color background;
public InteractiveButton(String text) {
this(text, new Color(0, 0, 0, 0));
}
public InteractiveButton(String text, Color background) {
setText(text);
setBorderPainted(false);
setVisible(true);
setForeground(new Color(200, 200, 200));
addActionListener(this);
addMouseListener(this);
setFocusable(false);
if (background.getAlpha() != 0) {
this.background = background;
} else {
this.background = new Color(0x38, 0x38, 0x39);
}
setBackground(this.background);
}
public void setColor(Color background) {
setBackground(background);
this.background = background;
}
@Override
public void actionPerformed(ActionEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
setBackground(new Color(0x44, 0x44, 0x44));
}
@Override
public void mouseExited(MouseEvent e) {
setBackground(this.background);
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
setBackground(new Color(0x77, 0x77, 0x77));
}
@Override
public void mouseReleased(MouseEvent e) {
setBackground(new Color(0x33, 0x33, 0x36));
}
}

View File

@ -1,17 +0,0 @@
package com.boydti.fawe.installer;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import javax.swing.JPanel;
public class InvisiblePanel extends JPanel {
public InvisiblePanel(LayoutManager layout) {
super(layout);
setBackground(new Color(0, 0, 0, 0));
}
public InvisiblePanel() {
this(new FlowLayout());
}
}

View File

@ -1,60 +0,0 @@
package com.boydti.fawe.installer;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import javax.swing.JFileChooser;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import sun.swing.FilePane;
public class JSystemFileChooser extends JFileChooser {
public void updateUI(){
LookAndFeel old = UIManager.getLookAndFeel();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Throwable ex) {
old = null;
}
super.updateUI();
if(old != null){
FilePane filePane = findFilePane(this);
filePane.setViewType(FilePane.VIEWTYPE_DETAILS);
filePane.setViewType(FilePane.VIEWTYPE_LIST);
Color background = UIManager.getColor("Label.background");
setBackground(background);
setOpaque(true);
try {
UIManager.setLookAndFeel(old);
}
catch (UnsupportedLookAndFeelException ignored) {} // shouldn't get here
}
}
private static FilePane findFilePane(Container parent){
for(Component comp: parent.getComponents()){
if(FilePane.class.isInstance(comp)){
return (FilePane)comp;
}
if(comp instanceof Container){
Container cont = (Container)comp;
if(cont.getComponentCount() > 0){
FilePane found = findFilePane(cont);
if (found != null) {
return found;
}
}
}
}
return null;
}
}

View File

@ -1,19 +0,0 @@
package com.boydti.fawe.installer;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
public class MinimizeButton extends InteractiveButton {
private final JFrame window;
public MinimizeButton(JFrame window) {
super("-");
this.window = window;
}
@Override
public void actionPerformed(ActionEvent e) {
window.setState(Frame.ICONIFIED);
}
}

View File

@ -1,43 +0,0 @@
package com.boydti.fawe.installer;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MovablePanel extends JPanel {
private Point initialClick;
private JFrame parent;
public MovablePanel(final JFrame parent) {
this.parent = parent;
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
initialClick = e.getPoint();
getComponentAt(initialClick);
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
// get location of Window
int thisX = parent.getLocation().x;
int thisY = parent.getLocation().y;
// Determine how much the mouse moved since the initial click
int xMoved = (thisX + e.getX()) - (thisX + initialClick.x);
int yMoved = (thisY + e.getY()) - (thisY + initialClick.y);
// Move window to this position
int X = thisX + xMoved;
int Y = thisY + yMoved;
parent.setLocation(X, Y);
}
});
}
}

View File

@ -1,58 +0,0 @@
package com.boydti.fawe.installer;
import com.boydti.fawe.config.BBC;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JTextArea;
public class TextAreaOutputStream extends PrintStream {
public TextAreaOutputStream(final JTextArea textArea) {
super(new OutputStream() {
StringBuffer buffer = new StringBuffer();
ExecutorService executor = Executors.newSingleThreadExecutor();
AtomicBoolean updated = new AtomicBoolean();
AtomicBoolean waiting = new AtomicBoolean();
boolean lineColor = false;
@Override
public void write(int b) throws IOException {
buffer.append((char) b);
if (b == '\n') {
updated.set(true);
if (waiting.compareAndSet(false, true)) {
executor.submit(new Runnable() {
@Override
public void run() {
try {
updated.set(false);
int len = buffer.length();
textArea.append(BBC.stripColor(buffer.substring(0, len)));
buffer.delete(0, len);
textArea.setVisible(true);
textArea.repaint();
} finally {
waiting.set(false);
if (updated.get() && waiting.compareAndSet(false, true)) {
executor.submit(this);
}
}
}
});
}
} else {
updated.lazySet(true);
}
}
@Override
protected void finalize() throws Throwable {
executor.shutdownNow();
}
});
}
}

View File

@ -1,40 +0,0 @@
package com.boydti.fawe.installer;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
public class URLButton extends InteractiveButton {
private final URL url;
public URLButton(URL url, String text) {
super("<HTML>" + text + "</HTML>");
this.url = url;
setFont(new Font(getFont().getName(), Font.PLAIN, 9));
setForeground(new Color(0x77, 0x77, 0x77));
}
@Override
public void actionPerformed(ActionEvent event) {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(url.toURI());
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return;
}
Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
Clipboard systemClipboard = defaultToolkit.getSystemClipboard();
systemClipboard.setContents(new StringSelection(url.toString()), null);
}
}

View File

@ -293,8 +293,7 @@ public class CorruptSchematicStreamer {
int vx = 0, vy = 0, vz = 0;
for (int x = 0; x < factors.size(); x++) {
int xValue = factors.get(x);
for (int y = 0; y < factors.size(); y++) {
int yValue = factors.get(y);
for (int yValue : factors) {
long area = xValue * yValue;
if (volume % area == 0) {
int z = (int) (volume / area);

View File

@ -10,6 +10,7 @@ import com.boydti.fawe.object.clipboard.FaweClipboard;
import com.boydti.fawe.object.clipboard.MemoryOptimizedClipboard;
import com.boydti.fawe.object.io.FastByteArrayOutputStream;
import com.boydti.fawe.object.io.FastByteArraysInputStream;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.NBTInputStream;
@ -18,15 +19,17 @@ import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.registry.state.PropertyKey;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.*;
import com.sk89q.worldedit.world.block.BlockID;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypeSwitch;
import com.sk89q.worldedit.world.block.BlockTypeSwitchBuilder;
import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.entity.EntityTypes;
import com.sk89q.worldedit.world.item.ItemTypes;
import com.sk89q.worldedit.world.registry.BlockMaterial;
import com.sk89q.worldedit.world.registry.LegacyMapper;
import net.jpountz.lz4.LZ4BlockInputStream;
@ -227,14 +230,14 @@ public class SchematicStreamer extends NBTStreamer {
if (forwardType.hasProperty(PropertyKey.SHAPE) && forwardType.hasProperty(PropertyKey.FACING)) {
Direction forwardFacing = (Direction) forwardBlock.getState(PropertyKey.FACING);
if (forwardFacing == left) {
BlockStateHolder rightBlock = fc.getBlock(x + right.getBlockX(), y + right.getBlockY(), z + right.getBlockZ());
BlockStateHolder rightBlock = fc.getBlock(x + right.toBlockVector().getBlockX(), y + right.toBlockVector().getBlockY(), z + right.toBlockVector().getBlockZ());
BlockType rightType = rightBlock.getBlockType();
if (!rightType.hasProperty(PropertyKey.SHAPE) || rightBlock.getState(PropertyKey.FACING) != facing) {
fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "inner_left"));
}
return;
} else if (forwardFacing == right) {
BlockStateHolder leftBlock = fc.getBlock(x + left.getBlockX(), y + left.getBlockY(), z + left.getBlockZ());
BlockStateHolder leftBlock = fc.getBlock(x + left.toBlockVector().getBlockX(), y + left.toBlockVector().getBlockY(), z + left.toBlockVector().getBlockZ());
BlockType leftType = leftBlock.getBlockType();
if (!leftType.hasProperty(PropertyKey.SHAPE) || leftBlock.getState(PropertyKey.FACING) != facing) {
fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "inner_right"));
@ -248,14 +251,14 @@ public class SchematicStreamer extends NBTStreamer {
if (backwardsType.hasProperty(PropertyKey.SHAPE) && backwardsType.hasProperty(PropertyKey.FACING)) {
Direction backwardsFacing = (Direction) backwardsBlock.getState(PropertyKey.FACING);
if (backwardsFacing == left) {
BlockStateHolder rightBlock = fc.getBlock(x + right.getBlockX(), y + right.getBlockY(), z + right.getBlockZ());
BlockStateHolder rightBlock = fc.getBlock(x + right.toBlockVector().getBlockX(), y + right.toBlockVector().getBlockY(), z + right.toBlockVector().getBlockZ());
BlockType rightType = rightBlock.getBlockType();
if (!rightType.hasProperty(PropertyKey.SHAPE) || rightBlock.getState(PropertyKey.FACING) != facing) {
fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "outer_left"));
}
return;
} else if (backwardsFacing == right) {
BlockStateHolder leftBlock = fc.getBlock(x + left.getBlockX(), y + left.getBlockY(), z + left.getBlockZ());
BlockStateHolder leftBlock = fc.getBlock(x + left.toBlockVector().getBlockX(), y + left.toBlockVector().getBlockY(), z + left.toBlockVector().getBlockZ());
BlockType leftType = leftBlock.getBlockType();
if (!leftType.hasProperty(PropertyKey.SHAPE) || leftBlock.getState(PropertyKey.FACING) != facing) {
fc.setBlock(x, y, z, block.with(PropertyKey.SHAPE, "outer_right"));

View File

@ -21,6 +21,7 @@ import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.math.MutableBlockVector3;
import com.sk89q.worldedit.registry.state.PropertyKey;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockID;
import com.sk89q.worldedit.world.block.BlockState;
@ -249,8 +250,8 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr
public void setPacketViewer(FawePlayer player) {
this.player = player;
if (player != null) {
FaweLocation pos = player.getLocation();
this.chunkOffset = BlockVector2.at(1 + (pos.x >> 4), 1 + (pos.z >> 4));
Location pos = player.getLocation();
this.chunkOffset = BlockVector2.at(1 + (pos.getBlockX() >> 4), 1 + (pos.getBlockZ() >> 4));
}
}
@ -291,9 +292,9 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr
int OX = chunkOffset.getBlockX();
int OZ = chunkOffset.getBlockZ();
FaweLocation position = player.getLocation();
int pcx = (position.x >> 4) - OX;
int pcz = (position.z >> 4) - OZ;
Location position = player.getLocation();
int pcx = (position.getBlockX() >> 4) - OX;
int pcz = (position.getBlockZ() >> 4) - OZ;
int scx = Math.max(0, pcx - 15);
int scz = Math.max(0, pcz - 15);
@ -595,11 +596,11 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr
continue;
}
placed.add(x, z);
ClipboardHolder holder = clipboards.get(PseudoRandom.random.random(clipboards.size()));
ClipboardHolder holder = clipboards.get(ThreadLocalRandom.current().nextInt(clipboards.size()));
if (randomRotate) {
int rotate = PseudoRandom.random.random(4) * 90;
int rotate = ThreadLocalRandom.current().nextInt(4) * 90;
if (rotate != 0) {
holder.setTransform(new AffineTransform().rotateY(PseudoRandom.random.random(4) * 90));
holder.setTransform(new AffineTransform().rotateY(ThreadLocalRandom.current().nextInt(4) * 90));
} else {
holder.setTransform(identity);
}
@ -644,11 +645,11 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr
}
mutable.mutY(y + 1);
placed.add(x, z);
ClipboardHolder holder = clipboards.get(PseudoRandom.random.random(clipboards.size()));
ClipboardHolder holder = clipboards.get(ThreadLocalRandom.current().nextInt(clipboards.size()));
if (randomRotate) {
int rotate = PseudoRandom.random.random(4) * 90;
int rotate = ThreadLocalRandom.current().nextInt(4) * 90;
if (rotate != 0) {
holder.setTransform(new AffineTransform().rotateY(PseudoRandom.random.random(4) * 90));
holder.setTransform(new AffineTransform().rotateY(ThreadLocalRandom.current().nextInt(4) * 90));
} else {
holder.setTransform(identity);
}
@ -901,9 +902,9 @@ public class HeightMapMCAGenerator extends MCAWriter implements StreamChange, Dr
int OX = chunkOffset.getBlockX();
int OZ = chunkOffset.getBlockZ();
FaweLocation position = player.getLocation();
int pcx = (position.x >> 4) - OX;
int pcz = (position.z >> 4) - OZ;
Location position = player.getLocation();
int pcx = (position.getBlockX() >> 4) - OX;
int pcz = (position.getBlockZ() >> 4) - OZ;
int scx = Math.max(0, pcx - 10);
int scz = Math.max(0, pcz - 10);

View File

@ -6,7 +6,6 @@ import com.boydti.fawe.object.FaweChunk;
import com.boydti.fawe.object.FaweQueue;
import com.boydti.fawe.object.io.FastByteArrayOutputStream;
import com.boydti.fawe.object.number.MutableLong;
import com.boydti.fawe.util.ArrayUtil;
import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.MathMan;
import com.boydti.fawe.util.ReflectionUtils;
@ -108,8 +107,8 @@ public class MCAChunk extends FaweChunk<Void> {
out.writeNamedTagName("Sections", NBTConstants.TYPE_LIST);
nbtOut.getOutputStream().writeByte(NBTConstants.TYPE_COMPOUND);
int len = 0;
for (int layer = 0; layer < ids.length; layer++) {
if (ids[layer] != null) len++;
for (int[] id : ids) {
if (id != null) len++;
}
nbtOut.getOutputStream().writeInt(len);
for (int layer = 0; layer < ids.length; layer++) {
@ -191,8 +190,8 @@ public class MCAChunk extends FaweChunk<Void> {
setNibble(endIndex, thisSkyLight, (byte) 0);
setNibble(endIndex, thisBlockLight, (byte) 0);
}
ArrayUtil.fill(thisSkyLight, startIndexShift, endIndexShift + 1, (byte) 0);
ArrayUtil.fill(thisBlockLight, startIndexShift, endIndexShift + 1, (byte) 0);
Arrays.fill(thisSkyLight, startIndexShift, endIndexShift + 1, (byte) 0);
Arrays.fill(thisBlockLight, startIndexShift, endIndexShift + 1, (byte) 0);
}
}
continue;
@ -292,8 +291,8 @@ public class MCAChunk extends FaweChunk<Void> {
if (otherIds == null) {
if (currentIds != null) {
Arrays.fill(currentIds, indexStart, indexEnd, 0);
ArrayUtil.fill(skyLight[thisLayer], indexStartShift, indexEndShift, (byte) 0);
ArrayUtil.fill(blockLight[thisLayer], indexStartShift, indexEndShift, (byte) 0);
Arrays.fill(skyLight[thisLayer], indexStartShift, indexEndShift, (byte) 0);
Arrays.fill(blockLight[thisLayer], indexStartShift, indexEndShift, (byte) 0);
}
} else {
if (currentIds == null) {
@ -320,8 +319,8 @@ public class MCAChunk extends FaweChunk<Void> {
continue;
}
Arrays.fill(thisIds, thisStartIndex, thisStartIndex + 256, 0);
ArrayUtil.fill(this.skyLight[thisLayer], thisStartIndexShift, thisStartIndexShift + 128, (byte) 0);
ArrayUtil.fill(this.blockLight[thisLayer], thisStartIndexShift, thisStartIndexShift + 128, (byte) 0);
Arrays.fill(this.skyLight[thisLayer], thisStartIndexShift, thisStartIndexShift + 128, (byte) 0);
Arrays.fill(this.blockLight[thisLayer], thisStartIndexShift, thisStartIndexShift + 128, (byte) 0);
continue;
} else if (thisIds == null) {
ids[thisLayer] = thisIds = new int[4096];

View File

@ -14,7 +14,6 @@ import java.util.concurrent.ForkJoinPool;
public class MCAFilter<T> extends IterableThreadLocal<T> {
public void withPool(ForkJoinPool pool, MCAQueue queue) {
return;
}
/**

View File

@ -621,8 +621,8 @@ public class MCAQueue extends NMSMappedFaweQueue<FaweQueue, FaweChunk, FaweChunk
@Override
public boolean supports(Capability capability) {
switch (capability) {
case CHANGE_TASKS: return false;
if (capability == Capability.CHANGE_TASKS) {
return false;
}
return super.supports(capability);
}
@ -823,4 +823,4 @@ public class MCAQueue extends NMSMappedFaweQueue<FaweQueue, FaweChunk, FaweChunk
parentNMS.sendBlockUpdate(chunk, players);
}
}
}
}

View File

@ -80,7 +80,7 @@ public class MCAQueueMap implements IFaweQueueMap {
}
@Override
public Collection<FaweChunk> getFaweCunks() {
public Collection<FaweChunk> getFaweChunks() {
final List<FaweChunk> chunks = new ArrayList<>();
for (Map.Entry<Long, MCAFile> entry : mcaFileMap.entrySet()) {
MCAFile file = entry.getValue();
@ -93,7 +93,7 @@ public class MCAQueueMap implements IFaweQueueMap {
@Override
public void forEachChunk(RunnableVal<FaweChunk> onEach) {
for (FaweChunk chunk : getFaweCunks()) {
for (FaweChunk chunk : getFaweChunks()) {
onEach.run(chunk);
}
}

View File

@ -165,8 +165,7 @@ public abstract class MCAWriter {
pool.submit(() -> {
try {
int totalLength = 8192;
for (int i = 0; i < compressed.length; i++) {
byte[] compressedBytes = compressed[i];
for (byte[] compressedBytes : compressed) {
if (compressedBytes != null) {
int blocks = ((4095 + compressedBytes.length + 5) / 4096) * 4096;
totalLength += blocks;

View File

@ -4,6 +4,7 @@ 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;
@ -91,7 +92,6 @@ public class WritableMCAChunk extends FaweChunk<Void> {
nbtOut.writeNamedTagName("", NBTConstants.TYPE_COMPOUND);
nbtOut.writeNamedTag("DataVersion", 1631);
nbtOut.writeLazyCompoundTag("Level", out -> {
// out.writeNamedTag("V", (byte) 1);
out.writeNamedTag("Status", "decorated");
out.writeNamedTag("xPos", getX());
out.writeNamedTag("zPos", getZ());
@ -104,23 +104,27 @@ public class WritableMCAChunk extends FaweChunk<Void> {
out.writeNamedEmptyList("TileEntities");
} else {
out.writeNamedTag("TileEntities", new ListTag(CompoundTag.class,
new ArrayList<>(tiles.values())));
new ArrayList<>(tiles.values())));
}
out.writeNamedTag("InhabitedTime", inhabitedTime);
out.writeNamedTag("LastUpdate", lastUpdate);
if (biomes != null) {
if (hasBiomes) {
out.writeNamedTag("Biomes", biomes);
}
int len = 0;
for (int layer = 0; layer < hasSections.length; layer++) {
if (hasSections[layer]) len++;
for (boolean hasSection : hasSections) {
if (hasSection) {
len++;
}
}
out.writeNamedTagName("Sections", NBTConstants.TYPE_LIST);
nbtOut.writeByte(NBTConstants.TYPE_COMPOUND);
nbtOut.writeInt(len);
for (int layer = 0; layer < hasSections.length; layer++) {
if (!hasSections[layer]) continue;
if (!hasSections[layer]) {
continue;
}
out.writeNamedTag("Y", (byte) layer);
int blockIndexStart = layer << 12;
@ -188,7 +192,9 @@ public class WritableMCAChunk extends FaweChunk<Void> {
out.writeNamedTagName("BlockStates", NBTConstants.TYPE_LONG_ARRAY);
out.writeInt(blockBitArrayEnd);
for (int i = 0; i < blockBitArrayEnd; i++) out.writeLong(blockstates[i]);
for (int i = 0; i < blockBitArrayEnd; i++) {
out.writeLong(blockstates[i]);
}
out.writeNamedTagName("BlockLight", NBTConstants.TYPE_BYTE_ARRAY);
@ -339,12 +345,16 @@ public class WritableMCAChunk extends FaweChunk<Void> {
}
public int getSkyLight(int x, int y, int z) {
if (!hasSections[y >> 4]) return 0;
if (!hasSections[y >> 4]) {
return 0;
}
return getNibble(getIndex(x, y, z), skyLight);
}
public int getBlockLight(int x, int y, int z) {
if (!hasSections[y >> 4]) return 0;
if (!hasSections[y >> 4]) {
return 0;
}
return getNibble(getIndex(x, y, z), blockLight);
}

View File

@ -16,7 +16,7 @@ public class DeleteUnclaimedFilter extends DeleteUninhabitedFilter {
public DeleteUnclaimedFilter(World world, long fileDuration, long inhabitedTicks, long chunkInactivity) {
super(fileDuration, inhabitedTicks, chunkInactivity);
for (FaweMaskManager m : FaweAPI.getMaskManagers()) {
RegionFilter filter = m.getFilter(Fawe.imp().getWorldName(world));
RegionFilter filter = m.getFilter(world.getName());
if (filter != null) {
filters.add(filter);
}

View File

@ -46,7 +46,7 @@ public class PlotTrimFilter extends DeleteUninhabitedFilter {
super(fileDuration, inhabitedTicks, chunkInactivity);
Fawe.debug("Initializing Plot trim...");
String worldName = Fawe.imp().getWorldName(world);
String worldName = world.getName();
PlotArea area = PlotSquared.get().getPlotAreaByString(worldName);
IndependentPlotGenerator gen = area.getGenerator();
if (!(area instanceof HybridPlotWorld) || !(gen instanceof HybridGen)) {
@ -61,7 +61,7 @@ public class PlotTrimFilter extends DeleteUninhabitedFilter {
this.unoccupiedChunks = new LongHashSet();
this.reference = calculateReference();
Fawe.debug(" - calculating claims");
this.calculateClaimedArea();
}
@ -189,4 +189,4 @@ public class PlotTrimFilter extends DeleteUninhabitedFilter {
}
});
}
}
}

View File

@ -3,7 +3,6 @@ package com.boydti.fawe.jnbt.anvil.filters;
import com.boydti.fawe.jnbt.anvil.MCAChunk;
import com.boydti.fawe.jnbt.anvil.MCAFilterCounter;
import com.boydti.fawe.object.number.MutableLong;
import com.boydti.fawe.util.ArrayUtil;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.Arrays;

View File

@ -1,6 +1,5 @@
package com.boydti.fawe.jnbt.anvil.generator;
import com.boydti.fawe.object.PseudoRandom;
import com.boydti.fawe.util.MathMan;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.extent.Extent;
@ -57,7 +56,7 @@ public class CavesGen extends GenBase {
double f2 = 0.0F;
if (maxAngle <= 0) {
int checkAreaSize = this.getCheckAreaSize() * 16 - 16;
int checkAreaSize = (this.getCheckAreaSize() * 16) - 16;
maxAngle = checkAreaSize - ThreadLocalRandom.current().nextInt(checkAreaSize / 4);
}
boolean isLargeCave = false;
@ -71,7 +70,7 @@ public class CavesGen extends GenBase {
int k = ThreadLocalRandom.current().nextInt(6) == 0 ? 1 : 0;
for (; angle < maxAngle; angle++) {
double d3 = 1.5D + MathMan.sinInexact(angle * 3.141593F / maxAngle) * paramdouble1 * 1.0F;
double d3 = 1.5D + MathMan.sinInexact(angle * Math.PI / maxAngle) * paramdouble1 * 1.0F;
double d4 = d3 * paramDouble4;
double f3 = MathMan.cosInexact(paramdouble3);

View File

@ -1,6 +1,5 @@
package com.boydti.fawe.jnbt.anvil.generator;
import com.boydti.fawe.object.PseudoRandom;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.math.BlockVector2;
@ -10,12 +9,10 @@ import java.util.concurrent.ThreadLocalRandom;
public abstract class GenBase {
private final int checkAreaSize;
private final PseudoRandom random;
private final long seed;
private final long worldSeed1, worldSeed2;
public GenBase(int area) {
this.random = new PseudoRandom();
this.checkAreaSize = area;
this.seed = ThreadLocalRandom.current().nextLong();
this.worldSeed1 = ThreadLocalRandom.current().nextLong();
@ -26,10 +23,6 @@ public abstract class GenBase {
return checkAreaSize;
}
public PseudoRandom getRandom() {
return random;
}
public void generate(BlockVector2 chunkPos, Extent chunk) throws WorldEditException {
int i = this.checkAreaSize;
int chunkX = chunkPos.getBlockX();

View File

@ -1,10 +1,8 @@
package com.boydti.fawe.jnbt.anvil.generator;
import com.boydti.fawe.object.PseudoRandom;
import com.sk89q.worldedit.WorldEditException;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public abstract class Resource {
public Resource() {}

View File

@ -1,6 +1,5 @@
package com.boydti.fawe.jnbt.anvil.generator;
import com.boydti.fawe.object.PseudoRandom;
import com.boydti.fawe.object.schematic.Schematic;
import com.sk89q.worldedit.math.MutableBlockVector3;
import com.sk89q.worldedit.WorldEditException;
@ -12,6 +11,7 @@ import com.sk89q.worldedit.math.transform.Transform;
import com.sk89q.worldedit.session.ClipboardHolder;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class SchemGen extends Resource {
@ -40,9 +40,9 @@ public class SchemGen extends Resource {
return false;
}
mutable.mutY(y + 1);
ClipboardHolder holder = clipboards.get(PseudoRandom.random.random(clipboards.size()));
ClipboardHolder holder = clipboards.get(ThreadLocalRandom.current().nextInt(clipboards.size()));
if (randomRotate) {
holder.setTransform(new AffineTransform().rotateY(PseudoRandom.random.random(4) * 90));
holder.setTransform(new AffineTransform().rotateY(ThreadLocalRandom.current().nextInt(4) * 90));
}
Clipboard clipboard = holder.getClipboard();
Schematic schematic = new Schematic(clipboard);

View File

@ -1,29 +0,0 @@
//package com.boydti.fawe.logging;
//
//import org.primesoft.blockshub.api.BlockData;
//
//public class MutableBlockData extends BlockData {
// public int data;
// public int id;
//
// public MutableBlockData() {
// super(0, 0);
// this.id = 0;
// this.data = 0;
// }
//
// @Override
// public int getType() {
// return id;
// }
//
// @Override
// public int getData() {
// return data;
// }
//
// @Override
// public boolean isAir() {
// return id == 0;
// }
//}

View File

@ -1,47 +0,0 @@
//package com.boydti.fawe.logging;
//
//import org.primesoft.blockshub.api.Vector;
//
//public class MutableVector3 extends Vector {
//
// public double x, y, z;
//
// public MutableVector3() {
// super(0, 0, 0);
// this.x = 0;
// this.y = 0;
// this.z = 0;
// }
//
// @Override
// public double getX() {
// return x;
// }
//
// @Override
// public double getY() {
// return y;
// }
//
// @Override
// public double getZ() {
// return z;
// }
//
// public boolean equals(Object obj) {
// if (!(obj instanceof Vector)) {
// return false;
// } else {
// Vector v = (Vector) obj;
// return this.x == v.getX() && this.z == v.getZ() && this.y == v.getY();
// }
// }
//
// public int hashCode() {
// byte hash = 3;
// int hash1 = 59 * hash + (int) (Double.doubleToLongBits(this.x) ^ Double.doubleToLongBits(this.x) >>> 32);
// hash1 = 59 * hash1 + (int) (Double.doubleToLongBits(this.y) ^ Double.doubleToLongBits(this.y) >>> 32);
// hash1 = 59 * hash1 + (int) (Double.doubleToLongBits(this.z) ^ Double.doubleToLongBits(this.z) >>> 32);
// return hash1;
// }
//}

View File

@ -1,14 +1,13 @@
package com.boydti.fawe.object;
import com.boydti.fawe.object.visitor.FaweChunkVisitor;
import com.boydti.fawe.util.MainUtil;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import java.util.ArrayDeque;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@ -121,7 +120,7 @@ public abstract class FaweChunk<T> implements Callable<FaweChunk> {
return BaseBlock.getFromInternalId(combined, tile).toImmutableState();
}
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return BlockState.getFromInternalId(combined);
}

View File

@ -1,7 +1,6 @@
package com.boydti.fawe.object;
import com.boydti.fawe.config.BBC;
import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.TaskManager;
public abstract class FaweCommand<T> {
@ -27,26 +26,16 @@ public abstract class FaweCommand<T> {
execute(player, args);
return true;
} else if (player == null) {
TaskManager.IMP.async(new Runnable() {
@Override
public void run() {
execute(player, args);
}
});
TaskManager.IMP.async(() -> execute(player, args));
} else {
if (!player.runAction(new Runnable() {
@Override
public void run() {
execute(player, args);
}
}, true, true)) {
if (!player.runAction(() -> execute(player, args), true, true)) {
BBC.WORLDEDIT_COMMAND_LIMIT.send(player);
return true;
}
}
return true;
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return false;
}

View File

@ -1,51 +0,0 @@
package com.boydti.fawe.object;
import com.boydti.fawe.FaweAPI;
import com.sk89q.worldedit.world.World;
/**
*/
public class FaweLocation {
public final int x;
public final int y;
public final int z;
public final String world;
public FaweLocation(final String world, final int x, final int y, final int z) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final FaweLocation other = (FaweLocation) obj;
return ((this.x == other.x) && (this.y == other.y) && (this.z == other.z) && (this.world.equals(other.world)));
}
public World getWorld() {
return FaweAPI.getWorld(world);
}
@Override
public String toString() {
return world + "," + x + "," + y + "," + z;
}
@Override
public int hashCode() {
return this.x << (8 + this.z) << (4 + this.y);
}
}

View File

@ -47,8 +47,8 @@ public class FaweOutputStream extends DataOutputStream {
public void write(long[] data) throws IOException {
this.writeVarInt(data.length);
for(int j = 0; j < data.length; ++j) {
this.writeLong(data[j]);
for (long datum : data) {
this.writeLong(datum);
}
}

View File

@ -10,33 +10,54 @@ import com.boydti.fawe.object.clipboard.DiskOptimizedClipboard;
import com.boydti.fawe.object.exception.FaweException;
import com.boydti.fawe.object.task.SimpleAsyncNotifyQueue;
import com.boydti.fawe.regions.FaweMaskManager;
import com.boydti.fawe.util.*;
import com.boydti.fawe.wrappers.FakePlayer;
import com.boydti.fawe.util.EditSessionBuilder;
import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.SetQueue;
import com.boydti.fawe.util.TaskManager;
import com.boydti.fawe.util.WEManager;
import com.boydti.fawe.wrappers.LocationMaskedPlayerWrapper;
import com.boydti.fawe.wrappers.PlayerWrapper;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.EmptyClipboardException;
import com.sk89q.worldedit.IncompleteRegionException;
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.*;
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.PlatformManager;
import com.sk89q.worldedit.extension.platform.PlayerProxy;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.regions.*;
import com.sk89q.worldedit.regions.ConvexPolyhedralRegion;
import com.sk89q.worldedit.regions.CylinderRegion;
import com.sk89q.worldedit.regions.Polygonal2DRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionOperationException;
import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.regions.selector.ConvexPolyhedralRegionSelector;
import com.sk89q.worldedit.regions.selector.CuboidRegionSelector;
import com.sk89q.worldedit.regions.selector.CylinderRegionSelector;
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;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.util.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
@ -63,15 +84,9 @@ public abstract class FawePlayer<T> extends Metadatable {
* @return
*/
public static <V> FawePlayer<V> wrap(Object obj) {
if (obj == null || (obj instanceof String && obj.equals("*"))) {
return FakePlayer.getConsole().toFawePlayer();
}
if (obj instanceof FawePlayer) {
return (FawePlayer<V>) obj;
}
if (obj instanceof FakePlayer) {
return ((FakePlayer) obj).toFawePlayer();
}
if (obj instanceof Player) {
Player actor = LocationMaskedPlayerWrapper.unwrap((Player) obj);
if (obj instanceof PlayerProxy) {
@ -95,18 +110,8 @@ public abstract class FawePlayer<T> extends Metadatable {
if (existing != null) {
return existing;
}
FakePlayer fake = new FakePlayer(actor.getName(), actor.getUniqueId(), actor);
return fake.toFawePlayer();
}
if (obj != null && obj.getClass().getName().contains("CraftPlayer") && !Fawe.imp().getPlatform().equals("bukkit")) {
try {
Method methodGetHandle = obj.getClass().getDeclaredMethod("getHandle");
obj = methodGetHandle.invoke(obj);
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
obj.getClass().getName();
return Fawe.imp().wrap(obj);
}
@ -206,7 +211,7 @@ public abstract class FawePlayer<T> extends Metadatable {
if (region != null) {
BlockVector3 min = region.getMinimumPoint();
BlockVector3 max = region.getMaximumPoint();
long area = (long) ((max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1));
long area = (max.getX() - min.getX()) * (max.getZ() - min.getZ() + 1);
if (area > 2 << 18) {
setConfirmTask(task, context, command);
BlockVector3 base = max.subtract(min).add(BlockVector3.ONE);
@ -220,7 +225,7 @@ public abstract class FawePlayer<T> extends Metadatable {
public synchronized boolean confirm() {
Runnable confirm = deleteMeta("cmdConfirm");
if (!(confirm instanceof Runnable)) {
if (confirm == null) {
return false;
}
queueAction(() -> {
@ -281,7 +286,7 @@ public abstract class FawePlayer<T> extends Metadatable {
e = e.getCause();
}
if (e instanceof WorldEditException) {
sendMessage(BBC.getPrefix() + e.getLocalizedMessage());
sendMessage(e.getLocalizedMessage());
} else {
FaweException fe = FaweException.get(e);
if (fe != null) {
@ -341,7 +346,7 @@ public abstract class FawePlayer<T> extends Metadatable {
if (session.getClipboard() != null) {
return;
}
} catch (EmptyClipboardException e) {
} catch (EmptyClipboardException ignored) {
}
if (player != null) {
Clipboard clip = doc.toClipboard();
@ -351,7 +356,7 @@ public abstract class FawePlayer<T> extends Metadatable {
}
} catch (Exception event) {
Fawe.debug("====== INVALID CLIPBOARD ======");
MainUtil.handleError(event, false);
event.printStackTrace();
Fawe.debug("===============---=============");
Fawe.debug("This shouldn't result in any failure");
Fawe.debug("File: " + file.getName() + " (len:" + file.length() + ")");
@ -365,7 +370,7 @@ public abstract class FawePlayer<T> extends Metadatable {
* @return
*/
public World getWorld() {
return FaweAPI.getWorld(getLocation().world);
return getPlayer().getWorld();
}
public FaweQueue getFaweQueue(boolean autoQueue) {
@ -467,6 +472,13 @@ public abstract class FawePlayer<T> extends Metadatable {
*/
public abstract void sendMessage(final String message);
/**
* Print a WorldEdit error.
*
* @param msg The error message text
*/
public abstract void printError(String msg);
/**
* Have the player execute a command
*
@ -479,7 +491,9 @@ public abstract class FawePlayer<T> extends Metadatable {
*
* @return
*/
public abstract FaweLocation getLocation();
public Location getLocation() {
return getPlayer().getLocation();
}
/**
* Get the WorldEdit player object
@ -516,7 +530,8 @@ public abstract class FawePlayer<T> extends Metadatable {
* @return
*/
public LocalSession getSession() {
return (this.session != null || this.getPlayer() == null || Fawe.get() == null) ? this.session : (session = Fawe.get().getWorldEdit().getSessionManager().get(this.getPlayer()));
if (this.session != null || this.getPlayer() == null || Fawe.get() == null) return this.session;
else return session = Fawe.get().getWorldEdit().getSessionManager().get(this.getPlayer());
}
/**
@ -550,19 +565,14 @@ public abstract class FawePlayer<T> extends Metadatable {
public void setSelection(Region region) {
RegionSelector selector;
switch (region.getClass().getName()) {
case "ConvexPolyhedralRegion":
selector = new ConvexPolyhedralRegionSelector((ConvexPolyhedralRegion) region);
break;
case "CylinderRegion":
selector = new CylinderRegionSelector((CylinderRegion) region);
break;
case "Polygonal2DRegion":
selector = new com.sk89q.worldedit.regions.selector.Polygonal2DRegionSelector((Polygonal2DRegion) region);
break;
default:
selector = new CuboidRegionSelector(null, region.getMinimumPoint(), region.getMaximumPoint());
break;
if (region instanceof ConvexPolyhedralRegion) {
selector = new ConvexPolyhedralRegionSelector((ConvexPolyhedralRegion) region);
} else if (region instanceof CylinderRegion) {
selector = new CylinderRegionSelector((CylinderRegion) region);
} else if (region instanceof Polygonal2DRegion) {
selector = new Polygonal2DRegionSelector((Polygonal2DRegion) region);
} else {
selector = new CuboidRegionSelector(null, region.getMinimumPoint(), region.getMaximumPoint());
}
selector.setWorld(region.getWorld());

View File

@ -75,17 +75,16 @@ public interface FaweQueue extends HasFaweQueue, Extent {
default BlockState getLazyBlock(int x, int y, int z) {
int combinedId4Data = getCachedCombinedId4Data(x, y, z, BlockTypes.AIR.getInternalId());
try {
BlockState state = BlockState.getFromInternalId(combinedId4Data);
return state;
return BlockState.getFromInternalId(combinedId4Data);
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
return BlockTypes.AIR.getDefaultState();
}
}
@Override
default <B extends BlockStateHolder<B>> boolean setBlock(int x, int y, int z, B block) throws WorldEditException {
return setBlock(x, y, z, block.getInternalId(), block instanceof BaseBlock ? ((BaseBlock)block).getNbtData() : null);
return setBlock(x, y, z, block.getInternalId(), block instanceof BaseBlock ? block.getNbtData() : null);
}
@Override
@ -101,7 +100,7 @@ public interface FaweQueue extends HasFaweQueue, Extent {
}
return block;
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
return BlockTypes.AIR.getDefaultState().toBaseBlock();
}
}

View File

@ -1,12 +1,8 @@
package com.boydti.fawe.object;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.object.changeset.FaweChangeSet;
import com.boydti.fawe.object.exception.FaweException;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.*;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.extent.AbstractDelegateExtent;
@ -14,12 +10,10 @@ import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.history.changeset.ChangeSet;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector2;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.ArrayList;
import java.util.List;

View File

@ -33,10 +33,7 @@ public class Metadatable {
* @return
*/
public <V> V getMeta(String key) {
if (this.meta != null) {
return (V) this.meta.get(key);
}
return null;
return (V) this.meta.get(key);
}
/**
@ -48,11 +45,8 @@ public class Metadatable {
* @return
*/
public <V> V getMeta(String key, V def) {
if (this.meta != null) {
V value = (V) this.meta.get(key);
return value == null ? def : value;
}
return def;
V value = (V) this.meta.get(key);
return value == null ? def : value;
}
/**
@ -63,6 +57,6 @@ public class Metadatable {
* @param key
*/
public <V> V deleteMeta(String key) {
return this.meta == null ? null : (V) this.meta.remove(key);
return (V) this.meta.remove(key);
}
}

View File

@ -1,23 +0,0 @@
package com.boydti.fawe.object;
import java.util.concurrent.ThreadLocalRandom;
@Deprecated
/**
* @Deprecated use ThreadLocalRandom instead
*/
public class PseudoRandom {
public static PseudoRandom random = new PseudoRandom();
public PseudoRandom() {
}
public int random(final int n) {
if (n == 1) {
return 0;
}
final long r = ((ThreadLocalRandom.current().nextLong() >>> 32) * n) >> 32;
return (int) r;
}
}

View File

@ -222,7 +222,7 @@ public class BrushSettings {
}
public BrushSettings addPermissions(String... perms) {
for (String perm : perms) permissions.add(perm);
Collections.addAll(permissions, perms);
return this;
}

View File

@ -24,6 +24,7 @@ import com.sk89q.worldedit.math.transform.AffineTransform;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.session.ClipboardHolder;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.concurrent.ThreadLocalRandom;
@ -69,7 +70,7 @@ public class CopyPastaBrush implements Brush, ResettableTool {
if (super.test(vector) && vector.getBlockY() >= minY) {
BaseBlock block = editSession.getFullBlock(vector);
if (!block.getBlockType().getMaterial().isAir()) {
builder.add(vector, EditSession.nullBlock.toBaseBlock(), block);
builder.add(vector, BlockTypes.AIR.getDefaultState().toBaseBlock(), block);
return true;
}
}

View File

@ -1,28 +1,24 @@
package com.boydti.fawe.object.brush;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.object.PseudoRandom;
import com.boydti.fawe.object.clipboard.CPUOptimizedClipboard;
import com.boydti.fawe.object.clipboard.FaweClipboard;
import com.boydti.fawe.object.clipboard.OffsetFaweClipboard;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.blocks.Blocks;
import com.sk89q.worldedit.command.tool.brush.Brush;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Stream;
public class ErodeBrush implements Brush {
private PseudoRandom rand = new PseudoRandom();
private static final BlockVector3[] FACES_TO_CHECK = {BlockVector3.at(0, 0, 1), BlockVector3.at(0, 0, -1), BlockVector3.at(0, 1, 0), BlockVector3.at(0, -1, 0), BlockVector3.at(1, 0, 0), BlockVector3.at(-1, 0, 0)};
private static final BlockVector3[] FACES_TO_CHECK = Direction.valuesOf(Direction.Flag.CARDINAL).stream().map(direction -> direction.toBlockVector()).toArray(size -> new BlockVector3[size]);
@Override
public void build(EditSession editSession, BlockVector3 position, Pattern pattern, double size) throws MaxChangedBlocksException {

View File

@ -1,6 +1,5 @@
package com.boydti.fawe.object.brush;
import com.boydti.fawe.object.PseudoRandom;
import com.boydti.fawe.object.collection.LocalBlockVectorSet;
import com.boydti.fawe.object.mask.SurfaceMask;
import com.sk89q.worldedit.EditSession;
@ -12,6 +11,8 @@ import com.sk89q.worldedit.function.visitor.BreadthFirstSearch;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.MutableBlockVector3;
import java.util.concurrent.ThreadLocalRandom;
public class ShatterBrush extends ScatterBrush {
private final MutableBlockVector3 mutable = new MutableBlockVector3();
@ -61,7 +62,7 @@ public class ShatterBrush extends ScatterBrush {
frontier.forEach(new LocalBlockVectorSet.BlockVectorSetVisitor() {
@Override
public void run(int x, int y, int z, int index) {
if (PseudoRandom.random.random(2) == 0) {
if (ThreadLocalRandom.current().nextInt(2) == 0) {
finalTmp.add(x, y, z);
return;
}
@ -101,4 +102,4 @@ public class ShatterBrush extends ScatterBrush {
}
}
}
}
}

View File

@ -1,21 +1,20 @@
package com.boydti.fawe.object.brush;
import com.boydti.fawe.object.PseudoRandom;
import com.boydti.fawe.object.collection.LocalBlockVectorSet;
import com.boydti.fawe.object.mask.SurfaceMask;
import com.boydti.fawe.object.pattern.BiomePattern;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.function.RegionFunction;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.function.mask.SolidBlockMask;
import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.visitor.BreadthFirstSearch;
import com.sk89q.worldedit.function.visitor.RecursiveVisitor;
import com.sk89q.worldedit.math.BlockVector3;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
public class SplatterBrush extends ScatterBrush {
private final boolean solid;
@ -45,25 +44,17 @@ public class SplatterBrush extends ScatterBrush {
SurfaceMask surface = new SurfaceMask(editSession);
final SolidBlockMask solid = new SolidBlockMask(editSession);
RecursiveVisitor visitor = new RecursiveVisitor(new Mask() {
@Override
public boolean test(BlockVector3 vector) {
double dist = vector.distanceSq(position);
if (dist < size2 && !placed.contains(vector) && (PseudoRandom.random.random(5) < 2) && surface.test(vector)) {
placed.add(vector);
return true;
}
return false;
RecursiveVisitor visitor = new RecursiveVisitor(vector -> {
double dist = vector.distanceSq(position);
if (dist < size2 && !placed.contains(vector) && (ThreadLocalRandom.current().nextInt(5) < 2) && surface.test(vector)) {
placed.add(vector);
return true;
}
}, new RegionFunction() {
@Override
public boolean apply(BlockVector3 vector) throws WorldEditException {
return editSession.setBlock(vector, finalPattern);
}
}, recursion, editSession);
return false;
}, vector -> editSession.setBlock(vector, finalPattern), recursion, editSession);
visitor.setMaxBranch(2);
visitor.setDirections(Arrays.asList(visitor.DIAGONAL_DIRECTIONS));
visitor.setDirections(Arrays.asList(BreadthFirstSearch.DIAGONAL_DIRECTIONS));
visitor.visit(position);
Operations.completeBlindly(visitor);
}
}
}

View File

@ -1,6 +1,5 @@
package com.boydti.fawe.object.brush;
import com.boydti.fawe.object.PseudoRandom;
import com.boydti.fawe.object.brush.heightmap.HeightMap;
import com.boydti.fawe.object.mask.AdjacentAnyMask;
import com.boydti.fawe.util.MathMan;
@ -13,14 +12,17 @@ import com.sk89q.worldedit.function.mask.Masks;
import com.sk89q.worldedit.function.mask.SolidBlockMask;
import com.sk89q.worldedit.function.operation.Operations;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.function.visitor.BreadthFirstSearch;
import com.sk89q.worldedit.function.visitor.RecursiveVisitor;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.MutableVector3;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.math.transform.AffineTransform;
import com.sk89q.worldedit.util.Location;
import java.io.InputStream;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;
public class StencilBrush extends HeightBrush {
private final boolean onlyWhite;
@ -53,7 +55,7 @@ public class StencilBrush extends HeightBrush {
Player player = editSession.getPlayer().getPlayer();
// BlockVector3 pos = player.getLocation();
// BlockVector3 pos = player.getLocation();
@ -84,7 +86,7 @@ public class StencilBrush extends HeightBrush {
if (val < cutoff) {
return true;
}
if (val >= 255 || PseudoRandom.random.random(maxY) < val) {
if (val >= 255 || ThreadLocalRandom.current().nextInt(maxY) < val) {
editSession.setBlock(vector.getBlockX(), vector.getBlockY(), vector.getBlockZ(), pattern);
}
return true;
@ -92,7 +94,7 @@ public class StencilBrush extends HeightBrush {
return false;
}
}, vector -> true, Integer.MAX_VALUE, editSession);
visitor.setDirections(Arrays.asList(visitor.DIAGONAL_DIRECTIONS));
visitor.setDirections(Arrays.asList(BreadthFirstSearch.DIAGONAL_DIRECTIONS));
visitor.visit(position);
Operations.completeBlindly(visitor);
}
@ -100,4 +102,4 @@ public class StencilBrush extends HeightBrush {
private void apply(double val) {
}
}
}

View File

@ -2,7 +2,7 @@ package com.boydti.fawe.object.brush;
public enum TargetMode {
TARGET_BLOCK_RANGE,
FOWARD_POINT_PITCH,
FORWARD_POINT_PITCH,
TARGET_POINT_HEIGHT,
TARGET_FACE_RANGE,
}

View File

@ -1,7 +1,5 @@
package com.boydti.fawe.object.brush.heightmap;
import com.boydti.fawe.object.PseudoRandom;
import com.boydti.fawe.util.MainUtil;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.function.mask.Mask;
@ -12,22 +10,23 @@ import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
public interface HeightMap {
public double getHeight(int x, int z);
import java.util.concurrent.ThreadLocalRandom;
public void setSize(int size);
public interface HeightMap {
double getHeight(int x, int z);
void setSize(int size);
default void perform(EditSession session, Mask mask, BlockVector3 pos, int size, int rotationMode, double yscale, boolean smooth, boolean towards, boolean layers) throws MaxChangedBlocksException {
int[][] data = generateHeightData(session, mask, pos, size, rotationMode, yscale, smooth, towards, layers);
applyHeightMapData(data, session, mask, pos, size, rotationMode, yscale, smooth, towards, layers);
applyHeightMapData(data, session, pos, size, yscale, smooth, towards, layers);
}
default void applyHeightMapData(int[][] data, EditSession session, Mask mask, BlockVector3 pos, int size, int rotationMode, double yscale, boolean smooth, boolean towards, boolean layers) throws MaxChangedBlocksException {
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;
int iterations = 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);
@ -37,17 +36,13 @@ public interface HeightMap {
HeightMapFilter filter = (HeightMapFilter) HeightMapFilter.class.getConstructors()[0].newInstance(GaussianKernel.class.getConstructors()[0].newInstance(5, 1));
data[1] = filter.filter(data[1], diameter, diameter);
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
try {
if (layers) {
heightMap.applyLayers(data[1]);
} else {
heightMap.apply(data[1]);
}
} catch (MaxChangedBlocksException e) {
throw e;
if (layers) {
heightMap.applyLayers(data[1]);
} else {
heightMap.apply(data[1]);
}
}
@ -58,22 +53,18 @@ public interface HeightMap {
int centerX = pos.getBlockX();
int centerZ = pos.getBlockZ();
int centerY = pos.getBlockY();
int endY = pos.getBlockY() + size;
int startY = pos.getBlockY() - size;
int[] oldData = new int[diameter * diameter];
int[] newData = new int[oldData.length];
if (layers) { // Pixel accuracy
centerY <<= 3;
maxY <<= 3;
}
// Vector mutablePos = new Vector(0, 0, 0);
if (towards) {
double sizePowInv = 1d / Math.pow(size, yscale);
int targetY = pos.getBlockY();
int tmpY = targetY;
for (int x = -size; x <= size; x++) {
int xx = centerX + x;
// mutablePos.mutX(xx);
for (int z = -size; z <= size; z++) {
int index = (z + size) * diameter + (x + size);
int zz = centerZ + z;
@ -108,7 +99,7 @@ public interface HeightMap {
int diff = targetY - height;
double raiseScaled = diff * (raisePow * sizePowInv);
double raiseScaledAbs = Math.abs(raiseScaled);
int random = PseudoRandom.random.random(256) < (int) ((Math.ceil(raiseScaledAbs) - Math.floor(raiseScaledAbs)) * 256) ? (diff > 0 ? 1 : -1) : 0;
int random = ThreadLocalRandom.current().nextInt(256) < (int) ((Math.ceil(raiseScaledAbs) - Math.floor(raiseScaledAbs)) * 256) ? (diff > 0 ? 1 : -1) : 0;
int raiseScaledInt = (int) raiseScaled + random;
newData[index] = height + raiseScaledInt;
}
@ -117,7 +108,6 @@ public interface HeightMap {
int height = pos.getBlockY();
for (int x = -size; x <= size; x++) {
int xx = centerX + x;
// mutablePos.mutX(xx);
for (int z = -size; z <= size; z++) {
int index = (z + size) * diameter + (x + size);
int zz = centerZ + z;
@ -148,7 +138,7 @@ public interface HeightMap {
continue;
}
raise = (yscale * raise);
int random = PseudoRandom.random.random(256) < (int) ((raise - (int) raise) * (256)) ? 1 : 0;
int random = ThreadLocalRandom.current().nextInt(256) < (int) ((raise - (int) raise) * (256)) ? 1 : 0;
int newHeight = height + (int) raise + random;
newData[index] = newHeight;
}

View File

@ -10,7 +10,7 @@ import java.util.List;
public class ScrollClipboard extends ScrollAction {
private final List<ClipboardHolder> clipboards;
private final LocalSession session;
int index = 0;
private int index = 0;
public ScrollClipboard(BrushTool tool, LocalSession session, List<ClipboardHolder> clipboards) {
super(tool);

View File

@ -45,7 +45,7 @@ public class SweepBrush implements Brush, ResettableTool {
return;
}
boolean newPos = this.position == null || !position.equals(this.position);
boolean newPos = !position.equals(this.position);
this.position = position;
FawePlayer player = editSession.getPlayer();
if (newPos) {
@ -98,7 +98,6 @@ public class SweepBrush implements Brush, ResettableTool {
MutableVector3 last = new MutableVector3(0, 0, 0);
for (double pos = 0D; pos <= 1D; pos += step) {
Vector3 gradient = interpol.get1stDerivative(pos);
if (last == null) last = new MutableVector3(interpol.get1stDerivative(pos));
double dist = MathMan.sqrtApprox(last.distanceSq(gradient));
last.mutX(gradient.getX());
last.mutY(gradient.getY());

View File

@ -20,7 +20,6 @@ public class VisualQueue extends SingleThreadIntervalQueue<FawePlayer> {
LocalSession session = fp.getSession();
Player player = fp.getPlayer();
Tool tool = session.getTool(player);
Brush brush;
if (tool instanceof BrushTool) {
BrushTool brushTool = (BrushTool) tool;
if (brushTool.getVisualMode() != VisualMode.NONE) {
@ -32,4 +31,4 @@ public class VisualQueue extends SingleThreadIntervalQueue<FawePlayer> {
}
}
}
}
}

View File

@ -13,13 +13,12 @@ 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 it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.io.DataOutput;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@ -43,10 +42,10 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
/*
* Block data
*
*
* [header]
* {int origin x, int origin z}
*
*
* [contents]...
* { short rel x, short rel z, unsigned byte y, short combinedFrom, short combinedTo }
*/
@ -66,7 +65,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
public DiskStorageHistory(World world, UUID uuid) {
super(world);
init(uuid, Fawe.imp().getWorldName(world));
init(uuid, world.getName());
}
public DiskStorageHistory(String world, UUID uuid) {
@ -116,12 +115,12 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
private void init(UUID uuid, int i) {
this.uuid = uuid;
this.index = i;
File folder = MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.HISTORY + File.separator + Fawe.imp().getWorldName(getWorld()) + File.separator + uuid);
File folder = MainUtil.getFile(Fawe.imp().getDirectory(), Settings.IMP.PATHS.HISTORY + File.separator + getWorld().getName() + File.separator + uuid);
initFiles(folder);
}
public void delete() {
Fawe.debug("Deleting history: " + Fawe.imp().getWorldName(getWorld()) + "/" + uuid + "/" + index);
// Fawe.debug("Deleting history: " + getWorld().getName() + "/" + uuid + "/" + index);
deleteFiles();
if (Settings.IMP.HISTORY.USE_DATABASE) {
RollbackDatabase db = DBHandler.IMP.getDatabase(getWorld());
@ -181,7 +180,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
if (osENTCF != null) osENTCF.flush();
if (osENTCT != null) osENTCT.flush();
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return flushed;
}
@ -218,7 +217,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
osENTCT = null;
}
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return flushed;
}
@ -418,7 +417,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
}
return summary;
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
return null;
@ -439,7 +438,7 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
fis.close();
gis.close();
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
return new IntegerPair(ox, oz);
@ -507,8 +506,8 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
public int getSize() {
int count = 0;
for (int i = 0; i < blocks.length; i++) {
count += blocks[i];
for (int block : blocks) {
count += block;
}
return count;
}
@ -523,6 +522,6 @@ public class DiskStorageHistory extends FaweStreamChangeSet {
@Override
public void setRecordChanges(boolean recordChanges) {
// TODO Auto-generated method stub
}
}

View File

@ -2,7 +2,6 @@ package com.boydti.fawe.object.changeset;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweAPI;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.config.Settings;
import com.boydti.fawe.logging.rollback.RollbackOptimizedHistory;
import com.boydti.fawe.object.FaweChunk;
@ -14,9 +13,6 @@ import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.TaskManager;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockID;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.history.change.BlockChange;
import com.sk89q.worldedit.history.change.Change;
@ -27,7 +23,8 @@ import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockID;
import java.util.Iterator;
import java.util.Map;
@ -58,13 +55,13 @@ public abstract class FaweChangeSet implements ChangeSet {
public FaweChangeSet(String world) {
this.worldName = world;
this.mainThread = (Fawe.get() != null) ? Fawe.isMainThread() : true;
this.mainThread = (Fawe.get() == null) || Fawe.isMainThread();
this.layers = FaweChunk.HEIGHT >> 4;
}
public FaweChangeSet(World world) {
this.world = world;
this.worldName = Fawe.imp().getWorldName(world);
this.worldName = world.getName();
this.mainThread = Fawe.isMainThread();
this.layers = (this.world.getMaxY() + 1) >> 4;
}
@ -85,15 +82,12 @@ public abstract class FaweChangeSet implements ChangeSet {
public boolean closeAsync() {
waitingAsync.incrementAndGet();
TaskManager.IMP.async(new Runnable() {
@Override
public void run() {
waitingAsync.decrementAndGet();
synchronized (waitingAsync) {
waitingAsync.notifyAll();
}
close();
TaskManager.IMP.async(() -> {
waitingAsync.decrementAndGet();
synchronized (waitingAsync) {
waitingAsync.notifyAll();
}
close();
});
return true;
}
@ -113,7 +107,7 @@ public abstract class FaweChangeSet implements ChangeSet {
}
}
} catch (InterruptedException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return true;
}
@ -153,8 +147,6 @@ public abstract class FaweChangeSet implements ChangeSet {
public void delete() {
}
;
public EditSession toEditSession(FawePlayer player) {
return toEditSession(player, null);
}
@ -202,7 +194,7 @@ public abstract class FaweChangeSet implements ChangeSet {
BaseBlock to = change.getCurrent();
add(loc, from, to);
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -230,7 +222,7 @@ public abstract class FaweChangeSet implements ChangeSet {
add(x, y, z, combinedFrom, combinedTo);
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -249,7 +241,7 @@ public abstract class FaweChangeSet implements ChangeSet {
add(x, y, z, combinedFrom, combinedTo);
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -258,115 +250,109 @@ public abstract class FaweChangeSet implements ChangeSet {
@Override
public void run(final FaweChunk previous, final FaweChunk next) {
FaweChangeSet.this.waitingCombined.incrementAndGet();
Runnable run = new Runnable() {
@Override
public void run() {
try {
int cx = previous.getX();
int cz = previous.getZ();
int bx = cx << 4;
int bz = cz << 4;
synchronized (FaweChangeSet.this) {
BiomeType[] previousBiomes = previous.getBiomeArray();
if (previousBiomes != null) {
BiomeType[] nextBiomes = next.getBiomeArray();
int index = 0;
for (int z = 0; z < 16; z++) {
int zz = bz + z;
for (int x = 0; x < 16; x++) {
BiomeType idFrom = previousBiomes[index];
BiomeType idTo = nextBiomes[index];
if (idFrom != idTo && idTo != null) {
addBiomeChange(bx + x, zz, idFrom, idTo);
}
index++;
Runnable run = () -> {
try {
int cx = previous.getX();
int cz = previous.getZ();
int bx = cx << 4;
int bz = cz << 4;
synchronized (FaweChangeSet.this) {
BiomeType[] previousBiomes = previous.getBiomeArray();
if (previousBiomes != null) {
BiomeType[] nextBiomes = next.getBiomeArray();
int index = 0;
for (int z = 0; z < 16; z++) {
int zz = bz + z;
for (int x = 0; x < 16; x++) {
BiomeType idFrom = previousBiomes[index];
BiomeType idTo = nextBiomes[index];
if (idFrom != idTo && idTo != null) {
addBiomeChange(bx + x, zz, idFrom, idTo);
}
index++;
}
}
// Block changes
for (int layer = 0; layer < layers; layer++) {
int[] currentLayer = next.getIdArray(layer);
int[] previousLayer = previous.getIdArray(layer);
if (currentLayer == null) {
continue;
}
int startY = layer << 4;
int index = 0;
for (int y = 0; y < 16; y++) {
int yy = y + startY;
for (int z = 0; z < 16; z++) {
int zz = z + bz;
for (int x = 0; x < 16; x++, index++) {
int xx = x + bx;
int combinedIdCurrent = currentLayer[index];
switch (combinedIdCurrent) {
case 0:
continue;
default:
int combinedIdPrevious;
if (previousLayer != null) {
combinedIdPrevious = previousLayer[index];
if (combinedIdPrevious == 0) {
combinedIdPrevious = BlockID.AIR;
}
} else {
combinedIdPrevious = BlockID.AIR;
}
if (combinedIdCurrent != combinedIdPrevious) {
add(xx, yy, zz, combinedIdPrevious, combinedIdCurrent);
}
}
// Block changes
for (int layer = 0; layer < layers; layer++) {
int[] currentLayer = next.getIdArray(layer);
int[] previousLayer = previous.getIdArray(layer);
if (currentLayer == null) {
continue;
}
int startY = layer << 4;
int index = 0;
for (int y = 0; y < 16; y++) {
int yy = y + startY;
for (int z = 0; z < 16; z++) {
int zz = z + bz;
for (int x = 0; x < 16; x++, index++) {
int xx = x + bx;
int combinedIdCurrent = currentLayer[index];
if (combinedIdCurrent != 0) {
int combinedIdPrevious;
if (previousLayer != null) {
combinedIdPrevious = previousLayer[index];
if (combinedIdPrevious == 0) {
combinedIdPrevious = BlockID.AIR;
}
} else {
combinedIdPrevious = BlockID.AIR;
}
if (combinedIdCurrent != combinedIdPrevious) {
add(xx, yy, zz, combinedIdPrevious, combinedIdCurrent);
}
}
}
}
}
// Tile changes
{
// Tiles created
Map<Short, CompoundTag> tiles = next.getTiles();
if (!tiles.isEmpty()) {
for (Map.Entry<Short, CompoundTag> entry : tiles.entrySet()) {
addTileCreate(entry.getValue());
}
}
// Tiles removed
tiles = previous.getTiles();
if (!tiles.isEmpty()) {
for (Map.Entry<Short, CompoundTag> entry : tiles.entrySet()) {
addTileRemove(entry.getValue());
}
}
// Tile changes
{
// Tiles created
Map<Short, CompoundTag> tiles = next.getTiles();
if (!tiles.isEmpty()) {
for (Map.Entry<Short, CompoundTag> entry : tiles.entrySet()) {
addTileCreate(entry.getValue());
}
}
// Entity changes
{
// Entities created
Set<CompoundTag> entities = next.getEntities();
if (!entities.isEmpty()) {
for (CompoundTag entityTag : entities) {
addEntityCreate(entityTag);
}
}
// Entities removed
entities = previous.getEntities();
if (!entities.isEmpty()) {
for (CompoundTag entityTag : entities) {
addEntityRemove(entityTag);
}
// Tiles removed
tiles = previous.getTiles();
if (!tiles.isEmpty()) {
for (Map.Entry<Short, CompoundTag> entry : tiles.entrySet()) {
addTileRemove(entry.getValue());
}
}
}
} catch (Throwable e) {
MainUtil.handleError(e);
} finally {
if (FaweChangeSet.this.waitingCombined.decrementAndGet() <= 0) {
synchronized (FaweChangeSet.this.waitingAsync) {
FaweChangeSet.this.waitingAsync.notifyAll();
// Entity changes
{
// Entities created
Set<CompoundTag> entities = next.getEntities();
if (!entities.isEmpty()) {
for (CompoundTag entityTag : entities) {
addEntityCreate(entityTag);
}
}
synchronized (FaweChangeSet.this.waitingCombined) {
FaweChangeSet.this.waitingCombined.notifyAll();
// Entities removed
entities = previous.getEntities();
if (!entities.isEmpty()) {
for (CompoundTag entityTag : entities) {
addEntityRemove(entityTag);
}
}
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
if (FaweChangeSet.this.waitingCombined.decrementAndGet() <= 0) {
synchronized (FaweChangeSet.this.waitingAsync) {
FaweChangeSet.this.waitingAsync.notifyAll();
}
synchronized (FaweChangeSet.this.waitingCombined) {
FaweChangeSet.this.waitingCombined.notifyAll();
}
}
}
};
if (mainThread) {
@ -377,4 +363,4 @@ public abstract class FaweChangeSet implements ChangeSet {
}
});
}
}
}

View File

@ -229,8 +229,8 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
// skip mode
int mode = is.read();
// origin
int x = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + (is.read() << 0));
int z = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + (is.read() << 0));
int x = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + is.read());
int z = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + is.read());
setOrigin(x, z);
setupStreamDelegates(mode);
}
@ -320,7 +320,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
posDel.write(stream, x - originX, y, z - originZ);
idDel.writeChange(stream, combinedFrom, combinedTo);
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -328,7 +328,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
public void addBiomeChange(int x, int z, BiomeType from, BiomeType to) {
blockSize++;
try {
OutputStream os = getBiomeOS();
FaweOutputStream os = getBiomeOS();
os.write((byte) (x >> 24));
os.write((byte) (x >> 16));
os.write((byte) (x >> 8));
@ -337,10 +337,10 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
os.write((byte) (z >> 16));
os.write((byte) (z >> 8));
os.write((byte) (z));
((FaweOutputStream) os).writeVarInt(from.getInternalId());
((FaweOutputStream) os).writeVarInt(to.getInternalId());
os.writeVarInt(from.getInternalId());
os.writeVarInt(to.getInternalId());
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -353,7 +353,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
NBTOutputStream nbtos = getTileCreateOS();
nbtos.writeTag(tag);
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -366,7 +366,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
NBTOutputStream nbtos = getTileRemoveOS();
nbtos.writeTag(tag);
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -379,7 +379,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
NBTOutputStream nbtos = getEntityRemoveOS();
nbtos.writeTag(tag);
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -392,7 +392,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
NBTOutputStream nbtos = getEntityCreateOS();
nbtos.writeTag(tag);
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -412,15 +412,15 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
change.z = posDel.readZ(is) + originZ;
idDel.readCombined(is, change, dir);
return change;
} catch (EOFException ignoreOEF) {
} catch (EOFException ignored) {
} catch (Exception e) {
e.printStackTrace();
MainUtil.handleError(e);
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return null;
}
@ -448,7 +448,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
}
public Iterator<MutableBiomeChange> getBiomeIterator(final boolean dir) throws IOException {
final InputStream is = getBiomeIS();
final FaweInputStream is = getBiomeIS();
if (is == null) {
return new ArrayList<MutableBiomeChange>().iterator();
}
@ -460,22 +460,22 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
try {
int int1 = is.read();
if (int1 != -1) {
int x = ((int1 << 24) + (is.read() << 16) + (is.read() << 8) + (is.read() << 0));
int z = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + (is.read() << 0));
int from = ((FaweInputStream) is).readVarInt();
int to = ((FaweInputStream) is).readVarInt();
int x = ((int1 << 24) + (is.read() << 16) + (is.read() << 8) + is.read());
int z = ((is.read() << 24) + (is.read() << 16) + (is.read() << 8) + is.read());
int from = is.readVarInt();
int to = is.readVarInt();
change.setBiome(x, z, from, to);
return change;
}
} catch (EOFException ignoreOEF) {
} catch (EOFException ignored) {
} catch (Exception e) {
e.printStackTrace();
MainUtil.handleError(e);
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return null;
}
@ -516,9 +516,6 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
public Iterator<MutableFullBlockChange> getFullBlockIterator(BlockBag blockBag, int inventory, final boolean dir) throws IOException {
final FaweInputStream is = new FaweInputStream(getBlockIS());
if (is == null) {
return new ArrayList<MutableFullBlockChange>().iterator();
}
final MutableFullBlockChange change = new MutableFullBlockChange(blockBag, inventory, dir);
return new Iterator<MutableFullBlockChange>() {
private MutableFullBlockChange last = read();
@ -530,15 +527,15 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
change.z = posDel.readZ(is) + originZ;
idDel.readCombined(is, change, dir);
return change;
} catch (EOFException ignoreOEF) {
} catch (EOFException ignored) {
} catch (Exception e) {
e.printStackTrace();
MainUtil.handleError(e);
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return null;
}
@ -565,7 +562,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
};
}
public Iterator<MutableEntityChange> getEntityIterator(final NBTInputStream is, final boolean create, final boolean dir) {
public Iterator<MutableEntityChange> getEntityIterator(final NBTInputStream is, final boolean create) {
if (is == null) {
return new ArrayList<MutableEntityChange>().iterator();
}
@ -576,15 +573,14 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
public MutableEntityChange read() {
try {
CompoundTag tag = (CompoundTag) is.readTag();
change.tag = tag;
change.tag = (CompoundTag) is.readTag();
return change;
} catch (Exception ignoreOEF) {
} catch (Exception ignored) {
}
try {
is.close();
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return null;
}
@ -610,12 +606,12 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
}
};
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
return null;
}
}
public Iterator<MutableTileChange> getTileIterator(final NBTInputStream is, final boolean create, final boolean dir) {
public Iterator<MutableTileChange> getTileIterator(final NBTInputStream is, final boolean create) {
if (is == null) {
return new ArrayList<MutableTileChange>().iterator();
}
@ -626,15 +622,14 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
public MutableTileChange read() {
try {
CompoundTag tag = (CompoundTag) is.readTag();
change.tag = tag;
change.tag = (CompoundTag) is.readTag();
return change;
} catch (Exception ignoreOEF) {
} catch (Exception ignored) {
}
try {
is.close();
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return null;
}
@ -660,7 +655,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
}
};
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
return null;
}
}
@ -668,11 +663,11 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
public Iterator<Change> getIterator(final boolean dir) {
close();
try {
final Iterator<MutableTileChange> tileCreate = getTileIterator(getTileCreateIS(), true, dir);
final Iterator<MutableTileChange> tileRemove = getTileIterator(getTileRemoveIS(), false, dir);
final Iterator<MutableTileChange> tileCreate = getTileIterator(getTileCreateIS(), true);
final Iterator<MutableTileChange> tileRemove = getTileIterator(getTileRemoveIS(), false);
final Iterator<MutableEntityChange> entityCreate = getEntityIterator(getEntityCreateIS(), true, dir);
final Iterator<MutableEntityChange> entityRemove = getEntityIterator(getEntityRemoveIS(), false, dir);
final Iterator<MutableEntityChange> entityCreate = getEntityIterator(getEntityCreateIS(), true);
final Iterator<MutableEntityChange> entityRemove = getEntityIterator(getEntityRemoveIS(), false);
final Iterator<MutableBlockChange> blockChange = getBlockIterator(dir);
@ -714,7 +709,7 @@ public abstract class FaweStreamChangeSet extends FaweChangeSet {
}
};
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return new ArrayList<Change>().iterator();
}

View File

@ -9,9 +9,9 @@ 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;
import java.io.OutputStream;
/**
* ChangeSet optimized for low memory usage
@ -66,7 +66,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
if (tileRStream != null) tileRStreamZip.flush();
return true;
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
return false;
@ -115,7 +115,7 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
}
return true;
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
return false;
@ -248,6 +248,6 @@ public class MemoryOptimizedHistory extends FaweStreamChangeSet {
@Override
public void setRecordChanges(boolean recordChanges) {
// TODO Auto-generated method stub
}
}

View File

@ -1,7 +1,6 @@
package com.boydti.fawe.object.clipboard;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.FaweCache;
import com.boydti.fawe.config.Settings;
import com.boydti.fawe.jnbt.NBTStreamer;
import com.boydti.fawe.object.IntegerTrio;
@ -10,7 +9,6 @@ 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;
@ -80,9 +78,9 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
this.braf = new RandomAccessFile(file, "rw");
braf.setLength(file.length());
init();
width = (int) mbb.getChar(2);
height = (int) mbb.getChar(4);
length = (int) mbb.getChar(6);
width = mbb.getChar(2);
height = mbb.getChar(4);
length = mbb.getChar(6);
area = width * length;
this.volume = length * width * height;
@ -182,7 +180,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
clipboard.setOrigin(BlockVector3.at(ox, oy, oz));
return clipboard;
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return null;
}
@ -206,10 +204,10 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
file.createNewFile();
}
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
}
this.braf = new RandomAccessFile(file, "rw");
long volume = (long) width * (long) height * (long) length * 4l + (long) HEADER_SIZE;
long volume = (long) width * (long) height * (long) length * 4L + (long) HEADER_SIZE;
braf.setLength(0);
braf.setLength(volume);
if (width * height * length != 0) {
@ -231,7 +229,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
mbb.putShort(10, (short) offset.getBlockY());
mbb.putShort(12, (short) offset.getBlockZ());
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -243,7 +241,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
length = dimensions.getBlockZ();
area = width * length;
volume = width * length * height;
long size = width * height * length * 4l + HEADER_SIZE + (hasBiomes() ? area : 0);
long size = width * height * length * 4L + HEADER_SIZE + (hasBiomes() ? area : 0);
if (braf.length() < size) {
close();
this.braf = new RandomAccessFile(file, "rw");
@ -254,7 +252,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
mbb.putChar(4, (char) height);
mbb.putChar(6, (char) length);
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -291,7 +289,6 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
System.gc();
}
}
cb = null;
}
@Override
@ -313,7 +310,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
braf = null;
}
} catch (IOException e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -352,7 +349,7 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
}
}
} catch (Throwable e) {
MainUtil.handleError(e);
e.printStackTrace();
}
}
@ -443,9 +440,9 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
} catch (IndexOutOfBoundsException ignore) {
} catch (Exception e) {
e.printStackTrace();
MainUtil.handleError(e);
e.printStackTrace();
}
return EditSession.nullBlock.toBaseBlock();
return BlockTypes.AIR.getDefaultState().toBaseBlock();
}
@Override
@ -482,9 +479,9 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
return base;
} catch (IndexOutOfBoundsException ignore) {
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return EditSession.nullBlock.toBaseBlock();
return BlockTypes.AIR.getDefaultState().toBaseBlock();
}
@Override
@ -503,13 +500,13 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
int index = (HEADER_SIZE) + ((getIndex(x, y, z) << 2));
int combined = block.getInternalId();
mbb.putInt(index, combined);
boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData();
boolean hasNbt = block instanceof BaseBlock && block.hasNbtData();
if (hasNbt) {
setTile(x, y, z, ((BaseBlock)block).getNbtData());
setTile(x, y, z, block.getNbtData());
}
return true;
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return false;
}
@ -520,17 +517,17 @@ public class DiskOptimizedClipboard extends FaweClipboard implements Closeable {
int combined = block.getInternalId();
int index = (HEADER_SIZE) + (i << 2);
mbb.putInt(index, combined);
boolean hasNbt = block instanceof BaseBlock && ((BaseBlock)block).hasNbtData();
boolean hasNbt = block instanceof BaseBlock && block.hasNbtData();
if (hasNbt) {
int y = i / area;
int newI = (i - (y * area));
int z = newI / width;
int x = newI - z * width;
setTile(x, y, z, ((BaseBlock)block).getNbtData());
setTile(x, y, z, block.getNbtData());
}
return true;
} catch (Exception e) {
MainUtil.handleError(e);
e.printStackTrace();
}
return false;
}

View File

@ -1,9 +1,6 @@
package com.boydti.fawe.object.clipboard;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
@ -14,12 +11,14 @@ import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockTypes;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
public class EmptyClipboard implements Clipboard {
@ -75,12 +74,12 @@ public class EmptyClipboard implements Clipboard {
@Override
public BaseBlock getFullBlock(BlockVector3 position) {
return EditSession.nullBlock.toBaseBlock();
return BlockTypes.AIR.getDefaultState().toBaseBlock();
}
@Override
public BlockState getLazyBlock(BlockVector3 position) {
return EditSession.nullBlock;
return BlockTypes.AIR.getDefaultState();
}
@Override

View File

@ -1,12 +1,11 @@
package com.boydti.fawe.object.clipboard;
import com.boydti.fawe.object.schematic.StructureFormat;
import com.google.common.io.ByteSource;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;
import com.sk89q.worldedit.extent.clipboard.Clipboard;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat;
import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader;
import com.sk89q.worldedit.extent.clipboard.io.SchematicReader;
import java.io.InputStream;
import java.net.URI;
import java.util.UUID;

View File

@ -77,7 +77,7 @@ public class ResizableClipboardBuilder extends MemoryOptimizedHistory {
int x = tileChange.tag.getInt("x");
int y = tileChange.tag.getInt("y");
int z = tileChange.tag.getInt("z");
clipboard.setTile(x, y, z, tileChange.tag);
clipboard.setTile(x,y,z, tileChange.tag);
}
}
} catch (WorldEditException e) {

View File

@ -17,6 +17,7 @@ import com.sk89q.worldedit.math.MutableBlockVector2;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.ArrayList;
import java.util.List;
@ -149,7 +150,7 @@ public class WorldCopyClipboard extends ReadOnlyClipboard {
}
task.run(xx, yy, zz, block);
} else if (air) {
task.run(xx, yy, zz, EditSession.nullBlock);
task.run(xx, yy, zz, BlockTypes.AIR.getDefaultState());
}
}
}

View File

@ -3,8 +3,8 @@ package com.boydti.fawe.object.clipboard;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.world.block.BlockTypes;
public class WorldCutClipboard extends WorldCopyClipboard {
public WorldCutClipboard(EditSession editSession, Region region, boolean copyEntities, boolean copyBiome) {
@ -21,13 +21,13 @@ public class WorldCutClipboard extends WorldCopyClipboard {
int yy = my + y;
int zz = mz + z;
BaseBlock block = extent.getFullBlock(BlockVector3.at(xx, yy, zz));
extent.setBlock(xx, yy, zz, EditSession.nullBlock);
extent.setBlock(xx, yy, zz, BlockTypes.AIR.getDefaultState());
return block;
}
public BaseBlock getBlockAbs(int x, int y, int z) {
BaseBlock block = extent.getFullBlock(BlockVector3.at(x, y, z));
extent.setBlock(x, y, z, EditSession.nullBlock);
extent.setBlock(x, y, z, BlockTypes.AIR.getDefaultState());
return block;
}
@ -40,4 +40,4 @@ public class WorldCutClipboard extends WorldCopyClipboard {
extent.commit();
}
}
}
}

View File

@ -7,13 +7,9 @@ import com.sk89q.worldedit.math.MutableBlockVector3;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* The BlockVectorSet is a Memory optimized Set for storing BlockVectors
@ -23,6 +19,7 @@ import java.util.Set;
*/
public class BlockVectorSet extends AbstractCollection<BlockVector3> implements Set<BlockVector3> {
private Int2ObjectMap<LocalBlockVectorSet> localSets = new Int2ObjectOpenHashMap<>();
private MutableBlockVector3 mutable = new MutableBlockVector3();
@Override
public int size() {
@ -35,23 +32,19 @@ public class BlockVectorSet extends AbstractCollection<BlockVector3> implements
public BlockVector3 get(int index) {
int count = 0;
ObjectIterator<Int2ObjectMap.Entry<LocalBlockVectorSet>> iter = localSets.int2ObjectEntrySet().iterator();
while (iter.hasNext()) {
Int2ObjectMap.Entry<LocalBlockVectorSet> entry = iter.next();
for (Int2ObjectMap.Entry<LocalBlockVectorSet> entry : localSets.int2ObjectEntrySet()) {
LocalBlockVectorSet set = entry.getValue();
int size = set.size();
int newSize = count + size;
if (newSize > index) {
int localIndex = index - count;
MutableBlockVector3 pos = new MutableBlockVector3(set.getIndex(localIndex));
if (pos != null) {
int pair = entry.getIntKey();
int cx = MathMan.unpairX(pair);
int cz = MathMan.unpairY(pair);
pos.mutX((cx << 11) + pos.getBlockX());
pos.mutZ((cz << 11) + pos.getBlockZ());
return pos;
}
BlockVector3 pos = mutable.setComponents(set.getIndex(localIndex));
int pair = entry.getIntKey();
int cx = MathMan.unpairX(pair);
int cz = MathMan.unpairY(pair);
pos = pos.mutX((cx << 11) + pos.getBlockX());
pos = pos.mutZ((cz << 11) + pos.getBlockZ());
return pos;
}
count += newSize;
}
@ -83,11 +76,12 @@ public class BlockVectorSet extends AbstractCollection<BlockVector3> implements
return false;
}
@NotNull
@Override
public Iterator<BlockVector3> iterator() {
final ObjectIterator<Int2ObjectMap.Entry<LocalBlockVectorSet>> entries = localSets.int2ObjectEntrySet().iterator();
if (!entries.hasNext()) {
return new ArrayList<BlockVector3>().iterator();
return Collections.emptyIterator();
}
return new Iterator<BlockVector3>() {
Int2ObjectMap.Entry<LocalBlockVectorSet> entry = entries.next();
@ -182,7 +176,7 @@ public class BlockVectorSet extends AbstractCollection<BlockVector3> implements
}
@Override
public boolean retainAll(Collection<?> c) {
public boolean retainAll(@NotNull Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator it = iterator();
@ -209,4 +203,4 @@ public class BlockVectorSet extends AbstractCollection<BlockVector3> implements
public void clear() {
localSets.clear();
}
}
}

View File

@ -3,6 +3,7 @@ package com.boydti.fawe.object.collection;
import com.boydti.fawe.util.MathMan;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.MutableBlockVector3;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.Iterator;
@ -115,14 +116,13 @@ public class LocalBlockVectorSet implements Set<BlockVector3> {
int b3 = ((byte) (index >> 15)) & 0xFF;
int b4 = ((byte) (index >> 23)) & 0xFF;
int x = offsetX + (((b3 + ((MathMan.unpair8x(b2)) << 8)) << 21) >> 21);
int y = b1;
int z = offsetZ + (((b4 + ((MathMan.unpair8y(b2)) << 8)) << 21) >> 21);
return MutableBlockVector3.get(x, y, z);
return MutableBlockVector3.get(x, b1, z);
}
return null;
}
@Override
@NotNull @Override
public Iterator<BlockVector3> iterator() {
return new Iterator<BlockVector3>() {
int index = set.nextSetBit(0);
@ -158,12 +158,12 @@ public class LocalBlockVectorSet implements Set<BlockVector3> {
};
}
@Override
@NotNull @Override
public Object[] toArray() {
return toArray(null);
}
@Override
@NotNull @Override
public <T> T[] toArray(T[] array) {
int size = size();
if (array == null || array.length < size) {
@ -177,9 +177,8 @@ public class LocalBlockVectorSet implements Set<BlockVector3> {
int b3 = ((byte) (index >> 15)) & 0xFF;
int b4 = ((byte) (index >> 23)) & 0xFF;
int x = offsetX + (((b3 + ((MathMan.unpair8x(b2)) << 8)) << 21) >> 21);
int y = b1;
int z = offsetZ + (((b4 + ((MathMan.unpair8y(b2)) << 8)) << 21) >> 21);
array[i] = (T) BlockVector3.at(x, y, z);
array[i] = (T) BlockVector3.at(x, b1, z);
index++;
}
return array;
@ -276,7 +275,7 @@ public class LocalBlockVectorSet implements Set<BlockVector3> {
}
@Override
public boolean retainAll(Collection<?> c) {
public boolean retainAll(@NotNull Collection<?> c) {
boolean result = false;
int size = size();
int index = -1;
@ -318,9 +317,8 @@ public class LocalBlockVectorSet implements Set<BlockVector3> {
int b3 = ((byte) (index >> 15)) & 0xFF;
int b4 = ((byte) (index >> 23)) & 0xFF;
int x = offsetX + (((b3 + ((MathMan.unpair8x(b2)) << 8)) << 21) >> 21);
int y = b1;
int z = offsetZ + (((b4 + ((MathMan.unpair8y(b2)) << 8)) << 21) >> 21);
visitor.run(x, y, z, index);
visitor.run(x, b1, z, index);
}
}

View File

@ -94,7 +94,7 @@ public final class SparseBitSet implements Cloneable, Serializable {
bits (setting, flipping, clearing, etc.) do not attempt to normalize the
set, in the interests of speed. However, when a set is scanned as the
resultant set of some operation, then, in most cases, the set will be
normalized--the exception being level2 areas that are not completly scanned
normalized--the exception being level2 areas that are not completely scanned
in a particular pass.
The sizes of the blocks and areas has been the result of some investigation
@ -2797,4 +2797,4 @@ public final class SparseBitSet implements Cloneable, Serializable {
* Word and block <b>xor</b> strategy.
*/
protected transient XorStrategy xorStrategy;
}
}

View File

@ -1,81 +0,0 @@
package com.boydti.fawe.object.extent;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.function.operation.Operation;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
public class EmptyExtent implements Extent {
public EmptyExtent() {
}
public BlockVector3 getMinimumPoint() {
return BlockVector3.ZERO;
}
public BlockVector3 getMaximumPoint() {
return BlockVector3.ZERO;
}
public List<Entity> getEntities(Region region) {
return Collections.emptyList();
}
public List<Entity> getEntities() {
return Collections.emptyList();
}
@Nullable
public Entity createEntity(Location location, BaseEntity entity) {
return null;
}
@Override
public BaseBlock getFullBlock(BlockVector3 position) {
return EditSession.nullBlock.toBaseBlock();
}
@Override
public BlockState getLazyBlock(BlockVector3 position) {
return EditSession.nullBlock;
}
@Nullable
public BiomeType getBiome(BlockVector2 position) {
return null;
}
@Override
public boolean setBlock(BlockVector3 position, BlockStateHolder block) throws WorldEditException {
return false;
}
@Override
public boolean setBiome(BlockVector2 position, BiomeType biome) {
return false;
}
@Override
public boolean setBiome(int x, int y, int z, BiomeType biome) {
return false;
}
@Nullable
public Operation commit() {
return null;
}
}

View File

@ -3,11 +3,13 @@ package com.boydti.fawe.object.extent;
import com.boydti.fawe.object.FaweQueue;
import com.boydti.fawe.object.HasFaweQueue;
import com.boydti.fawe.util.ReflectionUtils;
import com.sk89q.jnbt.*;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.DoubleTag;
import com.sk89q.jnbt.FloatTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.WorldEditException;
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.AbstractDelegateExtent;
@ -17,23 +19,26 @@ import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FastWorldEditExtent extends AbstractDelegateExtent implements HasFaweQueue {
private final World world;
private FaweQueue queue;
private final int maxY;
public FastWorldEditExtent(final World world, FaweQueue queue) {
super(queue);
this.world = world;
this.queue = queue;
this.maxY = world.getMaxY();
}
public FaweQueue getQueue() {
@ -112,7 +117,7 @@ public class FastWorldEditExtent extends AbstractDelegateExtent implements HasFa
public <B extends BlockStateHolder<B>> boolean setBlock(final BlockVector3 location, final B block) throws WorldEditException {
return setBlock(location.getBlockX(), location.getBlockY(), location.getBlockZ(), block);
}
@Override
@ -129,10 +134,9 @@ public class FastWorldEditExtent extends AbstractDelegateExtent implements HasFa
public BlockState getLazyBlock(int x, int y, int z) {
int combinedId4Data = queue.getCombinedId4Data(x, y, z, 0);
BlockType type = BlockTypes.getFromStateId(combinedId4Data);
BlockState state = type.withStateId(combinedId4Data);
return state;
return type.withStateId(combinedId4Data);
}
@Override
public BaseBlock getFullBlock(BlockVector3 pos) {
int combinedId4Data = queue.getCombinedId4Data(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ(), 0);

View File

@ -3,7 +3,6 @@ package com.boydti.fawe.object.extent;
import com.boydti.fawe.config.BBC;
import com.boydti.fawe.object.FaweLimit;
import com.boydti.fawe.util.WEManager;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
@ -16,6 +15,7 @@ import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.Collection;
import javax.annotation.Nullable;
@ -110,14 +110,14 @@ public abstract class FaweRegionExtent extends ResettableExtent {
}
return super.getBiome(position);
}
@Override
public BaseBlock getFullBlock(BlockVector3 position) {
if (!contains(position)) {
if (!limit.MAX_FAILS()) {
WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION);
}
return EditSession.nullBlock.toBaseBlock();
return BlockTypes.AIR.getDefaultState().toBaseBlock();
}
return super.getFullBlock(position);
}
@ -128,7 +128,7 @@ public abstract class FaweRegionExtent extends ResettableExtent {
if (!limit.MAX_FAILS()) {
WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION);
}
return EditSession.nullBlock;
return BlockTypes.AIR.getDefaultState();
}
return super.getBlock(position);
}
@ -139,7 +139,7 @@ public abstract class FaweRegionExtent extends ResettableExtent {
if (!limit.MAX_FAILS()) {
WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION);
}
return EditSession.nullBlock;
return BlockTypes.AIR.getDefaultState();
}
return super.getLazyBlock(position);
}
@ -150,7 +150,7 @@ public abstract class FaweRegionExtent extends ResettableExtent {
if (!limit.MAX_FAILS()) {
WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_OUTSIDE_REGION);
}
return EditSession.nullBlock;
return BlockTypes.AIR.getDefaultState();
}
return super.getLazyBlock(x, y, z);
}

View File

@ -6,6 +6,7 @@ import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.regions.Region;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
public class HeightBoundExtent extends FaweRegionExtent {
@ -35,6 +36,6 @@ public class HeightBoundExtent extends FaweRegionExtent {
@Override
public Collection<Region> getRegions() {
return Arrays.asList(new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, min, max, Integer.MIN_VALUE, Integer.MAX_VALUE));
return Collections.singletonList(new RegionWrapper(Integer.MIN_VALUE, Integer.MAX_VALUE, min, max, Integer.MIN_VALUE, Integer.MAX_VALUE));
}
}

View File

@ -2,7 +2,6 @@ package com.boydti.fawe.object.extent;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.function.pattern.Pattern;
import com.sk89q.worldedit.math.BlockVector3;
@ -20,4 +19,4 @@ public class PatternTransform extends ResettableExtent {
public boolean setBlock(BlockVector3 location, BlockStateHolder block) throws WorldEditException {
return pattern.apply(getExtent(), location, location);
}
}
}

View File

@ -42,8 +42,7 @@ public class PositionTransformExtent extends ResettableExtent {
mutable.mutY(((pos.getY() - min.getY())));
mutable.mutZ(((pos.getZ() - min.getZ())));
MutableVector3 tmp = new MutableVector3(transform.apply(mutable.toVector3()));
BlockVector3 result = min.add(tmp.toBlockPoint());
return result;
return min.add(tmp.toBlockPoint());
}
@Override
@ -60,7 +59,7 @@ public class PositionTransformExtent extends ResettableExtent {
public BlockState getBlock(BlockVector3 position) {
return super.getBlock(getPos(position));
}
@Override
public BaseBlock getFullBlock(BlockVector3 position) {
return super.getFullBlock(getPos(position));

View File

@ -3,8 +3,6 @@ package com.boydti.fawe.object.extent;
import com.boydti.fawe.config.BBC;
import com.boydti.fawe.object.FaweLimit;
import com.boydti.fawe.util.WEManager;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
@ -18,6 +16,7 @@ import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockTypes;
import java.util.List;
@ -66,17 +65,17 @@ public class ProcessedWEExtent extends AbstractDelegateExtent {
public BlockState getLazyBlock(int x, int y, int z) {
if (!limit.MAX_CHECKS()) {
WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_MAX_CHECKS);
return EditSession.nullBlock;
return BlockTypes.AIR.getDefaultState();
} else {
return extent.getLazyBlock(x, y, z);
}
}
@Override
public BaseBlock getFullBlock(BlockVector3 pos) {
if (!limit.MAX_CHECKS()) {
WEManager.IMP.cancelEditSafe(this, BBC.WORLDEDIT_CANCEL_REASON_MAX_CHECKS);
return EditSession.nullBlock.toBaseBlock();
return BlockTypes.AIR.getDefaultState().toBaseBlock();
} else {
return extent.getFullBlock(pos);
}

View File

@ -5,7 +5,6 @@ import com.boydti.fawe.object.random.SimpleRandom;
import com.boydti.fawe.object.random.TrueRandom;
import com.sk89q.worldedit.extent.AbstractDelegateExtent;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.function.pattern.RandomPattern;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
@ -80,4 +79,4 @@ public class RandomTransform extends SelectTransform {
public RandomCollection<ResettableExtent> getCollection() {
return collection;
}
}
}

View File

@ -5,6 +5,7 @@ import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.regions.Region;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
public class SingleRegionExtent extends FaweRegionExtent {
@ -32,6 +33,6 @@ public class SingleRegionExtent extends FaweRegionExtent {
@Override
public Collection<Region> getRegions() {
return Arrays.asList(region);
return Collections.singletonList(region);
}
}

View File

@ -1,6 +1,5 @@
package com.boydti.fawe.object.extent;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.extent.AbstractDelegateExtent;
@ -9,11 +8,11 @@ import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.registry.BundledBlockData;
import com.sk89q.worldedit.world.block.BlockTypes;
public class TemporalExtent extends AbstractDelegateExtent {
private int x, y, z = Integer.MAX_VALUE;
private BlockStateHolder<?> block = EditSession.nullBlock;
private BlockStateHolder<?> block = BlockTypes.AIR.getDefaultState();
private int bx, bz = Integer.MAX_VALUE;
private BiomeType biome = null;
@ -72,7 +71,7 @@ public class TemporalExtent extends AbstractDelegateExtent {
}
return super.getLazyBlock(x, y, z);
}
@Override
public BaseBlock getFullBlock(BlockVector3 position) {
if (position.getX() == x && position.getY() == y && position.getZ() == z) {

View File

@ -16,17 +16,14 @@ public class TransformExtent extends BlockTransformExtent {
private final MutableBlockVector3 mutable = new MutableBlockVector3();
private BlockVector3 min;
private int maxy;
public TransformExtent(Extent parent) {
super(parent);
this.maxy = parent.getMaximumPoint().getBlockY();
}
@Override
public ResettableExtent setExtent(Extent extent) {
min = null;
maxy = extent.getMaximumPoint().getBlockY();
return super.setExtent(extent);
}
@ -91,7 +88,7 @@ public class TransformExtent extends BlockTransformExtent {
public BlockState getBlock(BlockVector3 position) {
return transform(super.getBlock(getPos(position)));
}
@Override
public BaseBlock getFullBlock(BlockVector3 position) {
return transform(super.getFullBlock(getPos(position)));

View File

@ -1,206 +0,0 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.boydti.fawe.object.io.zstd;
import static com.boydti.fawe.object.io.zstd.UnsafeUtil.UNSAFE;
import static com.boydti.fawe.object.io.zstd.Util.highestBit;
import static com.boydti.fawe.object.io.zstd.Util.verify;
import static com.boydti.fawe.object.io.zstd.ZstdFrameDecompressor.SIZE_OF_LONG;
/**
* Bit streams are encoded as a byte-aligned little-endian stream. Thus, bits are laid out
* in the following manner, and the stream is read from right to left.
* <p>
* <p>
* ... [16 17 18 19 20 21 22 23] [8 9 10 11 12 13 14 15] [0 1 2 3 4 5 6 7]
*/
class BitStream
{
private BitStream()
{
}
public static boolean isEndOfStream(long startAddress, long currentAddress, int bitsConsumed)
{
return startAddress == currentAddress && bitsConsumed == Long.SIZE;
}
static long readTail(Object inputBase, long inputAddress, int inputSize)
{
long bits = UNSAFE.getByte(inputBase, inputAddress) & 0xFF;
switch (inputSize) {
case 7:
bits |= (UNSAFE.getByte(inputBase, inputAddress + 6) & 0xFFL) << 48;
case 6:
bits |= (UNSAFE.getByte(inputBase, inputAddress + 5) & 0xFFL) << 40;
case 5:
bits |= (UNSAFE.getByte(inputBase, inputAddress + 4) & 0xFFL) << 32;
case 4:
bits |= (UNSAFE.getByte(inputBase, inputAddress + 3) & 0xFFL) << 24;
case 3:
bits |= (UNSAFE.getByte(inputBase, inputAddress + 2) & 0xFFL) << 16;
case 2:
bits |= (UNSAFE.getByte(inputBase, inputAddress + 1) & 0xFFL) << 8;
}
return bits;
}
/**
* @return numberOfBits in the low order bits of a long
*/
public static long peekBits(int bitsConsumed, long bitContainer, int numberOfBits)
{
return (((bitContainer << bitsConsumed) >>> 1) >>> (63 - numberOfBits));
}
/**
* numberOfBits must be > 0
*
* @return numberOfBits in the low order bits of a long
*/
public static long peekBitsFast(int bitsConsumed, long bitContainer, int numberOfBits)
{
return ((bitContainer << bitsConsumed) >>> (64 - numberOfBits));
}
static class Initializer
{
private final Object inputBase;
private final long startAddress;
private final long endAddress;
private long bits;
private long currentAddress;
private int bitsConsumed;
public Initializer(Object inputBase, long startAddress, long endAddress)
{
this.inputBase = inputBase;
this.startAddress = startAddress;
this.endAddress = endAddress;
}
public long getBits()
{
return bits;
}
public long getCurrentAddress()
{
return currentAddress;
}
public int getBitsConsumed()
{
return bitsConsumed;
}
public void initialize()
{
verify(endAddress - startAddress >= 1, startAddress, "Bitstream is empty");
int lastByte = UNSAFE.getByte(inputBase, endAddress - 1) & 0xFF;
verify(lastByte != 0, endAddress, "Bitstream end mark not present");
bitsConsumed = SIZE_OF_LONG - highestBit(lastByte);
int inputSize = (int) (endAddress - startAddress);
if (inputSize >= SIZE_OF_LONG) { /* normal case */
currentAddress = endAddress - SIZE_OF_LONG;
bits = UNSAFE.getLong(inputBase, currentAddress);
}
else {
currentAddress = startAddress;
bits = readTail(inputBase, startAddress, inputSize);
bitsConsumed += (SIZE_OF_LONG - inputSize) * 8;
}
}
}
static final class Loader
{
private final Object inputBase;
private final long startAddress;
private long bits;
private long currentAddress;
private int bitsConsumed;
private boolean overflow;
public Loader(Object inputBase, long startAddress, long currentAddress, long bits, int bitsConsumed)
{
this.inputBase = inputBase;
this.startAddress = startAddress;
this.bits = bits;
this.currentAddress = currentAddress;
this.bitsConsumed = bitsConsumed;
}
public long getBits()
{
return bits;
}
public long getCurrentAddress()
{
return currentAddress;
}
public int getBitsConsumed()
{
return bitsConsumed;
}
public boolean isOverflow()
{
return overflow;
}
public boolean load()
{
if (bitsConsumed > 64) {
overflow = true;
return true;
}
else if (currentAddress == startAddress) {
return true;
}
int bytes = bitsConsumed >>> 3; // divide by 8
if (currentAddress >= startAddress + SIZE_OF_LONG) {
if (bytes > 0) {
currentAddress -= bytes;
bits = UNSAFE.getLong(inputBase, currentAddress);
}
bitsConsumed &= 0b111;
}
else if (currentAddress - bytes < startAddress) {
bytes = (int) (currentAddress - startAddress);
currentAddress = startAddress;
bitsConsumed -= bytes * SIZE_OF_LONG;
bits = UNSAFE.getLong(inputBase, startAddress);
return true;
}
else {
currentAddress -= bytes;
bitsConsumed -= bytes * SIZE_OF_LONG;
bits = UNSAFE.getLong(inputBase, currentAddress);
}
return false;
}
}
}

View File

@ -1,176 +0,0 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.boydti.fawe.object.io.zstd;
import static com.boydti.fawe.object.io.zstd.BitStream.peekBits;
import static com.boydti.fawe.object.io.zstd.FseTableReader.FSE_MAX_SYMBOL_VALUE;
import static com.boydti.fawe.object.io.zstd.UnsafeUtil.UNSAFE;
import static sun.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET;
class FiniteStateEntropy
{
private static final int MAX_TABLE_LOG = 12;
private final FiniteStateEntropy.Table table;
private final FseTableReader reader = new FseTableReader();
public FiniteStateEntropy(int maxLog)
{
table = new FiniteStateEntropy.Table(maxLog);
}
public int decompress(final Object inputBase, final long inputAddress, final long inputLimit, byte[] weights)
{
long input = inputAddress;
input += reader.readFseTable(table, inputBase, input, inputLimit, FSE_MAX_SYMBOL_VALUE, MAX_TABLE_LOG);
final Object outputBase = weights;
final long outputAddress = ARRAY_BYTE_BASE_OFFSET;
final long outputLimit = outputAddress + weights.length;
long output = outputAddress;
// initialize bit stream
BitStream.Initializer initializer = new BitStream.Initializer(inputBase, input, inputLimit);
initializer.initialize();
int bitsConsumed = initializer.getBitsConsumed();
long currentAddress = initializer.getCurrentAddress();
long bits = initializer.getBits();
// initialize first FSE stream
int state1 = (int) peekBits(bitsConsumed, bits, table.log2Size);
bitsConsumed += table.log2Size;
BitStream.Loader loader = new BitStream.Loader(inputBase, input, currentAddress, bits, bitsConsumed);
loader.load();
bits = loader.getBits();
bitsConsumed = loader.getBitsConsumed();
currentAddress = loader.getCurrentAddress();
// initialize second FSE stream
int state2 = (int) peekBits(bitsConsumed, bits, table.log2Size);
bitsConsumed += table.log2Size;
loader = new BitStream.Loader(inputBase, input, currentAddress, bits, bitsConsumed);
loader.load();
bits = loader.getBits();
bitsConsumed = loader.getBitsConsumed();
currentAddress = loader.getCurrentAddress();
byte[] symbols = table.symbol;
byte[] numbersOfBits = table.numberOfBits;
int[] newStates = table.newState;
// decode 4 symbols per loop
while (output < outputLimit) {
int numberOfBits;
UNSAFE.putByte(outputBase, output, symbols[state1]);
numberOfBits = numbersOfBits[state1];
state1 = (int) (newStates[state1] + peekBits(bitsConsumed, bits, numberOfBits));
bitsConsumed += numberOfBits;
UNSAFE.putByte(outputBase, output + 1, symbols[state2]);
numberOfBits = numbersOfBits[state2];
state2 = (int) (newStates[state2] + peekBits(bitsConsumed, bits, numberOfBits));
bitsConsumed += numberOfBits;
UNSAFE.putByte(outputBase, output + 2, symbols[state1]);
numberOfBits = numbersOfBits[state1];
state1 = (int) (newStates[state1] + peekBits(bitsConsumed, bits, numberOfBits));
bitsConsumed += numberOfBits;
UNSAFE.putByte(outputBase, output + 3, symbols[state2]);
numberOfBits = numbersOfBits[state2];
state2 = (int) (newStates[state2] + peekBits(bitsConsumed, bits, numberOfBits));
bitsConsumed += numberOfBits;
output += ZstdFrameDecompressor.SIZE_OF_INT;
loader = new BitStream.Loader(inputBase, input, currentAddress, bits, bitsConsumed);
boolean done = loader.load();
bitsConsumed = loader.getBitsConsumed();
bits = loader.getBits();
currentAddress = loader.getCurrentAddress();
if (done) {
break;
}
}
while (true) {
UNSAFE.putByte(outputBase, output++, symbols[state1]);
int numberOfBits = numbersOfBits[state1];
state1 = (int) (newStates[state1] + peekBits(bitsConsumed, bits, numberOfBits));
bitsConsumed += numberOfBits;
loader = new BitStream.Loader(inputBase, input, currentAddress, bits, bitsConsumed);
loader.load();
bitsConsumed = loader.getBitsConsumed();
bits = loader.getBits();
currentAddress = loader.getCurrentAddress();
if (loader.isOverflow()) {
UNSAFE.putByte(outputBase, output++, symbols[state2]);
break;
}
UNSAFE.putByte(outputBase, output++, symbols[state2]);
int numberOfBits1 = numbersOfBits[state2];
state2 = (int) (newStates[state2] + peekBits(bitsConsumed, bits, numberOfBits1));
bitsConsumed += numberOfBits1;
loader = new BitStream.Loader(inputBase, input, currentAddress, bits, bitsConsumed);
loader.load();
bitsConsumed = loader.getBitsConsumed();
bits = loader.getBits();
currentAddress = loader.getCurrentAddress();
if (loader.isOverflow()) {
UNSAFE.putByte(outputBase, output++, symbols[state1]);
break;
}
}
return (int) (output - outputAddress);
}
public static final class Table
{
int log2Size;
final int[] newState;
final byte[] symbol;
final byte[] numberOfBits;
public Table(int log2Size)
{
int size = 1 << log2Size;
newState = new int[size];
symbol = new byte[size];
numberOfBits = new byte[size];
}
public Table(int log2Size, int[] newState, byte[] symbol, byte[] numberOfBits)
{
int size = 1 << log2Size;
if (newState.length != size || symbol.length != size || numberOfBits.length != size) {
throw new IllegalArgumentException("Expected arrays to match provided size");
}
this.log2Size = log2Size;
this.newState = newState;
this.symbol = symbol;
this.numberOfBits = numberOfBits;
}
}
}

View File

@ -1,182 +0,0 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.boydti.fawe.object.io.zstd;
import static com.boydti.fawe.object.io.zstd.UnsafeUtil.UNSAFE;
import static com.boydti.fawe.object.io.zstd.Util.highestBit;
import static com.boydti.fawe.object.io.zstd.Util.verify;
class FseTableReader
{
private static final int FSE_MIN_TABLE_LOG = 5;
public static final int FSE_MAX_SYMBOL_VALUE = 255;
private final short[] nextSymbol = new short[FSE_MAX_SYMBOL_VALUE + 1];
private final short[] normalizedCounters = new short[FSE_MAX_SYMBOL_VALUE + 1];
public int readFseTable(FiniteStateEntropy.Table table, Object inputBase, long inputAddress, long inputLimit, int maxSymbol, int maxTableLog)
{
// read table headers
long input = inputAddress;
verify(inputLimit - inputAddress >= 4, input, "Not enough input bytes");
int threshold;
int symbolNumber = 0;
boolean previousIsZero = false;
int bitStream = UNSAFE.getInt(inputBase, input);
int tableLog = (bitStream & 0xF) + FSE_MIN_TABLE_LOG;
int numberOfBits = tableLog + 1;
bitStream >>>= 4;
int bitCount = 4;
verify(tableLog <= maxTableLog, input, "FSE table size exceeds maximum allowed size");
int remaining = (1 << tableLog) + 1;
threshold = 1 << tableLog;
while (remaining > 1 && symbolNumber <= maxSymbol) {
if (previousIsZero) {
int n0 = symbolNumber;
while ((bitStream & 0xFFFF) == 0xFFFF) {
n0 += 24;
if (input < inputLimit - 5) {
input += 2;
bitStream = (UNSAFE.getInt(inputBase, input) >>> bitCount);
}
else {
// end of bit stream
bitStream >>>= 16;
bitCount += 16;
}
}
while ((bitStream & 3) == 3) {
n0 += 3;
bitStream >>>= 2;
bitCount += 2;
}
n0 += bitStream & 3;
bitCount += 2;
verify(n0 <= maxSymbol, input, "Symbol larger than max value");
while (symbolNumber < n0) {
normalizedCounters[symbolNumber++] = 0;
}
if ((input <= inputLimit - 7) || (input + (bitCount >>> 3) <= inputLimit - 4)) {
input += bitCount >>> 3;
bitCount &= 7;
bitStream = UNSAFE.getInt(inputBase, input) >>> bitCount;
}
else {
bitStream >>>= 2;
}
}
short max = (short) ((2 * threshold - 1) - remaining);
short count;
if ((bitStream & (threshold - 1)) < max) {
count = (short) (bitStream & (threshold - 1));
bitCount += numberOfBits - 1;
}
else {
count = (short) (bitStream & (2 * threshold - 1));
if (count >= threshold) {
count -= max;
}
bitCount += numberOfBits;
}
count--; // extra accuracy
remaining -= Math.abs(count);
normalizedCounters[symbolNumber++] = count;
previousIsZero = count == 0;
while (remaining < threshold) {
numberOfBits--;
threshold >>>= 1;
}
if ((input <= inputLimit - 7) || (input + (bitCount >> 3) <= inputLimit - 4)) {
input += bitCount >>> 3;
bitCount &= 7;
}
else {
bitCount -= (int) (8 * (inputLimit - 4 - input));
input = inputLimit - 4;
}
bitStream = UNSAFE.getInt(inputBase, input) >>> (bitCount & 31);
}
verify(remaining == 1 && bitCount <= 32, input, "Input is corrupted");
maxSymbol = symbolNumber - 1;
verify(maxSymbol <= FSE_MAX_SYMBOL_VALUE, input, "Max symbol value too large (too many symbols for FSE)");
input += (bitCount + 7) >> 3;
// populate decoding table
int symbolCount = maxSymbol + 1;
int tableSize = 1 << tableLog;
int highThreshold = tableSize - 1;
table.log2Size = tableLog;
for (byte symbol = 0; symbol < symbolCount; symbol++) {
if (normalizedCounters[symbol] == -1) {
table.symbol[highThreshold--] = symbol;
nextSymbol[symbol] = 1;
}
else {
nextSymbol[symbol] = normalizedCounters[symbol];
}
}
// spread symbols
int tableMask = tableSize - 1;
int step = (tableSize >>> 1) + (tableSize >>> 3) + 3;
int position = 0;
for (byte symbol = 0; symbol < symbolCount; symbol++) {
for (int i = 0; i < normalizedCounters[symbol]; i++) {
table.symbol[position] = symbol;
do {
position = (position + step) & tableMask;
}
while (position > highThreshold);
}
}
// position must reach all cells once, otherwise normalizedCounter is incorrect
verify(position == 0, input, "Input is corrupted");
for (int i = 0; i < tableSize; i++) {
byte symbol = table.symbol[i];
short nextState = nextSymbol[symbol]++;
table.numberOfBits[i] = (byte) (tableLog - highestBit(nextState));
table.newState[i] = (short) ((nextState << table.numberOfBits[i]) - tableSize);
}
return (int) (input - inputAddress);
}
public static void buildRleTable(FiniteStateEntropy.Table table, byte value)
{
table.log2Size = 0;
table.symbol[0] = value;
table.newState[0] = 0;
table.numberOfBits[0] = 0;
}
}

View File

@ -1,317 +0,0 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.boydti.fawe.object.io.zstd;
import java.util.Arrays;
import static com.boydti.fawe.object.io.zstd.BitStream.isEndOfStream;
import static com.boydti.fawe.object.io.zstd.BitStream.peekBitsFast;
import static com.boydti.fawe.object.io.zstd.UnsafeUtil.UNSAFE;
import static com.boydti.fawe.object.io.zstd.Util.isPowerOf2;
import static com.boydti.fawe.object.io.zstd.Util.verify;
import static com.boydti.fawe.object.io.zstd.ZstdFrameDecompressor.SIZE_OF_INT;
import static com.boydti.fawe.object.io.zstd.ZstdFrameDecompressor.SIZE_OF_SHORT;
class Huffman
{
private static final int MAX_SYMBOL = 255;
private static final int MAX_TABLE_LOG = 12;
// stats
private final byte[] weights = new byte[MAX_SYMBOL + 1];
private final int[] ranks = new int[MAX_TABLE_LOG + 1];
// table
private int tableLog = -1;
private final byte[] symbols = new byte[1 << MAX_TABLE_LOG];
private final byte[] numbersOfBits = new byte[1 << MAX_TABLE_LOG];
private final FiniteStateEntropy finiteStateEntropy = new FiniteStateEntropy(6);
public boolean isLoaded()
{
return tableLog != -1;
}
public int readTable(final Object inputBase, final long inputAddress, final int size)
{
Arrays.fill(ranks, 0);
long input = inputAddress;
// read table header
verify(size > 0, input, "Not enough input bytes");
int inputSize = UNSAFE.getByte(inputBase, input++) & 0xFF;
int outputSize;
if (inputSize >= 128) {
outputSize = inputSize - 127;
inputSize = ((outputSize + 1) / 2);
verify(inputSize + 1 <= size, input, "Not enough input bytes");
verify(outputSize <= MAX_SYMBOL + 1, input, "Input is corrupted");
for (int i = 0; i < outputSize; i += 2) {
int value = UNSAFE.getByte(inputBase, input + i / 2) & 0xFF;
weights[i] = (byte) (value >>> 4);
weights[i + 1] = (byte) (value & 0b1111);
}
}
else {
verify(inputSize + 1 <= size, input, "Not enough input bytes");
outputSize = finiteStateEntropy.decompress(inputBase, input, input + inputSize, weights);
}
int totalWeight = 0;
for (int i = 0; i < outputSize; i++) {
ranks[weights[i]]++;
totalWeight += (1 << weights[i]) >> 1; // TODO same as 1 << (weights[n] - 1)?
}
verify(totalWeight != 0, input, "Input is corrupted");
tableLog = Util.highestBit(totalWeight) + 1;
verify(tableLog <= MAX_TABLE_LOG, input, "Input is corrupted");
int total = 1 << tableLog;
int rest = total - totalWeight;
verify(isPowerOf2(rest), input, "Input is corrupted");
int lastWeight = Util.highestBit(rest) + 1;
weights[outputSize] = (byte) lastWeight;
ranks[lastWeight]++;
int numberOfSymbols = outputSize + 1;
// populate table
int nextRankStart = 0;
for (int i = 1; i < tableLog + 1; ++i) {
int current = nextRankStart;
nextRankStart += ranks[i] << (i - 1);
ranks[i] = current;
}
for (int n = 0; n < numberOfSymbols; n++) {
int weight = weights[n];
int length = (1 << weight) >> 1; // TODO: 1 << (weight - 1) ??
byte symbol = (byte) n;
byte numberOfBits = (byte) (tableLog + 1 - weight);
for (int i = ranks[weight]; i < ranks[weight] + length; i++) {
symbols[i] = symbol;
numbersOfBits[i] = numberOfBits;
}
ranks[weight] += length;
}
verify(ranks[1] >= 2 && (ranks[1] & 1) == 0, input, "Input is corrupted");
return inputSize + 1;
}
public void decodeSingleStream(final Object inputBase, final long inputAddress, final long inputLimit, final Object outputBase, final long outputAddress, final long outputLimit)
{
BitStream.Initializer initializer = new BitStream.Initializer(inputBase, inputAddress, inputLimit);
initializer.initialize();
long bits = initializer.getBits();
int bitsConsumed = initializer.getBitsConsumed();
long currentAddress = initializer.getCurrentAddress();
int tableLog = this.tableLog;
byte[] numbersOfBits = this.numbersOfBits;
byte[] symbols = this.symbols;
// 4 symbols at a time
long output = outputAddress;
long fastOutputLimit = outputLimit - 4;
while (output < fastOutputLimit) {
BitStream.Loader loader = new BitStream.Loader(inputBase, inputAddress, currentAddress, bits, bitsConsumed);
boolean done = loader.load();
bits = loader.getBits();
bitsConsumed = loader.getBitsConsumed();
currentAddress = loader.getCurrentAddress();
if (done) {
break;
}
bitsConsumed = decodeSymbol(outputBase, output, bits, bitsConsumed, tableLog, numbersOfBits, symbols);
bitsConsumed = decodeSymbol(outputBase, output + 1, bits, bitsConsumed, tableLog, numbersOfBits, symbols);
bitsConsumed = decodeSymbol(outputBase, output + 2, bits, bitsConsumed, tableLog, numbersOfBits, symbols);
bitsConsumed = decodeSymbol(outputBase, output + 3, bits, bitsConsumed, tableLog, numbersOfBits, symbols);
output += SIZE_OF_INT;
}
decodeTail(inputBase, inputAddress, currentAddress, bitsConsumed, bits, outputBase, output, outputLimit);
}
public void decode4Streams(final Object inputBase, final long inputAddress, final long inputLimit, final Object outputBase, final long outputAddress, final long outputLimit)
{
verify(inputLimit - inputAddress >= 10, inputAddress, "Input is corrupted"); // jump table + 1 byte per stream
long start1 = inputAddress + 3 * SIZE_OF_SHORT; // for the shorts we read below
long start2 = start1 + (UNSAFE.getShort(inputBase, inputAddress) & 0xFFFF);
long start3 = start2 + (UNSAFE.getShort(inputBase, inputAddress + 2) & 0xFFFF);
long start4 = start3 + (UNSAFE.getShort(inputBase, inputAddress + 4) & 0xFFFF);
BitStream.Initializer initializer = new BitStream.Initializer(inputBase, start1, start2);
initializer.initialize();
int stream1bitsConsumed = initializer.getBitsConsumed();
long stream1currentAddress = initializer.getCurrentAddress();
long stream1bits = initializer.getBits();
initializer = new BitStream.Initializer(inputBase, start2, start3);
initializer.initialize();
int stream2bitsConsumed = initializer.getBitsConsumed();
long stream2currentAddress = initializer.getCurrentAddress();
long stream2bits = initializer.getBits();
initializer = new BitStream.Initializer(inputBase, start3, start4);
initializer.initialize();
int stream3bitsConsumed = initializer.getBitsConsumed();
long stream3currentAddress = initializer.getCurrentAddress();
long stream3bits = initializer.getBits();
initializer = new BitStream.Initializer(inputBase, start4, inputLimit);
initializer.initialize();
int stream4bitsConsumed = initializer.getBitsConsumed();
long stream4currentAddress = initializer.getCurrentAddress();
long stream4bits = initializer.getBits();
int segmentSize = (int) ((outputLimit - outputAddress + 3) / 4);
long outputStart2 = outputAddress + segmentSize;
long outputStart3 = outputStart2 + segmentSize;
long outputStart4 = outputStart3 + segmentSize;
long output1 = outputAddress;
long output2 = outputStart2;
long output3 = outputStart3;
long output4 = outputStart4;
long fastOutputLimit = outputLimit - 7;
int tableLog = this.tableLog;
byte[] numbersOfBits = this.numbersOfBits;
byte[] symbols = this.symbols;
while (output4 < fastOutputLimit) {
stream1bitsConsumed = decodeSymbol(outputBase, output1, stream1bits, stream1bitsConsumed, tableLog, numbersOfBits, symbols);
stream2bitsConsumed = decodeSymbol(outputBase, output2, stream2bits, stream2bitsConsumed, tableLog, numbersOfBits, symbols);
stream3bitsConsumed = decodeSymbol(outputBase, output3, stream3bits, stream3bitsConsumed, tableLog, numbersOfBits, symbols);
stream4bitsConsumed = decodeSymbol(outputBase, output4, stream4bits, stream4bitsConsumed, tableLog, numbersOfBits, symbols);
stream1bitsConsumed = decodeSymbol(outputBase, output1 + 1, stream1bits, stream1bitsConsumed, tableLog, numbersOfBits, symbols);
stream2bitsConsumed = decodeSymbol(outputBase, output2 + 1, stream2bits, stream2bitsConsumed, tableLog, numbersOfBits, symbols);
stream3bitsConsumed = decodeSymbol(outputBase, output3 + 1, stream3bits, stream3bitsConsumed, tableLog, numbersOfBits, symbols);
stream4bitsConsumed = decodeSymbol(outputBase, output4 + 1, stream4bits, stream4bitsConsumed, tableLog, numbersOfBits, symbols);
stream1bitsConsumed = decodeSymbol(outputBase, output1 + 2, stream1bits, stream1bitsConsumed, tableLog, numbersOfBits, symbols);
stream2bitsConsumed = decodeSymbol(outputBase, output2 + 2, stream2bits, stream2bitsConsumed, tableLog, numbersOfBits, symbols);
stream3bitsConsumed = decodeSymbol(outputBase, output3 + 2, stream3bits, stream3bitsConsumed, tableLog, numbersOfBits, symbols);
stream4bitsConsumed = decodeSymbol(outputBase, output4 + 2, stream4bits, stream4bitsConsumed, tableLog, numbersOfBits, symbols);
stream1bitsConsumed = decodeSymbol(outputBase, output1 + 3, stream1bits, stream1bitsConsumed, tableLog, numbersOfBits, symbols);
stream2bitsConsumed = decodeSymbol(outputBase, output2 + 3, stream2bits, stream2bitsConsumed, tableLog, numbersOfBits, symbols);
stream3bitsConsumed = decodeSymbol(outputBase, output3 + 3, stream3bits, stream3bitsConsumed, tableLog, numbersOfBits, symbols);
stream4bitsConsumed = decodeSymbol(outputBase, output4 + 3, stream4bits, stream4bitsConsumed, tableLog, numbersOfBits, symbols);
output1 += SIZE_OF_INT;
output2 += SIZE_OF_INT;
output3 += SIZE_OF_INT;
output4 += SIZE_OF_INT;
BitStream.Loader loader = new BitStream.Loader(inputBase, start1, stream1currentAddress, stream1bits, stream1bitsConsumed);
boolean done = loader.load();
stream1bitsConsumed = loader.getBitsConsumed();
stream1bits = loader.getBits();
stream1currentAddress = loader.getCurrentAddress();
if (done) {
break;
}
loader = new BitStream.Loader(inputBase, start2, stream2currentAddress, stream2bits, stream2bitsConsumed);
done = loader.load();
stream2bitsConsumed = loader.getBitsConsumed();
stream2bits = loader.getBits();
stream2currentAddress = loader.getCurrentAddress();
if (done) {
break;
}
loader = new BitStream.Loader(inputBase, start3, stream3currentAddress, stream3bits, stream3bitsConsumed);
done = loader.load();
stream3bitsConsumed = loader.getBitsConsumed();
stream3bits = loader.getBits();
stream3currentAddress = loader.getCurrentAddress();
if (done) {
break;
}
loader = new BitStream.Loader(inputBase, start4, stream4currentAddress, stream4bits, stream4bitsConsumed);
done = loader.load();
stream4bitsConsumed = loader.getBitsConsumed();
stream4bits = loader.getBits();
stream4currentAddress = loader.getCurrentAddress();
if (done) {
break;
}
}
verify(output1 <= outputStart2 && output2 <= outputStart3 && output3 <= outputStart4, inputAddress, "Input is corrupted");
/// finish streams one by one
decodeTail(inputBase, start1, stream1currentAddress, stream1bitsConsumed, stream1bits, outputBase, output1, outputStart2);
decodeTail(inputBase, start2, stream2currentAddress, stream2bitsConsumed, stream2bits, outputBase, output2, outputStart3);
decodeTail(inputBase, start3, stream3currentAddress, stream3bitsConsumed, stream3bits, outputBase, output3, outputStart4);
decodeTail(inputBase, start4, stream4currentAddress, stream4bitsConsumed, stream4bits, outputBase, output4, outputLimit);
}
private void decodeTail(final Object inputBase, final long startAddress, long currentAddress, int bitsConsumed, long bits, final Object outputBase, long outputAddress, final long outputLimit)
{
int tableLog = this.tableLog;
byte[] numbersOfBits = this.numbersOfBits;
byte[] symbols = this.symbols;
// closer to the end
while (outputAddress < outputLimit) {
BitStream.Loader loader = new BitStream.Loader(inputBase, startAddress, currentAddress, bits, bitsConsumed);
boolean done = loader.load();
bitsConsumed = loader.getBitsConsumed();
bits = loader.getBits();
currentAddress = loader.getCurrentAddress();
if (done) {
break;
}
bitsConsumed = decodeSymbol(outputBase, outputAddress++, bits, bitsConsumed, tableLog, numbersOfBits, symbols);
}
// not more data in bit stream, so no need to reload
while (outputAddress < outputLimit) {
bitsConsumed = decodeSymbol(outputBase, outputAddress++, bits, bitsConsumed, tableLog, numbersOfBits, symbols);
}
verify(isEndOfStream(startAddress, currentAddress, bitsConsumed), startAddress, "Bit stream is not fully consumed");
}
private static int decodeSymbol(Object outputBase, long outputAddress, long bitContainer, int bitsConsumed, int tableLog, byte[] numbersOfBits, byte[] symbols)
{
int value = (int) peekBitsFast(bitsConsumed, bitContainer, tableLog);
UNSAFE.putByte(outputBase, outputAddress, symbols[value]);
return bitsConsumed + numbersOfBits[value];
}
}

View File

@ -1,71 +0,0 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.boydti.fawe.object.io.zstd;
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.nio.Buffer;
final class UnsafeUtil
{
public static final Unsafe UNSAFE;
private static final Field ADDRESS_ACCESSOR;
private UnsafeUtil() {}
static {
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
UNSAFE = (Unsafe) theUnsafe.get(null);
}
catch (Exception e) {
throw new RuntimeException(e);
}
try {
Field field = Buffer.class.getDeclaredField("address");
field.setAccessible(true);
ADDRESS_ACCESSOR = field;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public static long getAddress(Buffer buffer)
{
try {
return (long) ADDRESS_ACCESSOR.get(buffer);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -1,108 +0,0 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.boydti.fawe.object.io.zstd;
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.nio.ByteBuffer;
import static com.boydti.fawe.object.io.zstd.UnsafeUtil.getAddress;
import static sun.misc.Unsafe.ARRAY_BYTE_BASE_OFFSET;
public class ZstdDecompressor
{
private final ZstdFrameDecompressor decompressor = new ZstdFrameDecompressor();
public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength)
throws MalformedInputException
{
long inputAddress = ARRAY_BYTE_BASE_OFFSET + inputOffset;
long inputLimit = inputAddress + inputLength;
long outputAddress = ARRAY_BYTE_BASE_OFFSET + outputOffset;
long outputLimit = outputAddress + maxOutputLength;
return decompressor.decompress(input, inputAddress, inputLimit, output, outputAddress, outputLimit);
}
public void decompress(ByteBuffer input, ByteBuffer output)
throws MalformedInputException
{
Object inputBase;
long inputAddress;
long inputLimit;
if (input.isDirect()) {
inputBase = null;
long address = getAddress(input);
inputAddress = address + input.position();
inputLimit = address + input.limit();
}
else if (input.hasArray()) {
inputBase = input.array();
inputAddress = ARRAY_BYTE_BASE_OFFSET + input.arrayOffset() + input.position();
inputLimit = ARRAY_BYTE_BASE_OFFSET + input.arrayOffset() + input.limit();
}
else {
throw new IllegalArgumentException("Unsupported input ByteBuffer implementation " + input.getClass().getName());
}
Object outputBase;
long outputAddress;
long outputLimit;
if (output.isDirect()) {
outputBase = null;
long address = getAddress(output);
outputAddress = address + output.position();
outputLimit = address + output.limit();
}
else if (output.hasArray()) {
outputBase = output.array();
outputAddress = ARRAY_BYTE_BASE_OFFSET + output.arrayOffset() + output.position();
outputLimit = ARRAY_BYTE_BASE_OFFSET + output.arrayOffset() + output.limit();
}
else {
throw new IllegalArgumentException("Unsupported output ByteBuffer implementation " + output.getClass().getName());
}
// HACK: Assure JVM does not collect Slice wrappers while decompressing, since the
// collection may trigger freeing of the underlying memory resulting in a segfault
// There is no other known way to signal to the JVM that an object should not be
// collected in a block, and technically, the JVM is allowed to eliminate these locks.
synchronized (input) {
synchronized (output) {
int written = new ZstdFrameDecompressor().decompress(inputBase, inputAddress, inputLimit, outputBase, outputAddress, outputLimit);
output.position(output.position() + written);
}
}
}
public static long getDecompressedSize(byte[] input, int offset, int length)
{
int baseAddress = ARRAY_BYTE_BASE_OFFSET + offset;
return ZstdFrameDecompressor.getDecompressedSize(input, baseAddress, baseAddress + length);
}
}

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